Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): link hover previews for the editor (#2653)

Andrew Mikofalvy1eaa5bb57bff
diff --git a/.changeset/link-hover-previews.md b/.changeset/link-hover-previews.md
new file mode 100644
index 000000000..31a338de5
--- /dev/null
+++ b/.changeset/link-hover-previews.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Hovering a link in the editor now shows a preview card. Links to other documents in the project get a doc card — title, folder path, tags, last-edited time, backlink count, and a short excerpt — built entirely from the local index and file contents: on by default, no configuration, and nothing leaves the machine. This is a hover-behavior change for existing users: resolved internal links previously showed only the URL pill, which is still there with all its actions — the card renders alongside it.
+
+External links get an opt-in preview card showing the destination's site name, page title, description, and favicon. It is off by default and per machine: enable it from **Settings → This project → Link previews**, which sets `linkPreviews.enabled` in project-local config (never shared with collaborators). When enabled, hovering an external link sends that link's URL to the destination site to fetch preview metadata — one request per previewed link, with no cookies or credentials attached. The opt-in is enforced by the local server (with it off, no external request is made), results are cached locally, requests to private or internal addresses are refused, and any preview that can't be fetched quietly falls back to the plain URL pill.
diff --git a/bun.lock b/bun.lock
index 1e6e1bf6f..ad3a117c7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -399,6 +399,7 @@
"file-type": "^22.0.1",
"happy-dom": "^20.10.2",
"ignore": "^5.3.2",
+ "ipaddr.js": "^2.3.0",
"just-bash": "^2.14.3",
"mermaid": "^11.14.0",
"mrmime": "^2.0.1",
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index b2d367f8c..e6e1f8f87 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -50,6 +50,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi
| `search.semantic.model` | string | `"text-embedding-3-small"` | project-local | Embeddings model id. Must be served by the provider at `baseUrl`. Changing it re-embeds the corpus. |
| `search.semantic.dimensions` | number | (native) | project-local | Optional output vector size. Omit for the model's native size (1536 for `text-embedding-3-small`). Set a smaller value to shrink the on-disk cache, trading a little quality. |
| `search.semantic.similarityFloor` | number | (unset) | project-local | Optional hard cutoff (0–1): drops semantic matches whose cosine similarity is below it. Retrieval is rank-based, so most setups leave it unset; set it only for a provider/model whose cosine scale you know. |
+| `linkPreviews.enabled` | boolean | `false` | project-local | Show a rich preview card (site name, page title, description, favicon) when you hover an external link in the editor. Default off. **When on, hovering an external link sends that link's URL to the destination site** to fetch its preview metadata — outbound egress, one request per previewed link. Previews of links to other documents in the project are read from the local index with no network request and are always on. See [Link previews](#link-previews) below. |
If `.ok/config.yml` contains a key that has been removed from the schema, config load fails with an error naming the replacement — a stale key is never a silent no-op. `ok config migrate` (`--dry-run` to preview; `--scope project|user|both`) strips removed keys from your config files.
@@ -105,6 +106,18 @@ To turn it on (per machine):
The first semantic search kicks off a background embed of the corpus (cents for a whole vault with `text-embedding-3-small`); vectors are cached incrementally under `.ok/local/` and only changed docs re-embed. If the key is missing, the provider errors, or you're offline, search silently degrades to lexical — it never blocks or errors. Each MCP `search` response reports embedding coverage so an agent knows when vectors are still filling in.
+## Link previews
+
+Hovering a link in the editor shows a preview card. For **internal links** (other documents in your project) the card — title, folder, tags, last-edited time, backlink count, and a short excerpt — is built entirely from the local index and file contents: always on, no configuration, and nothing leaves the machine.
+
+For **external links**, an opt-in card shows the destination's site name, page title, description, and favicon. It is **off by default**.
+
+<Callout type="warn">
+ **URL egress.** When `linkPreviews.enabled` is on, hovering an external link sends that link's URL to the destination site — one metadata request per previewed link, from your machine, with no cookies or credentials attached. Responses are size- and time-capped, results are cached locally under `.ok/local/`, and requests that resolve to private or internal addresses are refused. Nothing else is sent: internal-link cards never touch the network.
+</Callout>
+
+To turn it on (per machine): the **Settings → This project → Link previews** toggle, which sets `linkPreviews.enabled: true` in project-local config (`<project>/.ok/local/config.yml`), picked up live by a running server. The opt-in is enforced by the local server, so with it off no external request is made. A preview that can't be fetched (offline, timeout, the site blocks it) quietly falls back to the plain URL pill. External previews are not currently available in the packaged desktop app — the toggle applies to the browser and `ok ui` surfaces.
+
## Verifying changes
The Settings pane validates `.ok/config.yml` against the schema as you edit and surfaces errors inline. The **Ignore patterns** section shows a live count of files each pattern matches, so you can confirm scope changes without leaving the editor.
diff --git a/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx b/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx
new file mode 100644
index 000000000..a68041ffd
--- /dev/null
+++ b/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx
@@ -0,0 +1,240 @@
+/**
+ * Tier-3 RTL mount tests for Settings → Link previews (external link-preview
+ * egress opt-in).
+ *
+ * Behavior is driven through the project-local ConfigContext (mocked binding +
+ * preference) and asserted on user-visible output: the toggle state, the egress
+ * confirmation gate, and the disable-is-immediate path. The exact CRDT patch is
+ * pinned so a payload-shape regression fails here rather than silently writing
+ * the wrong key.
+ */
+
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { Config, ConfigBinding } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+// Radix Dialog mounts a focus-trap that reaches for DOM globals the jsdom
+// preload doesn't expose. Hoist the same shims the sibling settings DOM tests
+// use.
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+let mockProjectLocalConfig: Config | null = null;
+let mockProjectLocalSynced = true;
+let mockProjectLocalBinding: ConfigBinding | null = null;
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ userBinding: null,
+ userSynced: false,
+ projectBinding: null,
+ projectLocalBinding: mockProjectLocalBinding,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ userConfig: null,
+ projectConfig: null,
+ projectLocalConfig: mockProjectLocalConfig,
+ projectLocalSynced: mockProjectLocalSynced,
+ merged: null,
+ }),
+}));
+
+const { LinkPreviewsSection } = await import('./LinkPreviewsSection');
+
+function configWithLinkPreviews(enabled: boolean): Config {
+ return { linkPreviews: { enabled } } as unknown as Config;
+}
+
+// Records every patch payload so tests can assert the exact CRDT write.
+function makeBinding(): { binding: ConfigBinding; calls: unknown[] } {
+ const calls: unknown[] = [];
+ const binding = {
+ current: () => ({}),
+ patch: (patch: unknown) => {
+ calls.push(patch);
+ return { ok: true, value: { applied: [], effective: {} } };
+ },
+ subscribe: () => () => {},
+ hasSynced: () => true,
+ subscribeSynced: () => () => {},
+ dispose: () => {},
+ } as unknown as ConfigBinding;
+ return { binding, calls };
+}
+
+beforeEach(() => {
+ mockProjectLocalConfig = null;
+ mockProjectLocalSynced = true;
+ mockProjectLocalBinding = null;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('LinkPreviewsSection', () => {
+ test('off: switch is unchecked and the body says no requests leave the computer', () => {
+ const { binding } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ const toggle = screen.getByTestId('settings-link-previews-toggle');
+ expect(toggle.getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByTestId('settings-link-previews-body').textContent).toContain(
+ 'No requests leave this computer',
+ );
+ });
+
+ test('on: switch is checked and the body discloses the per-hover egress', () => {
+ const { binding } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(true);
+
+ render(<LinkPreviewsSection />);
+
+ const toggle = screen.getByTestId('settings-link-previews-toggle');
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByTestId('settings-link-previews-body').textContent).toContain(
+ 'sends its URL to the destination site',
+ );
+ });
+
+ test('toggle is disabled until the project-local binding has synced', () => {
+ mockProjectLocalBinding = null;
+ mockProjectLocalSynced = false;
+
+ render(<LinkPreviewsSection />);
+
+ expect(
+ screen.getByTestId('settings-link-previews-toggle').getAttribute('disabled'),
+ ).not.toBeNull();
+ });
+
+ test('enabling opens the egress confirm dialog and does NOT write until confirmed', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ await user.click(screen.getByTestId('settings-link-previews-toggle'));
+
+ // Confirmation gate is open with the egress disclosure; nothing written yet.
+ expect(await screen.findByText("This sends the link's address off your machine")).toBeDefined();
+ expect(calls.length).toBe(0);
+
+ await user.click(screen.getByTestId('settings-link-previews-confirm-enable'));
+
+ expect(calls).toEqual([{ linkPreviews: { enabled: true } }]);
+ });
+
+ test('disabling commits immediately with no confirmation dialog', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(true);
+
+ render(<LinkPreviewsSection />);
+
+ await user.click(screen.getByTestId('settings-link-previews-toggle'));
+
+ expect(screen.queryByText("This sends the link's address off your machine")).toBeNull();
+ expect(calls).toEqual([{ linkPreviews: { enabled: false } }]);
+ });
+
+ test('cancelling the confirm dialog writes nothing and leaves the toggle off', async () => {
+ const user = userEvent.setup();
+ const { binding, calls } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ await user.click(screen.getByTestId('settings-link-previews-toggle'));
+ await user.click(await screen.findByRole('button', { name: /cancel/i }));
+
+ expect(calls.length).toBe(0);
+ expect(screen.getByTestId('settings-link-previews-toggle').getAttribute('aria-checked')).toBe(
+ 'false',
+ );
+ });
+
+ test('cancelling the confirm dialog returns focus to the toggle switch (WCAG 2.4.3)', async () => {
+ const user = userEvent.setup();
+ const { binding } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ const toggle = screen.getByTestId('settings-link-previews-toggle');
+ await user.click(toggle);
+ await user.click(await screen.findByRole('button', { name: /cancel/i }));
+
+ // The dialog is opened programmatically (no Radix trigger), so without the
+ // explicit onCloseAutoFocus redirect Radix would focus a null triggerRef
+ // and focus would drop to document.body.
+ await waitFor(() => {
+ expect(screen.queryByTestId('settings-link-previews-confirm')).toBeNull();
+ });
+ expect(document.activeElement).toBe(toggle);
+ });
+
+ test('confirming the dialog returns focus to the toggle switch', async () => {
+ const user = userEvent.setup();
+ const { binding } = makeBinding();
+ mockProjectLocalBinding = binding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ const toggle = screen.getByTestId('settings-link-previews-toggle');
+ await user.click(toggle);
+ await user.click(await screen.findByTestId('settings-link-previews-confirm-enable'));
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('settings-link-previews-confirm')).toBeNull();
+ });
+ expect(document.activeElement).toBe(toggle);
+ });
+
+ test('write failure keeps the confirm dialog open for retry (egress consent invariant)', async () => {
+ const user = userEvent.setup();
+ // A binding whose patch always fails — the dialog must stay open so the user
+ // keeps their retry for a privacy-sensitive action.
+ const failBinding = {
+ ...makeBinding().binding,
+ patch: () => ({ ok: false, error: { code: 'noop', message: 'fail' } }),
+ } as unknown as ConfigBinding;
+ mockProjectLocalBinding = failBinding;
+ mockProjectLocalConfig = configWithLinkPreviews(false);
+
+ render(<LinkPreviewsSection />);
+
+ await user.click(screen.getByTestId('settings-link-previews-toggle'));
+ await user.click(await screen.findByTestId('settings-link-previews-confirm-enable'));
+
+ // Still open (success-gated close did not fire on the failed write).
+ expect(await screen.findByTestId('settings-link-previews-confirm')).toBeDefined();
+ });
+});
diff --git a/packages/app/src/components/settings/LinkPreviewsSection.tsx b/packages/app/src/components/settings/LinkPreviewsSection.tsx
new file mode 100644
index 000000000..681ca09d2
--- /dev/null
+++ b/packages/app/src/components/settings/LinkPreviewsSection.tsx
@@ -0,0 +1,233 @@
+/**
+ * Settings → Link previews — opt-in rich preview cards for external links in
+ * the editor hover panel. Per-machine (project-local scope) because enabling it
+ * sends the hovered URL to the destination site to fetch its metadata; each
+ * teammate opts in deliberately on their own machine rather than inheriting one
+ * collaborator's egress choice through git.
+ *
+ * The toggle reads the synchronous project-local CRDT preference (the same
+ * pattern as the Search and Sync sections — never the server's resolved state,
+ * which round-trips through the persistence debounce + config file-watcher and
+ * would make the control appear to lag). Every off → on transition is gated by
+ * a confirmation dialog that discloses the egress; on → off commits immediately
+ * (the safe direction).
+ *
+ * Previews of links to other documents in this project are read entirely from
+ * the local index with no network request and are always on — this setting
+ * gates external links only.
+ */
+import { humanFormat } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { type RefObject, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import {
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ Dialog as DialogRoot,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Switch } from '@/components/ui/switch';
+import { useConfigContext } from '@/lib/config-provider';
+
+export function LinkPreviewsSection() {
+ const { t } = useLingui();
+ const { projectLocalConfig, projectLocalSynced, projectLocalBinding } = useConfigContext();
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ // The confirm dialog is opened programmatically (no Radix trigger), so Radix
+ // has nothing to restore focus to on close. Keep a handle on the Switch and
+ // send focus back there ourselves (WCAG 2.4.3).
+ const switchRef = useRef<HTMLButtonElement | null>(null);
+
+ const enabled = projectLocalConfig?.linkPreviews?.enabled ?? false;
+ const bindingReady = projectLocalSynced && projectLocalBinding !== null;
+
+ function write(next: boolean): boolean {
+ if (projectLocalBinding === null) {
+ toast.error(t`Link preview settings not yet loaded — try again in a moment`);
+ return false;
+ }
+ const result = projectLocalBinding.patch({ linkPreviews: { enabled: next } });
+ if (!result.ok) {
+ const detail = humanFormat(result.error);
+ toast.error(
+ next
+ ? t`Failed to enable link previews — ${detail}`
+ : t`Failed to disable link previews — ${detail}`,
+ );
+ return false;
+ }
+ return true;
+ }
+
+ function onToggleRequest(next: boolean) {
+ if (next) {
+ // Off → on: gate behind the egress confirmation. On → off is the safe
+ // direction and commits immediately.
+ setConfirmOpen(true);
+ return;
+ }
+ write(false);
+ }
+
+ function onConfirm() {
+ // Close only on success so a failed write leaves the dialog open to retry.
+ if (write(true)) setConfirmOpen(false);
+ }
+
+ return (
+ <section
+ aria-labelledby="settings-link-previews-title"
+ className="space-y-3"
+ data-testid="settings-link-previews"
+ >
+ <div className="space-y-1">
+ <h3 id="settings-link-previews-title" className="text-base font-semibold">
+ <Trans>Link previews</Trans>
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ Show a preview card when you hover an external link in the editor. This setting applies
+ only to this computer.
+ </Trans>
+ </p>
+ </div>
+
+ <div className="rounded-md border p-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <label htmlFor="settings-link-previews-toggle" className="text-sm font-medium">
+ <Trans>External link previews</Trans>
+ </label>
+ <p className="text-muted-foreground text-1sm" data-testid="settings-link-previews-body">
+ {enabled ? (
+ <Trans>
+ On — hovering an external link sends its URL to the destination site to fetch a
+ preview.
+ </Trans>
+ ) : (
+ <Trans>
+ Off — external links show only their URL. No requests leave this computer.
+ </Trans>
+ )}
+ </p>
+ </div>
+ <Switch
+ ref={switchRef}
+ id="settings-link-previews-toggle"
+ checked={enabled}
+ disabled={!bindingReady}
+ onCheckedChange={onToggleRequest}
+ aria-label={
+ enabled ? t`Disable external link previews` : t`Enable external link previews`
+ }
+ data-testid="settings-link-previews-toggle"
+ />
+ </div>
+ <p className="text-muted-foreground text-1sm mt-2">
+ <Trans>
+ Previews of links to other documents in this project are always on and read from the
+ local index — nothing leaves your computer for those.
+ </Trans>
+ </p>
+ </div>
+
+ <EnableLinkPreviewsConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ onConfirm={onConfirm}
+ returnFocusRef={switchRef}
+ />
+ </section>
+ );
+}
+
+interface EnableLinkPreviewsConfirmDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: () => void;
+ /** The Switch that initiated the off to on request; focus returns to it on close. */
+ returnFocusRef: RefObject<HTMLButtonElement | null>;
+}
+
+/**
+ * Guards every off → on transition. Turning external link previews on is the
+ * moment a hovered URL first leaves the machine, so the dialog spells out what
+ * is sent, where, and that it's per-machine.
+ */
+function EnableLinkPreviewsConfirmDialog({
+ open,
+ onOpenChange,
+ onConfirm,
+ returnFocusRef,
+}: EnableLinkPreviewsConfirmDialogProps) {
+ return (
+ <DialogRoot open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className="sm:max-w-lg"
+ data-testid="settings-link-previews-confirm"
+ onCloseAutoFocus={(event) => {
+ // With no Radix trigger, the default close-auto-focus targets a null
+ // triggerRef and focus falls to document.body. Preempt it and return
+ // focus to the Switch instead, on confirm, cancel, and Escape alike
+ // (same idiom as FrontmatterRow's add-property flow).
+ event.preventDefault();
+ returnFocusRef.current?.focus();
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>
+ <Trans>Turn on external link previews?</Trans>
+ </DialogTitle>
+ <DialogDescription>
+ <Trans>
+ External link previews show a card with the site name, page title, and description
+ when you hover a link.
+ </Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody>
+ <div
+ role="alert"
+ className="rounded-md border border-amber-300 bg-amber-50 px-3 py-2.5 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950 dark:text-amber-200"
+ >
+ <p className="mb-2 font-medium">
+ <Trans>This sends the link's address off your machine</Trans>
+ </p>
+ <ul className="list-disc space-y-1.5 pl-5">
+ <li>
+ <Trans>
+ When you hover an external link, its URL is sent to the destination site to fetch
+ the page's preview metadata — one request per previewed link.
+ </Trans>
+ </li>
+ <li>
+ <Trans>
+ Only external links trigger a request. Links to other documents in this project
+ preview from the local index and never leave your computer.
+ </Trans>
+ </li>
+ <li>
+ <Trans>This setting is per-machine and isn't shared with collaborators.</Trans>
+ </li>
+ </ul>
+ </div>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline">
+ <Trans>Cancel</Trans>
+ </Button>
+ </DialogClose>
+ <Button onClick={onConfirm} data-testid="settings-link-previews-confirm-enable">
+ <Trans>Turn on</Trans>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </DialogRoot>
+ );
+}
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index 8d81f2f97..2c7c2c8a5 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -108,6 +108,7 @@ import { cn } from '@/lib/utils';
import { AccountSection } from './AccountSection';
import { AiToolsSection } from './AiToolsSection';
import { EmbeddingsKeySection } from './EmbeddingsKeySection';
+import { LinkPreviewsSection } from './LinkPreviewsSection';
import { OkignoreSection } from './OkignoreSection';
import { ProjectAiToolsSection } from './ProjectAiToolsSection';
import { ProjectTemplatesSection } from './ProjectTemplatesSection';
@@ -225,6 +226,14 @@ export function SettingsDialogBody({
// binding from ConfigContext (like SyncSection) — no prop threading.
return <SearchSection />;
}
+ if (activeId === 'link-previews') {
+ // Project-local external-link-preview egress opt-in. Reads its own
+ // project-local binding from ConfigContext, same as SearchSection. The
+ // nav item is hidden on the packaged file:// renderer, whose Origin:
+ // null requests the preview route's anti-proxy gate rejects (see the
+ // gating in SettingsDialogShell).
+ return <LinkPreviewsSection />;
+ }
if (activeId === 'terminal') {
// Desktop-only per-project shell consent (the nav item is gated to the
// Electron host). Reads + writes its own project-local binding.
diff --git a/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx
new file mode 100644
index 000000000..1d788d4b7
--- /dev/null
+++ b/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx
@@ -0,0 +1,101 @@
+/**
+ * The Settings → Link previews nav item is hidden on the packaged file://
+ * renderer: a file: page's POST /api/link-preview carries Origin: null, which
+ * the route's anti-proxy gate rejects by design
+ * (packages/server/src/link-preview/request-gate.ts), so external link
+ * previews can never render there. Every other host (web, ok ui, and the DEV
+ * desktop renderer on http://localhost — a loopback Origin the gate passes)
+ * keeps the item.
+ *
+ * jsdom's window.location is unforgeable, so the test stubs the
+ * `isFileProtocolPage` helper seam instead — the same mock.module capability
+ * faking the terminal desktop-only test uses for the Electron bridge.
+ */
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+let fileProtocolPage = false;
+
+mock.module('@/lib/file-protocol-page', () => ({
+ isFileProtocolPage: () => fileProtocolPage,
+}));
+
+mock.module('@inkeep/open-knowledge-core', () => ({
+ SHOW_INSTALL_SKILL: false,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray | string, ...values: unknown[]) => {
+ if (typeof strings === 'string') return strings;
+ return strings.reduce(
+ (text, chunk, index) =>
+ `${text}${chunk}${index < values.length ? String(values[index]) : ''}`,
+ '',
+ );
+ },
+ }),
+}));
+
+mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
+ SettingsDialogBodyLazy: () => <div data-testid="settings-body-probe" />,
+}));
+
+mock.module('@/components/ui/dialog', () => ({
+ Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
+ open ? <div role="dialog">{children}</div> : null,
+ DialogContent: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ DialogDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
+ DialogTitle: ({ children, id }: { children?: ReactNode; id?: string }) => (
+ <h2 id={id}>{children}</h2>
+ ),
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <div className={className} />,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ collabUrl: 'ws://test.invalid' }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ userBinding: null,
+ userSynced: false,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ }),
+}));
+
+mock.module('@/lib/handoff/use-claude-desktop-integration', () => ({
+ useClaudeDesktopIntegration: () => ({ desktopPresent: false }),
+}));
+
+const { SettingsDialogShell } = await import('./SettingsDialogShell');
+
+describe('SettingsDialogShell link-previews nav item (no file:// renderer)', () => {
+ beforeEach(() => {
+ fileProtocolPage = false;
+ });
+ afterEach(() => {
+ cleanup();
+ fileProtocolPage = false;
+ });
+
+ test('hides the Link previews section on a file: page (packaged desktop)', () => {
+ fileProtocolPage = true;
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ expect(screen.queryByTestId('settings-sidebar-item-link-previews')).toBeNull();
+ });
+
+ test('shows the Link previews section on http(s) hosts (web, dev desktop)', () => {
+ fileProtocolPage = false;
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ expect(screen.getByTestId('settings-sidebar-item-link-previews')).not.toBeNull();
+ });
+});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index 46be0109a..21f67d1ac 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -21,7 +21,9 @@
* Sidebar IA:
* USER → Preferences, Hotkeys, Account, AI tools & CLI (Electron
* host only)
- * THIS PROJECT → Sync, Search, Templates, Ignore patterns, Config sharing
+ * THIS PROJECT → Sync, Search, Link previews (hidden on the packaged
+ * file:// renderer), Templates, Ignore patterns, Config
+ * sharing
* INTEGRATIONS → Claude Desktop (hidden when desktopPresent === false)
*/
@@ -35,6 +37,7 @@ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/compone
import { Skeleton } from '@/components/ui/skeleton';
import { useDocumentContext } from '@/editor/DocumentContext';
import { useConfigContext } from '@/lib/config-provider';
+import { isFileProtocolPage } from '@/lib/file-protocol-page';
import { useClaudeDesktopIntegration } from '@/lib/handoff/use-claude-desktop-integration';
import { cn } from '@/lib/utils';
@@ -97,6 +100,17 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
// its per-project revoke toggle only appears under the Electron preload.
const isOkDesktopHost = typeof window !== 'undefined' && window.okDesktop != null;
+ // The packaged desktop renderer loads over file:// (desktop main's
+ // loadFile), so its POST /api/link-preview requests carry Origin: null,
+ // which the route's anti-proxy gate rejects by design (see
+ // packages/server/src/link-preview/request-gate.ts). External link
+ // previews can never render on that host, so hide the toggle instead of
+ // promising a setting that cannot work. The DEV desktop renderer loads
+ // from http://localhost (loopback Origin, gate passes) and keeps the
+ // item. Remove this gate when a loopback-origin/desktop discriminator
+ // ships.
+ const isFileProtocolRenderer = isFileProtocolPage();
+
const groups: SidebarGroup[] = [
{
id: 'user',
@@ -119,6 +133,7 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
items: [
{ id: 'sync', label: t`Sync` },
{ id: 'search', label: t`Search` },
+ ...(isFileProtocolRenderer ? [] : [{ id: 'link-previews', label: t`Link previews` }]),
...(isOkDesktopHost ? [{ id: 'terminal', label: t`Terminal` }] : []),
// Per-project MCP wiring + runtime skill — desktop-only because the
// install actors live in the Electron main process (like Terminal).
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
index 7fb9d4da8..63a472637 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
@@ -1,6 +1,8 @@
import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { Editor } from '@tiptap/core';
+import type { ReactNode } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
if (typeof globalThis.DOMRect === 'undefined') {
@@ -52,6 +54,36 @@ mock.module('./use-headings', () => ({
useHeadings: () => [],
}));
+// External-preview infrastructure. `loadHarness` stands in for the local-server
+// round-trip (its `calls` prove the egress gate suppresses the request);
+// `configHarness` drives the `linkPreviews.enabled` gate; the passthrough
+// InteractionPropPanel renders the panel body inline so the pill + card are
+// assertable without the Radix Popover / floating-ui positioning.
+const loadHarness: { calls: number; result: LinkPreviewMetadata | null } = {
+ calls: 0,
+ result: null,
+};
+const configHarness = { enabled: false };
+
+mock.module('../link-preview/external-link-preview.ts', () => ({
+ loadLinkPreview: (_url: string, _signal?: AbortSignal) => {
+ loadHarness.calls += 1;
+ return Promise.resolve(loadHarness.result);
+ },
+}));
+
+mock.module('../../lib/config-provider', () => ({
+ useConfigContext: () => ({
+ projectLocalConfig: { linkPreviews: { enabled: configHarness.enabled } },
+ }),
+}));
+
+mock.module('../../components/InteractionPropPanel', () => ({
+ InteractionPropPanel: ({ children }: { children: ReactNode }) => (
+ <div data-testid="prop-panel">{children}</div>
+ ),
+}));
+
const { InternalLinkPropPanel } = await import('./InternalLinkPropPanel');
const { _resetPendingLinkEditForTest, setPendingLinkEdit } = await import('./link-edit-autoopen');
@@ -99,6 +131,9 @@ afterEach(() => {
from: 0,
to: 4,
};
+ loadHarness.calls = 0;
+ loadHarness.result = null;
+ configHarness.enabled = false;
});
describe('InternalLinkPropPanel', () => {
@@ -231,3 +266,88 @@ describe('InternalLinkPropPanel', () => {
expect(deleteRange).not.toHaveBeenCalled();
});
});
+
+const EXTERNAL_URL = 'https://example.com/some/page';
+
+const EXTERNAL_PREVIEW: LinkPreviewMetadata = {
+ domain: 'example.com',
+ title: 'Example Domain',
+ description: 'An illustrative example page.',
+};
+
+function externalMarkInfo(): CurrentMarkInfo {
+ return { id: 'm1', markType: 'link', attrs: { href: EXTERNAL_URL }, from: 0, to: 4 };
+}
+
+function renderExternalPanel() {
+ return render(
+ <TooltipProvider>
+ <InternalLinkPropPanel
+ editor={makeEditor()}
+ nodeId="m1"
+ sourceDocName="notes/source"
+ onClose={() => {}}
+ onNavigate={() => true}
+ />
+ </TooltipProvider>,
+ );
+}
+
+function externalCard(container: HTMLElement): HTMLElement | null {
+ return container.querySelector('[data-slot="external-link-preview-card"]');
+}
+
+function pillText(container: HTMLElement): string {
+ return container.querySelector('[data-slot="internal-link-prop-panel-text"]')?.textContent ?? '';
+}
+
+const nextTick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
+
+describe('InternalLinkPropPanel — external link preview', () => {
+ test('enabled: enhances the pill to the Option B card when the preview lands', async () => {
+ currentMarkInfo = externalMarkInfo();
+ configHarness.enabled = true;
+ loadHarness.result = EXTERNAL_PREVIEW;
+
+ const { container } = renderExternalPanel();
+
+ // The URL pill (with edit + remove actions) is present immediately.
+ expect(pillText(container)).toContain(EXTERNAL_URL);
+ expect(container.querySelector('[data-slot="internal-link-prop-panel-edit"]')).toBeTruthy();
+ expect(container.querySelector('[data-slot="internal-link-prop-panel-remove"]')).toBeTruthy();
+
+ // The card fills in once the preview resolves (progressive enhancement).
+ expect(await screen.findByText('Example Domain')).toBeDefined();
+ expect(externalCard(container)).toBeTruthy();
+ expect(loadHarness.calls).toBe(1);
+ });
+
+ test('enabled: a failed preview leaves exactly the URL pill and no card', async () => {
+ currentMarkInfo = externalMarkInfo();
+ configHarness.enabled = true;
+ loadHarness.result = null;
+
+ const { container } = renderExternalPanel();
+
+ await waitFor(() => expect(loadHarness.calls).toBe(1));
+ await nextTick();
+
+ expect(externalCard(container)).toBeNull();
+ expect(pillText(container)).toContain(EXTERNAL_URL);
+ expect(container.querySelector('[data-slot="internal-link-prop-panel-edit"]')).toBeTruthy();
+ });
+
+ test('disabled: sends no request and shows only the pill', async () => {
+ currentMarkInfo = externalMarkInfo();
+ configHarness.enabled = false;
+ loadHarness.result = EXTERNAL_PREVIEW;
+
+ const { container } = renderExternalPanel();
+
+ await nextTick();
+
+ expect(loadHarness.calls).toBe(0);
+ expect(externalCard(container)).toBeNull();
+ expect(pillText(container)).toContain(EXTERNAL_URL);
+ });
+});
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
index fa17d9c6b..9abff2e33 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.tsx
@@ -49,6 +49,7 @@ import {
} from '../../components/ui/dialog';
import { Input } from '../../components/ui/input';
import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';
+import { useConfigContext } from '../../lib/config-provider';
import { type CreatePageSeed, createPageFromSeedAndUpdate } from '../../lib/create-page';
import { normalizeDocNameInput } from '../../lib/doc-paths';
import { cn } from '../../lib/utils';
@@ -63,6 +64,10 @@ import {
LinkPathSuggestionInput,
preventLinkPathSuggestionDialogDismiss,
} from '../link-path-suggestions';
+import { ExternalLinkPreviewCard } from '../link-preview/ExternalLinkPreviewCard.tsx';
+import { InternalDocPreviewCard } from '../link-preview/InternalDocPreviewCard.tsx';
+import { useExternalLinkPreview } from '../link-preview/use-external-link-preview.ts';
+import { useInternalDocPreview } from '../link-preview/use-internal-doc-preview.ts';
import { isSafeNavigationUrl } from '../safe-navigation-url';
import { CopyButton } from './LinkPropPanelCopy';
import { consumePendingLinkEdit } from './link-edit-autoopen';
@@ -364,13 +369,34 @@ export function InternalLinkPropPanel({
const { addPage, folderPaths, pages, loading } = usePageList();
const { t } = useLingui();
+ // Classify + resolve the target before the early-return guards so the
+ // doc-preview hook is called unconditionally (Rules of Hooks). The card only
+ // renders for a resolved doc target; every other kind leaves the pill as-is.
+ const target = href ? classifyMarkdownHref(href, sourceDocName) : null;
+ const docIntent =
+ target?.kind === 'doc' ? resolveLinkTargetIntent(target.docName, { pages, folderPaths }) : null;
+ const docPreview = useInternalDocPreview({
+ docName:
+ target?.kind === 'doc' &&
+ docIntent?.kind === 'navigate' &&
+ docIntent.displayState === 'resolved'
+ ? target.docName
+ : null,
+ anchor: target?.kind === 'doc' ? target.anchor : null,
+ enabled: true,
+ });
+ const { projectLocalConfig } = useConfigContext();
+ const externalPreview = useExternalLinkPreview({
+ url: target?.kind === 'external' ? target.url : null,
+ enabled: projectLocalConfig?.linkPreviews?.enabled ?? false,
+ });
+
if (!info) {
// Mark removed mid-render — gracefully close.
return null;
}
const linkText = editor.state.doc.textBetween(info.from, info.to);
- const target = href ? classifyMarkdownHref(href, sourceDocName) : null;
function handleSave(nextHref: string, nextText: string, labelChanged: boolean) {
const live = getCurrentMarkInfo(editor.state, nodeId);
@@ -508,12 +534,11 @@ export function InternalLinkPropPanel({
className: 'text-muted-foreground',
};
} else if (target?.kind === 'doc') {
- const intent = resolveLinkTargetIntent(target.docName, { pages, folderPaths });
- isFolder = intent.kind === 'navigate' && intent.displayState === 'folder';
- isUnresolved = intent.kind === 'create';
+ isFolder = docIntent?.kind === 'navigate' && docIntent.displayState === 'folder';
+ isUnresolved = docIntent?.kind === 'create';
missingCreateSeed =
- intent.kind === 'create'
- ? { initialDir: intent.initialDir, suggestedName: intent.suggestedName }
+ docIntent?.kind === 'create'
+ ? { initialDir: docIntent.initialDir, suggestedName: docIntent.suggestedName }
: null;
if (isFolder) {
stateLabel = {
@@ -715,6 +740,9 @@ export function InternalLinkPropPanel({
</Tooltip>
</div>
</div>
+
+ {docPreview ? <InternalDocPreviewCard preview={docPreview} /> : null}
+ {externalPreview ? <ExternalLinkPreviewCard metadata={externalPreview} /> : null}
</InteractionPropPanel>
</>
);
diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx
new file mode 100644
index 000000000..31be264e6
--- /dev/null
+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx
@@ -0,0 +1,127 @@
+/**
+ * First DOM test for WikiLinkPropPanel. Covers the US doc-card wiring: a
+ * resolved wiki target renders the internal doc card (title / folder / excerpt)
+ * additively above the pill, an unavailable field is omitted (progressive), and
+ * an unresolved target keeps the create-page state with no card.
+ *
+ * The Radix-Popover-based `InteractionPropPanel` is mocked to a passthrough so
+ * the panel body renders inline (floating-ui / portal positioning is not under
+ * test here). `usePageList` is mocked to a single resolved page; the doc-card
+ * reader is mocked to echo whatever docName the panel decides to resolve, so
+ * the test exercises the panel's own resolved-vs-create gating rather than a
+ * stubbed verdict. Lingui macros resolve to the English-passthrough shim.
+ */
+
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { Editor } from '@tiptap/core';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { InternalDocPreview } from '../link-preview/internal-doc-preview.ts';
+
+const RESOLVED_DOC = 'guides/install';
+
+// The reader the panel decides to call: return a preview only when the panel
+// resolved a docName (its own gating), null otherwise — so the create branch
+// genuinely drives "no card".
+const previewHarness: { value: InternalDocPreview } = {
+ value: {
+ docName: RESOLVED_DOC,
+ title: 'Install guide',
+ folderPath: 'guides',
+ lastEditedAt: new Date(Date.now() - 3 * 86_400_000).toISOString(),
+ excerpt: 'Install the CLI and run ok start to boot the server.',
+ // tags / backlinkCount intentionally undefined — the "unavailable field
+ // omitted" assertion.
+ },
+};
+
+mock.module('../link-preview/use-internal-doc-preview.ts', () => ({
+ useInternalDocPreview: ({ docName }: { docName: string | null }) =>
+ docName ? previewHarness.value : null,
+}));
+
+mock.module('../../components/InteractionPropPanel', () => ({
+ InteractionPropPanel: ({ children }: { children: ReactNode }) => (
+ <div data-testid="prop-panel">{children}</div>
+ ),
+}));
+
+mock.module('../../components/PageListContext', () => ({
+ usePageList: () => ({
+ addPage: () => {},
+ assetPaths: new Set<string>(),
+ filePaths: new Set<string>(),
+ folderPaths: new Set<string>(['guides']),
+ pages: new Set<string>([RESOLVED_DOC]),
+ pagesBySlug: new Map<string, string>(),
+ pagesByBasename: new Map<string, string>(),
+ pageTitles: new Map<string, string>([[RESOLVED_DOC, 'Install guide']]),
+ pageMeta: new Map(),
+ loading: false,
+ error: null,
+ refetch: () => {},
+ }),
+}));
+
+afterEach(cleanup);
+
+/**
+ * Minimal editor + getPos stub. The panel reads node attrs and `editor.view.dom`
+ * at render; `posToDOMRect` / state mutations only run in the mocked panel's
+ * callbacks, which this test never fires.
+ */
+function makeEditor(target: string): Editor {
+ const node = { attrs: { target, alias: null, anchor: null }, nodeSize: 1 };
+ return {
+ state: { doc: { nodeAt: () => node } },
+ view: { dom: document.createElement('div') },
+ } as unknown as Editor;
+}
+
+async function renderPanel(target: string) {
+ const { WikiLinkPropPanel } = await import('./WikiLinkPropPanel');
+ return render(
+ <TooltipProvider>
+ <WikiLinkPropPanel
+ editor={makeEditor(target)}
+ getPos={() => 1}
+ onClose={() => {}}
+ onNavigate={() => true}
+ />
+ </TooltipProvider>,
+ );
+}
+
+function card(container: HTMLElement): HTMLElement | null {
+ return container.querySelector('[data-slot="internal-doc-preview-card"]');
+}
+
+describe('WikiLinkPropPanel — resolved doc renders the doc card', () => {
+ test('renders title, folder, and excerpt with an unavailable field omitted', async () => {
+ const { container } = await renderPanel(RESOLVED_DOC);
+
+ expect(card(container)).toBeTruthy();
+ expect(screen.getByText('Install guide')).toBeTruthy();
+ expect(
+ container.querySelector('[data-slot="internal-doc-preview-folder"]')?.textContent,
+ ).toContain('guides');
+ expect(
+ container.querySelector('[data-slot="internal-doc-preview-excerpt"]')?.textContent,
+ ).toContain('Install the CLI');
+ // backlinkCount + tags are undefined → those slots are omitted (progressive).
+ expect(container.querySelector('[data-slot="internal-doc-preview-tags"]')).toBeNull();
+ const meta = container.querySelector('[data-slot="internal-doc-preview-meta"]');
+ expect(meta?.textContent ?? '').not.toContain('backlink');
+ });
+});
+
+describe('WikiLinkPropPanel — unresolved target keeps create-page, no card', () => {
+ test('an unknown target shows the create-page action and renders no doc card', async () => {
+ const { container } = await renderPanel('ghost/missing');
+
+ expect(card(container)).toBeNull();
+ expect(container.querySelector('[data-slot="wiki-link-prop-panel-create"]')).toBeTruthy();
+ expect(screen.getByText('Create page')).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx
index 6587eb83b..11879c370 100644
--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx
+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.tsx
@@ -61,6 +61,8 @@ import {
LinkPathSuggestionInput,
preventLinkPathSuggestionDialogDismiss,
} from '../link-path-suggestions';
+import { InternalDocPreviewCard } from '../link-preview/InternalDocPreviewCard.tsx';
+import { useInternalDocPreview } from '../link-preview/use-internal-doc-preview.ts';
import { isSafeNavigationUrl } from '../safe-navigation-url';
import { CopyButton } from './LinkPropPanelCopy';
import { useHeadings } from './use-headings';
@@ -356,6 +358,21 @@ export function WikiLinkPropPanel({ editor, getPos, onClose, onNavigate }: WikiL
const [isCreating, setIsCreating] = useState(false);
const { t } = useLingui();
+ // Call the doc-preview hook unconditionally (Rules of Hooks), before the node
+ // guard. The card only renders for a resolved doc target; unresolved / folder
+ // / asset / external states leave the pill as-is.
+ const resolvedDocPreview = useInternalDocPreview({
+ docName:
+ !externalTarget &&
+ !loading &&
+ linkIntent?.kind === 'navigate' &&
+ linkIntent.displayState === 'resolved'
+ ? linkIntent.hashDocName
+ : null,
+ anchor,
+ enabled: true,
+ });
+
if (!node) {
// Node was removed mid-render — gracefully close.
return null;
@@ -638,6 +655,8 @@ export function WikiLinkPropPanel({ editor, getPos, onClose, onNavigate }: WikiL
</Tooltip>
</div>
</div>
+
+ {resolvedDocPreview ? <InternalDocPreviewCard preview={resolvedDocPreview} /> : null}
</InteractionPropPanel>
<EditWikiLinkDialog
diff --git a/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx
new file mode 100644
index 000000000..c4d1398a3
--- /dev/null
+++ b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx
@@ -0,0 +1,71 @@
+/**
+ * DOM tests for ExternalLinkPreviewCard (the Option B external card). Asserts
+ * present-field rendering, the progressive-omission contract (absent title /
+ * description / favicon are dropped, domain-only is valid), and — as a security
+ * pin — that a favicon URI which is not a `data:image/…` value is never rendered
+ * (a remote/script URI must not slip into an `<img src>`).
+ *
+ * Lingui macros resolve to the English-passthrough shim under `test:dom`; this
+ * card has no chrome strings, so assertions read the server-provided data.
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen } from '@testing-library/react';
+import { ExternalLinkPreviewCard } from './ExternalLinkPreviewCard';
+
+afterEach(cleanup);
+
+const FULL: LinkPreviewMetadata = {
+ domain: 'example.com',
+ title: 'Example Domain',
+ description: 'This domain is for use in illustrative examples.',
+ faviconDataUri: 'data:image/png;base64,iVBORw0KGgo=',
+};
+
+function slot(container: HTMLElement, name: string): HTMLElement | null {
+ return container.querySelector(`[data-slot="external-link-preview-${name}"]`);
+}
+
+describe('ExternalLinkPreviewCard — present fields', () => {
+ test('renders favicon (from the data URI), domain, title, and description', () => {
+ const { container } = render(<ExternalLinkPreviewCard metadata={FULL} />);
+ const favicon = slot(container, 'favicon');
+ expect(favicon?.getAttribute('src')).toBe(FULL.faviconDataUri);
+ expect(slot(container, 'domain')?.textContent).toBe('example.com');
+ expect(screen.getByText('Example Domain')).toBeTruthy();
+ expect(slot(container, 'description')?.textContent).toContain('illustrative examples');
+ });
+});
+
+describe('ExternalLinkPreviewCard — progressive omission', () => {
+ test('a metadata object with only a domain renders domain-only', () => {
+ const { container } = render(<ExternalLinkPreviewCard metadata={{ domain: 'bare.test' }} />);
+ expect(slot(container, 'domain')?.textContent).toBe('bare.test');
+ expect(slot(container, 'favicon')).toBeNull();
+ expect(slot(container, 'title')).toBeNull();
+ expect(slot(container, 'description')).toBeNull();
+ });
+
+ test('an absent favicon omits the image but keeps the rest of the card', () => {
+ const { faviconDataUri: _dropped, ...noFavicon } = FULL;
+ const { container } = render(<ExternalLinkPreviewCard metadata={noFavicon} />);
+ expect(slot(container, 'favicon')).toBeNull();
+ expect(slot(container, 'domain')?.textContent).toBe('example.com');
+ expect(screen.getByText('Example Domain')).toBeTruthy();
+ });
+});
+
+describe('ExternalLinkPreviewCard — favicon safety', () => {
+ test('a non-data:image favicon URI is never rendered as an image', () => {
+ const hostile: LinkPreviewMetadata = {
+ domain: 'example.com',
+ faviconDataUri: 'https://tracker.example/pixel.gif',
+ };
+ const { container } = render(<ExternalLinkPreviewCard metadata={hostile} />);
+ expect(slot(container, 'favicon')).toBeNull();
+ expect(container.querySelector('img')).toBeNull();
+ // The card still renders its text fields.
+ expect(slot(container, 'domain')?.textContent).toBe('example.com');
+ });
+});
diff --git a/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.tsx b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.tsx
new file mode 100644
index 000000000..917b36d13
--- /dev/null
+++ b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.tsx
@@ -0,0 +1,64 @@
+/**
+ * ExternalLinkPreviewCard — the Option B text card shown inside a link hover
+ * panel for an external URL once the server-side preview lands. Purely
+ * presentational: it renders whatever the server returned and omits absent
+ * fields, and is rendered only on success, so a failure/timeout/guard-rejection
+ * (the reader returns null) simply leaves today's URL pill untouched.
+ *
+ * Everything here is treated as hostile input the server already sanitized:
+ * text fields render as text nodes only (never `dangerouslySetInnerHTML`), and
+ * the registrable domain shown is the server's URL-derived value, not a claim
+ * from the fetched metadata. The favicon is the one image — it renders only from
+ * a self-contained `data:image/…` URI (a defense-in-depth check rejects anything
+ * else), so the card never hotlinks a remote resource.
+ */
+
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+
+export function ExternalLinkPreviewCard({ metadata }: { metadata: LinkPreviewMetadata }) {
+ const faviconSrc = metadata.faviconDataUri?.startsWith('data:image/')
+ ? metadata.faviconDataUri
+ : null;
+
+ return (
+ <div data-slot="external-link-preview-card" className="mt-2.5 border-t border-border/70 pt-2.5">
+ <div className="flex items-center gap-1.5">
+ {faviconSrc ? (
+ <img
+ data-slot="external-link-preview-favicon"
+ src={faviconSrc}
+ alt=""
+ aria-hidden="true"
+ width={16}
+ height={16}
+ className="size-4 shrink-0 rounded-sm"
+ />
+ ) : null}
+ <span
+ data-slot="external-link-preview-domain"
+ className="truncate text-xs font-medium text-muted-foreground"
+ >
+ {metadata.domain}
+ </span>
+ </div>
+
+ {metadata.title ? (
+ <div
+ data-slot="external-link-preview-title"
+ className="mt-1 line-clamp-2 text-sm font-medium text-foreground"
+ >
+ {metadata.title}
+ </div>
+ ) : null}
+
+ {metadata.description ? (
+ <p
+ data-slot="external-link-preview-description"
+ className="mt-1 line-clamp-3 text-xs text-muted-foreground"
+ >
+ {metadata.description}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx b/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx
new file mode 100644
index 000000000..894f570b4
--- /dev/null
+++ b/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx
@@ -0,0 +1,100 @@
+/**
+ * DOM tests for InternalDocPreviewCard (the W2 doc card). Asserts the
+ * present-field rendering and, above all, the progressive-omission contract:
+ * a field the reader has not resolved (excerpt/tags/backlinks still loading or
+ * failed) is omitted, an empty-body excerpt ('') shows the "No excerpt"
+ * affordance, and the always-local title/folder render regardless.
+ *
+ * Lingui macros resolve to the English-passthrough shim under `test:dom`
+ * (`tests/lingui-macro-preload.ts`), so assertions read source-locale text.
+ */
+
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import { InternalDocPreviewCard } from './InternalDocPreviewCard';
+import type { InternalDocPreview } from './internal-doc-preview.ts';
+
+afterEach(cleanup);
+
+const DAY_MS = 86_400_000;
+function daysAgoIso(days: number): string {
+ return new Date(Date.now() - days * DAY_MS).toISOString();
+}
+
+const fullPreview: InternalDocPreview = {
+ docName: 'guides/install',
+ title: 'Install guide',
+ folderPath: 'guides',
+ lastEditedAt: daysAgoIso(3),
+ tags: ['setup', 'onboarding'],
+ backlinkCount: 2,
+ excerpt: 'Install the CLI and run ok start to boot the server.',
+};
+
+function slot(container: HTMLElement, name: string): HTMLElement | null {
+ return container.querySelector(`[data-slot="internal-doc-preview-${name}"]`);
+}
+
+describe('InternalDocPreviewCard — resolved doc fields', () => {
+ test('renders title, folder, tags, excerpt, backlink count, and edited time', () => {
+ const { container } = render(<InternalDocPreviewCard preview={fullPreview} />);
+ expect(screen.getByText('Install guide')).toBeTruthy();
+ expect(slot(container, 'folder')?.textContent).toContain('guides');
+ expect(screen.getByText('setup')).toBeTruthy();
+ expect(screen.getByText('onboarding')).toBeTruthy();
+ expect(slot(container, 'excerpt')?.textContent).toContain('Install the CLI');
+ const meta = slot(container, 'meta')?.textContent ?? '';
+ expect(meta).toContain('2 backlinks');
+ expect(meta).toContain('ago');
+ });
+
+ test('a single backlink uses the singular form', () => {
+ const { container } = render(
+ <InternalDocPreviewCard preview={{ ...fullPreview, backlinkCount: 1 }} />,
+ );
+ expect(slot(container, 'meta')?.textContent).toContain('1 backlink');
+ expect(slot(container, 'meta')?.textContent).not.toContain('1 backlinks');
+ });
+});
+
+describe('InternalDocPreviewCard — progressive omission', () => {
+ test('omits excerpt, tags, and backlink count while their reads are unresolved', () => {
+ // The reader leaves excerpt/tags/backlinkCount undefined until the local
+ // reads land (or on failure); only title/folder/mtime are local-synchronous.
+ const preview: InternalDocPreview = {
+ docName: 'guides/install',
+ title: 'Install guide',
+ folderPath: 'guides',
+ lastEditedAt: daysAgoIso(1),
+ };
+ const { container } = render(<InternalDocPreviewCard preview={preview} />);
+ expect(screen.getByText('Install guide')).toBeTruthy();
+ expect(slot(container, 'folder')).toBeTruthy();
+ expect(slot(container, 'tags')).toBeNull();
+ expect(slot(container, 'excerpt')).toBeNull();
+ expect(slot(container, 'empty')).toBeNull();
+ // The edited time still renders from the local mtime; the backlink chip does not.
+ expect(slot(container, 'meta')?.textContent ?? '').not.toContain('backlink');
+ });
+
+ test('an empty body shows the "No excerpt" affordance, not an excerpt', () => {
+ const { container } = render(
+ <InternalDocPreviewCard preview={{ ...fullPreview, excerpt: '' }} />,
+ );
+ expect(slot(container, 'excerpt')).toBeNull();
+ expect(slot(container, 'empty')?.textContent).toContain('No excerpt');
+ });
+
+ test('an empty tags array omits the tags row', () => {
+ const { container } = render(<InternalDocPreviewCard preview={{ ...fullPreview, tags: [] }} />);
+ expect(slot(container, 'tags')).toBeNull();
+ });
+
+ test('a root-level doc (no folder) omits the folder row', () => {
+ const { container } = render(
+ <InternalDocPreviewCard preview={{ ...fullPreview, folderPath: null }} />,
+ );
+ expect(slot(container, 'folder')).toBeNull();
+ expect(screen.getByText('Install guide')).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/editor/link-preview/InternalDocPreviewCard.tsx b/packages/app/src/editor/link-preview/InternalDocPreviewCard.tsx
new file mode 100644
index 000000000..4050b5d62
--- /dev/null
+++ b/packages/app/src/editor/link-preview/InternalDocPreviewCard.tsx
@@ -0,0 +1,131 @@
+/**
+ * InternalDocPreviewCard — the W2 doc-preview card shown inside a link hover
+ * panel for a resolved internal target. Purely presentational: it renders
+ * whatever fields the {@link InternalDocPreview} reader has resolved and omits
+ * the rest, so the card enhances in place as the local reads land and never
+ * blocks on a slow or failed field.
+ *
+ * The card is additive — the hover panel's URL/target pill renders above it and
+ * is never removed, so a card that can't render (unresolved target, absent
+ * preview) simply leaves today's pill untouched.
+ *
+ * Field states worth knowing:
+ * - `excerpt === undefined` → the body read hasn't resolved (or failed): omit
+ * the excerpt line entirely (progressive).
+ * - `excerpt === ''` → the body read succeeded but the doc is empty:
+ * show the "No excerpt" affordance.
+ * - `tags` / `backlinkCount` undefined → omit that row/field.
+ */
+
+import { t } from '@lingui/core/macro';
+import { Plural, Trans } from '@lingui/react/macro';
+import { Clock3, FolderOpen, Link2 } from 'lucide-react';
+import { useState } from 'react';
+import type { InternalDocPreview } from './internal-doc-preview.ts';
+
+const MINUTE_MS = 60_000;
+const HOUR_MS = 60 * MINUTE_MS;
+const DAY_MS = 24 * HOUR_MS;
+const WEEK_MS = 7 * DAY_MS;
+const MONTH_MS = 30 * DAY_MS;
+const YEAR_MS = 365 * DAY_MS;
+
+/**
+ * Compact, Lingui-routed "time ago" for the edited timestamp. Compact units
+ * (`3d`, `2w`, `5mo`) sidestep pluralization and keep the hover footer terse.
+ * Returns null for an unparseable timestamp so the caller omits the field.
+ */
+function formatEditedAgo(iso: string, now: number): string | null {
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return null;
+ const diff = Math.max(0, now - then);
+ if (diff < MINUTE_MS) return t`just now`;
+ if (diff < HOUR_MS) return t`${Math.floor(diff / MINUTE_MS)}m ago`;
+ if (diff < DAY_MS) return t`${Math.floor(diff / HOUR_MS)}h ago`;
+ if (diff < WEEK_MS) return t`${Math.floor(diff / DAY_MS)}d ago`;
+ if (diff < MONTH_MS) return t`${Math.floor(diff / WEEK_MS)}w ago`;
+ if (diff < YEAR_MS) return t`${Math.floor(diff / MONTH_MS)}mo ago`;
+ return t`${Math.floor(diff / YEAR_MS)}y ago`;
+}
+
+export function InternalDocPreviewCard({ preview }: { preview: InternalDocPreview }) {
+ // `Date.now()` is impure — calling it directly in render violates React
+ // Compiler's purity contract. Snapshot it once at mount; a hover card is
+ // short-lived, so the relative time needs no re-tick.
+ const [now] = useState(() => Date.now());
+ const editedAgo = preview.lastEditedAt ? formatEditedAgo(preview.lastEditedAt, now) : null;
+ const hasTags = preview.tags !== undefined && preview.tags.length > 0;
+ const hasMeta = editedAgo !== null || preview.backlinkCount !== undefined;
+
+ return (
+ <div data-slot="internal-doc-preview-card" className="mt-2.5 border-t border-border/70 pt-2.5">
+ <div
+ data-slot="internal-doc-preview-title"
+ className="truncate text-sm font-medium text-foreground"
+ >
+ {preview.title}
+ </div>
+
+ {preview.folderPath ? (
+ <div
+ data-slot="internal-doc-preview-folder"
+ className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground"
+ >
+ <FolderOpen className="size-3 shrink-0" aria-hidden="true" />
+ <span className="truncate">{preview.folderPath}</span>
+ </div>
+ ) : null}
+
+ {hasTags ? (
+ <div data-slot="internal-doc-preview-tags" className="mt-1.5 flex flex-wrap gap-1">
+ {preview.tags?.map((tag) => (
+ <span
+ key={tag}
+ className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground"
+ >
+ {tag}
+ </span>
+ ))}
+ </div>
+ ) : null}
+
+ {preview.excerpt !== undefined ? (
+ preview.excerpt ? (
+ <p
+ data-slot="internal-doc-preview-excerpt"
+ className="mt-1.5 line-clamp-3 text-xs text-muted-foreground"
+ >
+ {preview.excerpt}
+ </p>
+ ) : (
+ <p
+ data-slot="internal-doc-preview-empty"
+ className="mt-1.5 text-xs italic text-muted-foreground/70"
+ >
+ <Trans>No excerpt</Trans>
+ </p>
+ )
+ ) : null}
+
+ {hasMeta ? (
+ <div
+ data-slot="internal-doc-preview-meta"
+ className="mt-1.5 flex items-center gap-2.5 text-[11px] text-muted-foreground/80"
+ >
+ {editedAgo ? (
+ <span className="flex items-center gap-1">
+ <Clock3 className="size-3 shrink-0" aria-hidden="true" />
+ <Trans>Edited {editedAgo}</Trans>
+ </span>
+ ) : null}
+ {preview.backlinkCount !== undefined ? (
+ <span className="flex items-center gap-1">
+ <Link2 className="size-3 shrink-0" aria-hidden="true" />
+ <Plural value={preview.backlinkCount} one="# backlink" other="# backlinks" />
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/editor/link-preview/doc-excerpt.test.ts b/packages/app/src/editor/link-preview/doc-excerpt.test.ts
new file mode 100644
index 000000000..6807a277c
--- /dev/null
+++ b/packages/app/src/editor/link-preview/doc-excerpt.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, test } from 'bun:test';
+import { extractDocExcerpt } from './doc-excerpt.ts';
+
+describe('extractDocExcerpt', () => {
+ test('strips markdown markup and returns readable prose', () => {
+ const md = 'This has **bold**, _italic_, `code`, and a [link](https://example.com) inside.';
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toBe('This has bold, italic, code, and a link inside.');
+ });
+
+ test('skips a leading title heading and previews the opening body', () => {
+ const md = '# Project Phoenix\n\nThe rollout plan for the new billing service.';
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toBe('The rollout plan for the new billing service.');
+ expect(excerpt).not.toContain('Project Phoenix');
+ });
+
+ test('strips frontmatter before extracting the excerpt', () => {
+ const md = '---\ntitle: Secret Title\ntags: [a, b]\n---\nVisible body prose here.';
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toBe('Visible body prose here.');
+ expect(excerpt).not.toContain('Secret Title');
+ expect(excerpt).not.toContain('tags');
+ });
+
+ test('returns an empty string for an empty body', () => {
+ expect(extractDocExcerpt('')).toBe('');
+ expect(extractDocExcerpt('---\ntitle: Only Frontmatter\n---\n')).toBe('');
+ expect(extractDocExcerpt('# Heading Only\n')).toBe('');
+ });
+
+ test('skips fenced code blocks including hash lines inside them', () => {
+ const md = ['```ts', '# not a heading', 'const x = 1;', '```', 'Real prose after code.'].join(
+ '\n',
+ );
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toBe('Real prose after code.');
+ expect(excerpt).not.toContain('const x');
+ expect(excerpt).not.toContain('not a heading');
+ });
+
+ test('gathers at most maxLines prose lines', () => {
+ const md = 'Line one.\nLine two.\nLine three.\nLine four.\nLine five.';
+ const excerpt = extractDocExcerpt(md, { maxLines: 2 });
+ expect(excerpt).toBe('Line one. Line two.');
+ expect(excerpt).not.toContain('three');
+ });
+
+ test('bounds output for a very large single line', () => {
+ const huge = 'word '.repeat(100_000);
+ const excerpt = extractDocExcerpt(huge, { maxChars: 100 });
+ expect(excerpt.length).toBeLessThanOrEqual(101);
+ expect(excerpt.endsWith('…')).toBe(true);
+ });
+
+ test('bounds output for a document with very many lines', () => {
+ const md = Array.from({ length: 20_000 }, (_, i) => `Paragraph number ${i}.`).join('\n\n');
+ const excerpt = extractDocExcerpt(md, { maxLines: 3, maxChars: 240 });
+ expect(excerpt.length).toBeLessThanOrEqual(241);
+ expect(excerpt).toContain('Paragraph number 0.');
+ expect(excerpt).not.toContain('Paragraph number 19999.');
+ });
+
+ test('previews the referenced section for an anchor target', () => {
+ const md = [
+ '# Title',
+ '',
+ 'Intro paragraph.',
+ '',
+ '## Deployment',
+ '',
+ 'Deploy with the blue-green strategy.',
+ '',
+ '## Rollback',
+ '',
+ 'Roll back by promoting the previous release.',
+ ].join('\n');
+ const excerpt = extractDocExcerpt(md, { anchor: 'deployment' });
+ expect(excerpt).toContain('Deployment');
+ expect(excerpt).toContain('Deploy with the blue-green strategy.');
+ expect(excerpt).not.toContain('Roll back');
+ expect(excerpt).not.toContain('Intro paragraph.');
+ });
+
+ test('stops an anchor section at the next same-level heading but keeps subheadings', () => {
+ const md = [
+ '## Setup',
+ '',
+ 'Install dependencies.',
+ '',
+ '### Prerequisites',
+ '',
+ 'You need Node.',
+ '',
+ '## Teardown',
+ '',
+ 'Remove everything.',
+ ].join('\n');
+ const excerpt = extractDocExcerpt(md, { anchor: 'setup', maxLines: 5 });
+ expect(excerpt).toContain('Install dependencies.');
+ expect(excerpt).toContain('You need Node.');
+ expect(excerpt).not.toContain('Remove everything.');
+ });
+
+ test('falls back to the document head when the anchor does not resolve', () => {
+ const md = '# Title\n\nHead prose paragraph.\n\n## Real Section\n\nSection body.';
+ const excerpt = extractDocExcerpt(md, { anchor: 'nonexistent-anchor' });
+ expect(excerpt).toBe('Head prose paragraph.');
+ });
+
+ test('renders wiki links, images, and list markers as plain text', () => {
+ const md = '- See [[guides/install|the install guide]] and ![alt text](./img.png) here.';
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toContain('the install guide');
+ expect(excerpt).toContain('alt text');
+ expect(excerpt).not.toContain('[[');
+ expect(excerpt).not.toContain('](');
+ expect(excerpt.startsWith('-')).toBe(false);
+ });
+
+ test('skips thematic breaks between paragraphs', () => {
+ const md = 'Alpha paragraph.\n\n---\n\nBravo paragraph.';
+ const excerpt = extractDocExcerpt(md, { maxLines: 3 });
+ expect(excerpt).toBe('Alpha paragraph. Bravo paragraph.');
+ expect(excerpt).not.toContain('---');
+ });
+
+ test('preserves snake_case identifiers when stripping emphasis', () => {
+ const md = 'The function is named handle_document_read in the server.';
+ const excerpt = extractDocExcerpt(md);
+ expect(excerpt).toContain('handle_document_read');
+ });
+});
diff --git a/packages/app/src/editor/link-preview/doc-excerpt.ts b/packages/app/src/editor/link-preview/doc-excerpt.ts
new file mode 100644
index 000000000..1a9e10062
--- /dev/null
+++ b/packages/app/src/editor/link-preview/doc-excerpt.ts
@@ -0,0 +1,211 @@
+/**
+ * Pure markdown-to-plain-text excerpt extraction for the internal doc-preview
+ * card. Given a document's markdown (frontmatter tolerated), returns a short
+ * plain-text snippet of the opening prose — or, when an anchor is supplied and
+ * resolves to a heading, of that section.
+ *
+ * Intentionally a lightweight line scanner rather than a full markdown parse:
+ * the output feeds a hover preview, so "readable text, bounded work" beats
+ * byte-perfect fidelity. Work is capped on both axes (line count and character
+ * count) so a pathologically large document can't stall the hover.
+ */
+
+import {
+ createCodeFenceTracker,
+ getHeadingSlug,
+ stripFrontmatter,
+ toWikiLinkSlug,
+} from '@inkeep/open-knowledge-core';
+
+export interface DocExcerptOptions {
+ /**
+ * Heading slug to preview a specific section instead of the document head.
+ * When it resolves to a heading, the excerpt is that heading plus its
+ * following lines; when it doesn't resolve, extraction falls back to the head.
+ */
+ anchor?: string | null;
+ /** Maximum number of prose source lines to gather. */
+ maxLines?: number;
+ /** Hard cap on the returned character count (a single huge line is truncated). */
+ maxChars?: number;
+}
+
+const DEFAULT_MAX_LINES = 3;
+const DEFAULT_MAX_CHARS = 240;
+
+/**
+ * Upper bound on lines scanned. A document that is thousands of blank lines
+ * before its first prose (or a giant anchor section) resolves to a partial or
+ * empty excerpt rather than walking the whole body on every hover.
+ */
+const MAX_SCAN_LINES = 400;
+
+const ATX_HEADING_RE = /^(#{1,6})\s+(.*)$/;
+
+/** Extract a plain-text excerpt from markdown for the hover preview card. */
+export function extractDocExcerpt(markdown: string, options: DocExcerptOptions = {}): string {
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
+ const maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
+ const anchor = options.anchor?.trim() || null;
+
+ const { body } = stripFrontmatter(markdown);
+ const lines = body.split('\n').map(stripCarriageReturn);
+
+ const sectionLines = anchor ? collectSection(lines, anchor, maxLines) : null;
+ const collected = sectionLines ?? collectDocHead(lines, maxLines);
+
+ const joined = collected.join(' ').replace(/\s+/g, ' ').trim();
+ if (joined.length <= maxChars) return joined;
+ return `${joined.slice(0, maxChars).trimEnd()}…`;
+}
+
+function stripCarriageReturn(line: string): string {
+ return line.endsWith('\r') ? line.slice(0, -1) : line;
+}
+
+/**
+ * Gather the opening body — prose from the top of the document up to the first
+ * heading that follows it. Leading headings (the title, an empty section) are
+ * skipped so extraction lands on the first real prose; the first heading after
+ * prose begins bounds the opening body so later sections don't leak in.
+ */
+function collectDocHead(lines: string[], maxLines: number): string[] {
+ const isInCodeFence = createCodeFenceTracker();
+ const out: string[] = [];
+ let started = false;
+ const scanLimit = Math.min(lines.length, MAX_SCAN_LINES);
+ for (let i = 0; i < scanLimit && out.length < maxLines; i++) {
+ const line = lines[i] ?? '';
+ // The tracker is stateful and must observe every line in order; call it
+ // first so fence state stays correct even for lines we go on to skip.
+ if (isInCodeFence(line)) continue;
+ if (ATX_HEADING_RE.test(line)) {
+ if (started) break;
+ continue;
+ }
+ const text = stripLineMarkup(line);
+ if (!text) continue;
+ out.push(text);
+ started = true;
+ }
+ return out;
+}
+
+/**
+ * Gather the heading matching `anchor` plus its section body. Returns null when
+ * no heading matches so the caller can fall back to the document head.
+ */
+function collectSection(lines: string[], anchor: string, maxLines: number): string[] | null {
+ const heading = findHeadingLineForAnchor(lines, anchor);
+ if (!heading) return null;
+
+ const out: string[] = [];
+ const headingText = stripLineMarkup(lines[heading.index] ?? '');
+ if (headingText) out.push(headingText);
+
+ const isInCodeFence = createCodeFenceTracker();
+ // Prime fence state up to and including the heading line so the body scan
+ // below starts with the correct in/out-of-fence reading.
+ for (let i = 0; i <= heading.index; i++) isInCodeFence(lines[i] ?? '');
+
+ const scanLimit = Math.min(lines.length, heading.index + 1 + MAX_SCAN_LINES);
+ for (let i = heading.index + 1; i < scanLimit && out.length < maxLines; i++) {
+ const line = lines[i] ?? '';
+ if (isInCodeFence(line)) continue;
+ const headingMatch = line.match(ATX_HEADING_RE);
+ if (headingMatch) {
+ // A same-or-higher-level heading ends this section; a deeper subheading
+ // keeps it going (skip only the marker line).
+ if ((headingMatch[1] ?? '').length <= heading.level) break;
+ continue;
+ }
+ const text = stripLineMarkup(line);
+ if (text) out.push(text);
+ }
+ return out;
+}
+
+function findHeadingLineForAnchor(
+ lines: string[],
+ anchor: string,
+): { index: number; level: number } | null {
+ const anchorSlug = toWikiLinkSlug(anchor);
+ const isInCodeFence = createCodeFenceTracker();
+ const slugCounts = new Map<string, number>();
+ const scanLimit = Math.min(lines.length, MAX_SCAN_LINES);
+ for (let i = 0; i < scanLimit; i++) {
+ const line = lines[i] ?? '';
+ if (isInCodeFence(line)) continue;
+ const match = line.match(ATX_HEADING_RE);
+ if (!match) continue;
+ const text = (match[2] ?? '').trim();
+ const slug = getHeadingSlug(text, slugCounts);
+ if (!slug) continue;
+ // The stored href anchor is already a slug; also match a freshly-slugged
+ // form so a hand-written `#Section Title` anchor still resolves.
+ if (slug === anchor || slug === anchorSlug) {
+ return { index: i, level: (match[1] ?? '').length };
+ }
+ }
+ return null;
+}
+
+/** Reduce one markdown line to its plain-text content. Empty when structural. */
+function stripLineMarkup(rawLine: string): string {
+ if (isStructuralLine(rawLine)) return '';
+
+ let line = rawLine;
+ // Leading block markers: nested blockquotes, then one list/heading marker.
+ line = line.replace(/^\s*(?:>\s?)+/, '');
+ line = line.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+|#{1,6}\s+)/, '');
+
+ // Image transclusions carry no text; drop before generic wiki-link handling.
+ line = line.replace(/!\[\[[^\]]*\]\]/g, '');
+ // Standard image: keep the alt text.
+ line = line.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1');
+ // Wiki link: prefer alias, else target (anchor dropped).
+ line = line.replace(/\[\[([^\]]+)\]\]/g, (_match, inner: string) => wikiLinkDisplay(inner));
+ // Inline and reference links: keep the visible text.
+ line = line.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1');
+ line = line.replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1');
+ // Inline code: keep the code text, drop the backticks.
+ line = line.replace(/``([^`]+)``/g, '$1');
+ line = line.replace(/`([^`]+)`/g, '$1');
+ // Emphasis / strong / strikethrough. Underscore emphasis is word-boundary
+ // guarded so identifiers like snake_case survive.
+ line = line.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
+ line = line.replace(/\*\*([^*]+)\*\*/g, '$1');
+ line = line.replace(/\*([^*]+)\*/g, '$1');
+ line = line.replace(/___([^_]+)___/g, '$1');
+ line = line.replace(/__([^_]+)__/g, '$1');
+ line = line.replace(/(^|[^A-Za-z0-9])_([^_]+)_(?![A-Za-z0-9])/g, '$1$2');
+ line = line.replace(/~~([^~]+)~~/g, '$1');
+ // Autolinks: keep the address inside the angle brackets, then drop any
+ // residual HTML tags.
+ line = line.replace(/<((?:https?|mailto):[^>]+)>/g, '$1');
+ line = line.replace(/<\/?[A-Za-z][^>]*>/g, '');
+ // Backslash escapes resolve to the escaped character.
+ line = line.replace(/\\([\\`*_{}[\]()#+\-.!~>|])/g, '$1');
+
+ return line.replace(/\s+/g, ' ').trim();
+}
+
+/** Resolve a wiki-link inner (`target#anchor|alias`) to its display text. */
+function wikiLinkDisplay(inner: string): string {
+ const pipeIndex = inner.indexOf('|');
+ if (pipeIndex >= 0) {
+ const alias = inner.slice(pipeIndex + 1).trim();
+ if (alias) return alias;
+ }
+ const target = pipeIndex >= 0 ? inner.slice(0, pipeIndex) : inner;
+ return (target.split('#')[0] ?? '').trim();
+}
+
+/** Thematic breaks and setext underlines carry no preview text. */
+function isStructuralLine(line: string): boolean {
+ const trimmed = line.trim();
+ if (!trimmed) return false;
+ if (/^([-*_])(?:[ \t]*\1){2,}$/.test(trimmed)) return true;
+ if (/^=+$/.test(trimmed)) return true;
+ return false;
+}
diff --git a/packages/app/src/editor/link-preview/external-link-preview.test.ts b/packages/app/src/editor/link-preview/external-link-preview.test.ts
new file mode 100644
index 000000000..37648f07b
--- /dev/null
+++ b/packages/app/src/editor/link-preview/external-link-preview.test.ts
@@ -0,0 +1,194 @@
+/**
+ * Unit tests for the external link-preview data layer. Only the network boundary
+ * (`globalThis.fetch`) is stubbed; the caching, single-flight, and
+ * response-mapping logic runs for real and is asserted through the public
+ * `loadLinkPreview` — so "negative results are not cached" and "concurrent
+ * hovers coalesce" are behavioral pins, not stubbed internals.
+ *
+ * Each test uses a fresh URL so the module-level success cache never bleeds
+ * across cases.
+ */
+
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import { loadLinkPreview, SUCCESS_CACHE_MAX_ENTRIES } from './external-link-preview.ts';
+
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const META: LinkPreviewMetadata = {
+ domain: 'example.com',
+ title: 'Example Domain',
+ description: 'An illustrative example page.',
+ faviconDataUri: 'data:image/png;base64,iVBORw0KGgo=',
+};
+
+function okResponse(metadata: LinkPreviewMetadata): Response {
+ return new Response(JSON.stringify({ ok: true, metadata }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+function failResponse(reason: string): Response {
+ return new Response(JSON.stringify({ ok: false, reason }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+let urlSeq = 0;
+function uniqueUrl(): string {
+ urlSeq += 1;
+ return `https://example-${urlSeq}.test/page`;
+}
+
+describe('loadLinkPreview — success + cache', () => {
+ test('POSTs the URL as JSON and returns the parsed metadata', async () => {
+ const url = uniqueUrl();
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
+ Promise.resolve(okResponse(META)),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ const result = await loadLinkPreview(url);
+ expect(result).toEqual(META);
+
+ const [input, init] = fetchMock.mock.calls[0] ?? [];
+ expect(input).toBe('/api/link-preview');
+ expect(init?.method).toBe('POST');
+ expect(new Headers(init?.headers).get('content-type')).toBe('application/json');
+ expect(JSON.parse(String(init?.body))).toEqual({ url });
+ });
+
+ test('a re-hover of a previewed URL is served from cache without re-fetching', async () => {
+ const url = uniqueUrl();
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
+ Promise.resolve(okResponse(META)),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ expect(await loadLinkPreview(url)).toEqual(META);
+ expect(await loadLinkPreview(url)).toEqual(META);
+ expect(fetchMock.mock.calls.length).toBe(1);
+ });
+});
+
+describe('loadLinkPreview — failures fall back to null and are not cached', () => {
+ test('a guard-rejection envelope returns null and a later hover retries', async () => {
+ const url = uniqueUrl();
+ let call = 0;
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) => {
+ call += 1;
+ return Promise.resolve(call === 1 ? failResponse('blocked') : okResponse(META));
+ });
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ expect(await loadLinkPreview(url)).toBeNull();
+ // Not cached: the second hover re-requests and now succeeds.
+ expect(await loadLinkPreview(url)).toEqual(META);
+ expect(fetchMock.mock.calls.length).toBe(2);
+ });
+
+ test('a non-2xx response (gate/body rejection) returns null', async () => {
+ const url = uniqueUrl();
+ globalThis.fetch = mock(() =>
+ Promise.resolve(new Response('{}', { status: 403 })),
+ ) as unknown as typeof fetch;
+ expect(await loadLinkPreview(url)).toBeNull();
+ });
+
+ test('a thrown request (network/offline) returns null', async () => {
+ const url = uniqueUrl();
+ globalThis.fetch = mock(() => Promise.reject(new Error('offline'))) as unknown as typeof fetch;
+ expect(await loadLinkPreview(url)).toBeNull();
+ });
+});
+
+describe('loadLinkPreview — bounded LRU success cache', () => {
+ /** Fetch stub that succeeds for every URL and records which URL each call was for. */
+ function countingFetch(): { calls: string[] } {
+ const calls: string[] = [];
+ globalThis.fetch = mock((_input: RequestInfo | URL, init?: RequestInit) => {
+ calls.push((JSON.parse(String(init?.body)) as { url: string }).url);
+ return Promise.resolve(okResponse(META));
+ }) as unknown as typeof fetch;
+ return { calls };
+ }
+
+ test('an entry older than the cap is evicted and re-fetched', async () => {
+ const { calls } = countingFetch();
+ const victim = uniqueUrl();
+ await loadLinkPreview(victim);
+ // A full cap of newer entries lands after the victim, so it must be gone
+ // regardless of what earlier tests left in the module-level cache.
+ for (let i = 0; i < SUCCESS_CACHE_MAX_ENTRIES; i += 1) {
+ await loadLinkPreview(uniqueUrl());
+ }
+ await loadLinkPreview(victim);
+ expect(calls.filter((u) => u === victim)).toHaveLength(2);
+ });
+
+ test('a cache hit bumps recency, so a re-hovered URL survives later inserts', async () => {
+ const { calls } = countingFetch();
+ const survivor = uniqueUrl();
+ await loadLinkPreview(survivor);
+ for (let i = 0; i < SUCCESS_CACHE_MAX_ENTRIES - 1; i += 1) {
+ await loadLinkPreview(uniqueUrl());
+ }
+ // The survivor is now the oldest entry; this hit must move it to the back.
+ await loadLinkPreview(survivor);
+ for (let i = 0; i < SUCCESS_CACHE_MAX_ENTRIES - 1; i += 1) {
+ await loadLinkPreview(uniqueUrl());
+ }
+ // Without the recency bump the fillers above would have evicted it.
+ await loadLinkPreview(survivor);
+ expect(calls.filter((u) => u === survivor)).toHaveLength(1);
+ });
+});
+
+describe('loadLinkPreview — single-flight + abort', () => {
+ test('concurrent identical hovers coalesce to a single request', async () => {
+ const url = uniqueUrl();
+ let resolveFetch!: (r: Response) => void;
+ const fetchMock = mock(
+ () =>
+ new Promise<Response>((resolve) => {
+ resolveFetch = resolve;
+ }),
+ );
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+
+ const first = loadLinkPreview(url);
+ const second = loadLinkPreview(url);
+ expect(fetchMock.mock.calls.length).toBe(1);
+
+ resolveFetch(okResponse(META));
+ expect(await first).toEqual(META);
+ expect(await second).toEqual(META);
+ });
+
+ test('aborting the caller signal resolves to null and caches nothing', async () => {
+ const url = uniqueUrl();
+ const controller = new AbortController();
+ const abortingFetch = mock(
+ (_input: RequestInfo | URL, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () =>
+ reject(new DOMException('Aborted', 'AbortError')),
+ );
+ }),
+ );
+ globalThis.fetch = abortingFetch as unknown as typeof fetch;
+
+ const pending = loadLinkPreview(url, controller.signal);
+ controller.abort();
+ expect(await pending).toBeNull();
+
+ // Nothing cached from the aborted attempt: a fresh hover re-requests.
+ globalThis.fetch = mock(() => Promise.resolve(okResponse(META))) as unknown as typeof fetch;
+ expect(await loadLinkPreview(url)).toEqual(META);
+ });
+});
diff --git a/packages/app/src/editor/link-preview/external-link-preview.ts b/packages/app/src/editor/link-preview/external-link-preview.ts
new file mode 100644
index 000000000..312c5890c
--- /dev/null
+++ b/packages/app/src/editor/link-preview/external-link-preview.ts
@@ -0,0 +1,98 @@
+/**
+ * Data layer for the external link-preview card. Sends the hovered URL to the
+ * local server's `POST /api/link-preview`, which performs the SSRF-guarded
+ * outbound fetch and returns sanitized metadata (or a bounded failure reason).
+ * The renderer never fetches the remote site directly — this call reaches only
+ * the user's own local process.
+ *
+ * A previewed URL is held in a per-session success cache so a re-hover renders
+ * with no visible loading. The cache is a small bounded LRU (Map insertion
+ * order = recency, the same trick as the server's preview-cache): entries can
+ * carry a base64 favicon data URI, so an unbounded map would grow renderer
+ * memory for the life of a long desktop session. Failures are deliberately NOT
+ * cached: the server
+ * already negative-caches dead links, and not caching here lets a transient
+ * failure recover on the next hover without sticking for the session. Concurrent
+ * identical hovers coalesce to a single request via the in-flight map.
+ *
+ * Every non-success path resolves to `null` (the card renders only on success,
+ * so `null` leaves today's URL pill untouched — the zero-regression contract).
+ */
+
+import { type LinkPreviewMetadata, LinkPreviewResponseSchema } from '@inkeep/open-knowledge-core';
+
+/** Success-cache bound; exported so the eviction test stays in sync. */
+export const SUCCESS_CACHE_MAX_ENTRIES = 128;
+
+const successCache = new Map<string, LinkPreviewMetadata>();
+const inflight = new Map<string, Promise<LinkPreviewMetadata | null>>();
+
+async function requestLinkPreview(
+ url: string,
+ signal: AbortSignal | undefined,
+): Promise<LinkPreviewMetadata | null> {
+ const res = await fetch('/api/link-preview', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ url }),
+ signal,
+ });
+ // A non-2xx is a gate/body-shape rejection (e.g. the null-origin 403 on the
+ // packaged desktop build) — treat as "no preview", fall back to the pill.
+ if (!res.ok) return null;
+ const parsed = LinkPreviewResponseSchema.safeParse(await res.json());
+ if (!parsed.success || !parsed.data.ok) return null;
+ return parsed.data.metadata;
+}
+
+/**
+ * Load the preview metadata for an external URL, or `null` on any failure,
+ * guard rejection, or abort. Cached (success only) + single-flight. The caller's
+ * `signal` cancels the underlying request on hover-out / navigation.
+ */
+export function loadLinkPreview(
+ url: string,
+ signal?: AbortSignal,
+): Promise<LinkPreviewMetadata | null> {
+ const cached = successCache.get(url);
+ if (cached) {
+ // LRU touch: delete-and-reinsert so the oldest key stays at the Map front.
+ successCache.delete(url);
+ successCache.set(url, cached);
+ return Promise.resolve(cached);
+ }
+
+ const existing = inflight.get(url);
+ if (existing) return existing;
+
+ const promise = (async () => {
+ try {
+ const metadata = await requestLinkPreview(url, signal);
+ if (metadata) {
+ successCache.set(url, metadata);
+ while (successCache.size > SUCCESS_CACHE_MAX_ENTRIES) {
+ const oldest = successCache.keys().next().value;
+ if (oldest === undefined) break;
+ successCache.delete(oldest);
+ }
+ }
+ return metadata;
+ } catch (err) {
+ // Abort (hover-out / navigation) and network errors both land here — the
+ // request never yielded an outcome, so nothing is cached and the next
+ // hover retries. A genuine fault is surfaced; an expected hover-out abort
+ // stays silent.
+ if (!(err instanceof Error) || err.name !== 'AbortError') {
+ console.warn(
+ '[link-preview] external preview fetch failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return null;
+ } finally {
+ inflight.delete(url);
+ }
+ })();
+ inflight.set(url, promise);
+ return promise;
+}
diff --git a/packages/app/src/editor/link-preview/internal-doc-preview.test.ts b/packages/app/src/editor/link-preview/internal-doc-preview.test.ts
new file mode 100644
index 000000000..96624fbf3
--- /dev/null
+++ b/packages/app/src/editor/link-preview/internal-doc-preview.test.ts
@@ -0,0 +1,147 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import {
+ CONTENT_CACHE_MAX_ENTRIES,
+ deriveContentFields,
+ deriveFolderPath,
+ extractDocTags,
+ loadBacklinkCount,
+ loadDocContent,
+} from './internal-doc-preview.ts';
+
+describe('deriveFolderPath', () => {
+ test('returns the folder segment of a nested docName', () => {
+ expect(deriveFolderPath('guides/setup/install')).toBe('guides/setup');
+ expect(deriveFolderPath('notes/todo')).toBe('notes');
+ });
+
+ test('returns null for a root-level docName', () => {
+ expect(deriveFolderPath('readme')).toBe(null);
+ expect(deriveFolderPath('')).toBe(null);
+ });
+});
+
+describe('extractDocTags', () => {
+ test('parses a frontmatter tags array', () => {
+ const md = '---\ntitle: Doc\ntags: [alpha, beta]\n---\nBody text.';
+ expect(extractDocTags(md)).toEqual(['alpha', 'beta']);
+ });
+
+ test('accepts a single scalar tag', () => {
+ const md = '---\ntags: showcase\n---\nBody.';
+ expect(extractDocTags(md)).toEqual(['showcase']);
+ });
+
+ test('returns an empty array when there is no frontmatter', () => {
+ expect(extractDocTags('Just body text, no frontmatter.')).toEqual([]);
+ });
+
+ test('returns an empty array when frontmatter has no tags key', () => {
+ expect(extractDocTags('---\ntitle: Doc\n---\nBody.')).toEqual([]);
+ });
+});
+
+describe('deriveContentFields', () => {
+ test('derives tags and an excerpt that excludes frontmatter', () => {
+ const md = '---\ntitle: Hidden\ntags: [x]\n---\n# Title\n\nThe body prose to preview.';
+ const fields = deriveContentFields(md, null);
+ expect(fields.tags).toEqual(['x']);
+ expect(fields.excerpt).toBe('The body prose to preview.');
+ expect(fields.excerpt).not.toContain('Hidden');
+ });
+
+ test('scopes the excerpt to the anchored section', () => {
+ const md = '## Overview\n\nOverview text.\n\n## Details\n\nDetails text.';
+ const fields = deriveContentFields(md, 'details');
+ expect(fields.excerpt).toContain('Details text.');
+ expect(fields.excerpt).not.toContain('Overview text.');
+ });
+});
+
+/**
+ * Eviction coverage for the module-level content + backlink caches. Only the
+ * network boundary (`globalThis.fetch`) is stubbed; the real caches, LRU touch,
+ * and eviction run and are asserted through `loadDocContent` / `loadBacklinkCount`.
+ * Each case uses fresh docNames so the module-level caches never bleed across it.
+ */
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+function jsonResponse(payload: unknown): Response {
+ return new Response(JSON.stringify(payload), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+/** Fetch stub that answers both local read endpoints and records the docName of each call. */
+function countingFetch(): { docCalls: string[]; backlinkCalls: string[] } {
+ const docCalls: string[] = [];
+ const backlinkCalls: string[] = [];
+ globalThis.fetch = mock((input: RequestInfo | URL) => {
+ const url = new URL(String(input), 'http://local');
+ if (url.pathname === '/api/document') {
+ const docName = url.searchParams.get('docName') ?? '';
+ docCalls.push(docName);
+ return Promise.resolve(
+ jsonResponse({ docName, content: `body of ${docName}`, lifecycle: null }),
+ );
+ }
+ const docName = url.searchParams.get('docNames') ?? '';
+ backlinkCalls.push(docName);
+ return Promise.resolve(jsonResponse({ counts: { [docName]: 0 } }));
+ }) as unknown as typeof fetch;
+ return { docCalls, backlinkCalls };
+}
+
+let docSeq = 0;
+function uniqueDoc(): string {
+ docSeq += 1;
+ return `evict-doc-${docSeq}`;
+}
+
+describe('loadDocContent — bounded LRU content cache', () => {
+ test('an entry older than the cap is evicted and re-fetched', async () => {
+ const { docCalls } = countingFetch();
+ const victim = uniqueDoc();
+ await loadDocContent(victim);
+ // A full cap of newer entries lands after the victim, so it must be gone
+ // regardless of what earlier tests left in the module-level cache.
+ for (let i = 0; i < CONTENT_CACHE_MAX_ENTRIES; i += 1) {
+ await loadDocContent(uniqueDoc());
+ }
+ await loadDocContent(victim);
+ expect(docCalls.filter((d) => d === victim)).toHaveLength(2);
+ });
+
+ test('a cache hit bumps recency, so a re-read doc survives later inserts', async () => {
+ const { docCalls } = countingFetch();
+ const survivor = uniqueDoc();
+ await loadDocContent(survivor);
+ for (let i = 0; i < CONTENT_CACHE_MAX_ENTRIES - 1; i += 1) {
+ await loadDocContent(uniqueDoc());
+ }
+ // The survivor is now the oldest entry; this hit must move it to the back.
+ await loadDocContent(survivor);
+ for (let i = 0; i < CONTENT_CACHE_MAX_ENTRIES - 1; i += 1) {
+ await loadDocContent(uniqueDoc());
+ }
+ // Without the recency bump the fillers above would have evicted it.
+ await loadDocContent(survivor);
+ expect(docCalls.filter((d) => d === survivor)).toHaveLength(1);
+ });
+});
+
+describe('loadBacklinkCount — bounded LRU count cache', () => {
+ test('an entry older than the cap is evicted and re-fetched', async () => {
+ const { backlinkCalls } = countingFetch();
+ const victim = uniqueDoc();
+ await loadBacklinkCount(victim);
+ for (let i = 0; i < CONTENT_CACHE_MAX_ENTRIES; i += 1) {
+ await loadBacklinkCount(uniqueDoc());
+ }
+ await loadBacklinkCount(victim);
+ expect(backlinkCalls.filter((d) => d === victim)).toHaveLength(2);
+ });
+});
diff --git a/packages/app/src/editor/link-preview/internal-doc-preview.ts b/packages/app/src/editor/link-preview/internal-doc-preview.ts
new file mode 100644
index 000000000..2cd82b28a
--- /dev/null
+++ b/packages/app/src/editor/link-preview/internal-doc-preview.ts
@@ -0,0 +1,171 @@
+/**
+ * Data layer for the internal doc-preview card. Assembles a document's preview
+ * fields from local sources only: title, folder, and modified time come from
+ * the in-memory page-list index (synchronous, elsewhere); tags, excerpt, and
+ * backlink count come from the local server over existing read endpoints
+ * (`/api/document`, `/api/backlink-counts`) — nothing leaves the machine and
+ * no new endpoint is added. Each async field is read independently and omitted
+ * on failure so the card renders whatever is ready without blocking.
+ */
+
+import {
+ BacklinkCountsSuccessSchema,
+ DocumentReadSuccessSchema,
+ extractFrontmatterTags,
+ stripFrontmatter,
+ unwrapFrontmatterFences,
+} from '@inkeep/open-knowledge-core';
+import { extractDocExcerpt } from './doc-excerpt.ts';
+
+export interface InternalDocPreview {
+ docName: string;
+ title: string;
+ /** Folder path segment of the docName, or null at the content root. */
+ folderPath: string | null;
+ /** ISO timestamp of the last local modification, or null when unknown. */
+ lastEditedAt: string | null;
+ /** Undefined until the document read resolves (or on failure); `[]` when none. */
+ tags?: string[];
+ /** Undefined until the count read resolves (or on failure). */
+ backlinkCount?: number;
+ /** Undefined until the document read resolves (or on failure); `''` for an empty body. */
+ excerpt?: string;
+}
+
+/** Fields derived from a document's raw markdown once the local read resolves. */
+export interface InternalDocContentFields {
+ tags: string[];
+ excerpt: string;
+}
+
+/** Folder path segment of a docName, or null when the doc is at the content root. */
+export function deriveFolderPath(docName: string): string | null {
+ const slashIndex = docName.lastIndexOf('/');
+ return slashIndex > 0 ? docName.slice(0, slashIndex) : null;
+}
+
+/** Parse frontmatter tags from a document's raw markdown. */
+export function extractDocTags(content: string): string[] {
+ const { frontmatter } = stripFrontmatter(content);
+ if (!frontmatter) return [];
+ return extractFrontmatterTags(unwrapFrontmatterFences(frontmatter));
+}
+
+/** Derive both content-sourced fields (tags + excerpt) from raw markdown. */
+export function deriveContentFields(
+ content: string,
+ anchor: string | null,
+): InternalDocContentFields {
+ return {
+ tags: extractDocTags(content),
+ excerpt: extractDocExcerpt(content, { anchor }),
+ };
+}
+
+/**
+ * Success-cache bound, shared by both per-session caches; exported so the
+ * eviction test stays in sync (mirrors external-link-preview's LRU bound).
+ */
+export const CONTENT_CACHE_MAX_ENTRIES = 128;
+
+// Per-session caches. A hover preview tolerates staleness (an edited or renamed
+// target degrades to the pill on real navigation), so successful reads are held
+// in a small bounded LRU for the life of the tab (evicted oldest-first once the
+// cap is exceeded, so a long session can't grow renderer memory without bound);
+// failures are not cached so a transient error retries on the next hover. The
+// in-flight maps coalesce concurrent identical reads.
+const contentCache = new Map<string, string>();
+const backlinkCountCache = new Map<string, number>();
+const inflightContent = new Map<string, Promise<string | null>>();
+const inflightBacklink = new Map<string, Promise<number | null>>();
+
+async function fetchDocContent(docName: string): Promise<string> {
+ const res = await fetch(`/api/document?docName=${encodeURIComponent(docName)}`);
+ if (!res.ok) throw new Error(`document read failed: ${res.status}`);
+ return DocumentReadSuccessSchema.parse(await res.json()).content;
+}
+
+async function fetchBacklinkCount(docName: string): Promise<number> {
+ const res = await fetch(`/api/backlink-counts?docNames=${encodeURIComponent(docName)}`);
+ if (!res.ok) throw new Error(`backlink-counts failed: ${res.status}`);
+ const { counts } = BacklinkCountsSuccessSchema.parse(await res.json());
+ return counts[docName] ?? 0;
+}
+
+/** Read a document's raw markdown from the local server. Cached + single-flight. */
+export function loadDocContent(docName: string): Promise<string | null> {
+ const cached = contentCache.get(docName);
+ if (cached !== undefined) {
+ // LRU touch: delete-and-reinsert so the oldest key stays at the Map front.
+ contentCache.delete(docName);
+ contentCache.set(docName, cached);
+ return Promise.resolve(cached);
+ }
+ const existing = inflightContent.get(docName);
+ if (existing) return existing;
+ const promise = (async () => {
+ try {
+ const content = await fetchDocContent(docName);
+ contentCache.set(docName, content);
+ while (contentCache.size > CONTENT_CACHE_MAX_ENTRIES) {
+ const oldest = contentCache.keys().next().value;
+ if (oldest === undefined) break;
+ contentCache.delete(oldest);
+ }
+ return content;
+ } catch (err) {
+ // A real fault in the local read is surfaced so an endpoint regression is
+ // visible; this path threads no abort signal, so any error is genuine.
+ if (!(err instanceof Error) || err.name !== 'AbortError') {
+ console.warn(
+ '[link-preview] internal doc read failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return null;
+ } finally {
+ inflightContent.delete(docName);
+ }
+ })();
+ inflightContent.set(docName, promise);
+ return promise;
+}
+
+/** Read a document's inbound-link count from the local server. Cached + single-flight. */
+export function loadBacklinkCount(docName: string): Promise<number | null> {
+ const cached = backlinkCountCache.get(docName);
+ if (cached !== undefined) {
+ // LRU touch: delete-and-reinsert so the oldest key stays at the Map front.
+ backlinkCountCache.delete(docName);
+ backlinkCountCache.set(docName, cached);
+ return Promise.resolve(cached);
+ }
+ const existing = inflightBacklink.get(docName);
+ if (existing) return existing;
+ const promise = (async () => {
+ try {
+ const count = await fetchBacklinkCount(docName);
+ backlinkCountCache.set(docName, count);
+ while (backlinkCountCache.size > CONTENT_CACHE_MAX_ENTRIES) {
+ const oldest = backlinkCountCache.keys().next().value;
+ if (oldest === undefined) break;
+ backlinkCountCache.delete(oldest);
+ }
+ return count;
+ } catch (err) {
+ // A real fault in the local read is surfaced so an endpoint regression is
+ // visible; this path threads no abort signal, so any error is genuine.
+ if (!(err instanceof Error) || err.name !== 'AbortError') {
+ console.warn(
+ '[link-preview] backlink-count read failed:',
+ err instanceof Error ? err.message : String(err),
+ );
+ }
+ return null;
+ } finally {
+ inflightBacklink.delete(docName);
+ }
+ })();
+ inflightBacklink.set(docName, promise);
+ return promise;
+}
diff --git a/packages/app/src/editor/link-preview/use-external-link-preview.ts b/packages/app/src/editor/link-preview/use-external-link-preview.ts
new file mode 100644
index 000000000..387d25ab7
--- /dev/null
+++ b/packages/app/src/editor/link-preview/use-external-link-preview.ts
@@ -0,0 +1,49 @@
+/**
+ * Reader hook for the external link-preview card. Returns the fetched metadata
+ * for an external URL, or `null` while loading, on any failure, or when the
+ * feature is disabled — so the card renders only on success and every other
+ * state leaves today's URL pill (the zero-regression contract).
+ *
+ * The fetch runs from an effect keyed on the URL, so it fires only while the
+ * hover panel is open on this link. The panel opens after the interaction
+ * layer's sustained-dwell delay, which makes the fetch dwell-gated without any
+ * change to the hover machine: a cursor merely transiting a link never opens the
+ * panel, so no egress request is sent. Hover-out (or re-targeting to a different
+ * link) unmounts/re-runs the effect, aborting the in-flight request.
+ */
+
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import { useEffect, useState } from 'react';
+import { loadLinkPreview } from './external-link-preview.ts';
+
+interface UseExternalLinkPreviewParams {
+ /** The external URL to preview, or null when the target is not an external link. */
+ url: string | null;
+ /** The `linkPreviews.enabled` egress gate. When false, no request is sent. */
+ enabled: boolean;
+}
+
+export function useExternalLinkPreview({
+ url,
+ enabled,
+}: UseExternalLinkPreviewParams): LinkPreviewMetadata | null {
+ // Store the metadata together with the URL it belongs to. The hover panel is
+ // a reused singleton, so `url` can change without a remount; binding the
+ // result to its URL means a resolved card for the previous link never renders
+ // under the new link's pill while the new fetch is still in flight.
+ const [entry, setEntry] = useState<{ url: string; metadata: LinkPreviewMetadata } | null>(null);
+
+ useEffect(() => {
+ if (!enabled || !url) return;
+
+ const controller = new AbortController();
+ void loadLinkPreview(url, controller.signal).then((result) => {
+ if (controller.signal.aborted || !result) return;
+ setEntry({ url, metadata: result });
+ });
+ return () => controller.abort();
+ }, [url, enabled]);
+
+ if (!enabled || !url) return null;
+ return entry?.url === url ? entry.metadata : null;
+}
diff --git a/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx b/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx
new file mode 100644
index 000000000..373c95bfa
--- /dev/null
+++ b/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx
@@ -0,0 +1,95 @@
+/**
+ * DOM test for the internal doc-preview reader hook's target binding. The hover
+ * panel is a reused singleton, so `docName` changes without a remount; the
+ * async fields (excerpt / tags / backlink count) must be bound to the target
+ * they were loaded for and matched at render, or a chip-to-chip focus move
+ * paints doc A's excerpt under doc B's title for the frame(s) before a reset
+ * effect runs.
+ *
+ * The probe records every render's output, so the assertion covers the exact
+ * mixed frame a screen-level query would race past. Only the data loaders
+ * (`loadDocContent` / `loadBacklinkCount`) are stubbed — the derive helpers and
+ * the hook itself run for real.
+ */
+
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render } from '@testing-library/react';
+
+const realDataLayer = await import('./internal-doc-preview.ts');
+
+mock.module('./internal-doc-preview.ts', () => ({
+ ...realDataLayer,
+ loadDocContent: (docName: string) => Promise.resolve(`# Heading\n\nBody of ${docName}.`),
+ loadBacklinkCount: (docName: string) => Promise.resolve(docName === 'a.md' ? 3 : 5),
+}));
+
+mock.module('../../components/PageListContext', () => ({
+ usePageList: () => ({
+ pageTitles: new Map<string, string>([
+ ['a.md', 'Doc A'],
+ ['b.md', 'Doc B'],
+ ]),
+ pageMeta: new Map(),
+ }),
+}));
+
+const { useInternalDocPreview } = await import('./use-internal-doc-preview.ts');
+
+interface RenderFrame {
+ title: string | undefined;
+ excerpt: string | undefined;
+ backlinkCount: number | undefined;
+}
+
+const renderLog: RenderFrame[] = [];
+
+function Probe({ docName }: { docName: string | null }) {
+ const preview = useInternalDocPreview({ docName, anchor: null, enabled: true });
+ renderLog.push({
+ title: preview?.title,
+ excerpt: preview?.excerpt,
+ backlinkCount: preview?.backlinkCount,
+ });
+ return <output data-testid="excerpt">{preview?.excerpt ?? '(none)'}</output>;
+}
+
+/** Let the loaders' already-resolved promises flush their setState calls. */
+const flushAsyncFields = () => act(async () => {});
+
+describe('useInternalDocPreview target binding', () => {
+ beforeEach(() => {
+ renderLog.length = 0;
+ });
+ afterEach(cleanup);
+
+ test('async fields fill in for the bound target', async () => {
+ const { getByTestId } = render(<Probe docName="a.md" />);
+ await flushAsyncFields();
+ expect(getByTestId('excerpt').textContent).toBe('Body of a.md.');
+ const last = renderLog.at(-1);
+ expect(last).toEqual({ title: 'Doc A', excerpt: 'Body of a.md.', backlinkCount: 3 });
+ });
+
+ test('a chip-to-chip target change never mixes the new title with stale async fields', async () => {
+ const { rerender, getByTestId } = render(<Probe docName="a.md" />);
+ await flushAsyncFields();
+ expect(getByTestId('excerpt').textContent).toBe('Body of a.md.');
+
+ renderLog.length = 0;
+ rerender(<Probe docName="b.md" />);
+
+ // The very first post-change frame: B's synchronous title with NO stale
+ // async fields (a post-paint reset effect would be one frame too late).
+ expect(renderLog[0]).toEqual({ title: 'Doc B', excerpt: undefined, backlinkCount: undefined });
+
+ await flushAsyncFields();
+ expect(getByTestId('excerpt').textContent).toBe('Body of b.md.');
+
+ // No frame anywhere in the transition mixed B's title with A's data.
+ const mixed = renderLog.filter(
+ (frame) =>
+ frame.title === 'Doc B' && (frame.excerpt === 'Body of a.md.' || frame.backlinkCount === 3),
+ );
+ expect(mixed).toHaveLength(0);
+ });
+});
diff --git a/packages/app/src/editor/link-preview/use-internal-doc-preview.ts b/packages/app/src/editor/link-preview/use-internal-doc-preview.ts
new file mode 100644
index 000000000..93cc82de2
--- /dev/null
+++ b/packages/app/src/editor/link-preview/use-internal-doc-preview.ts
@@ -0,0 +1,90 @@
+/**
+ * Reader hook for the internal doc-preview card. Returns the preview data for a
+ * resolved internal target: title / folder / modified-time land synchronously
+ * from the page-list index; tags, excerpt, and backlink count fill in from the
+ * local server and are each omitted (left undefined) on failure so the card
+ * enhances progressively and degrades to the pill on error.
+ *
+ * Author attribution (edited-by identity) is intentionally not surfaced here —
+ * only the local modified time is available without a heavier history read.
+ */
+
+import { useEffect, useState } from 'react';
+import { usePageList } from '../../components/PageListContext';
+import {
+ deriveContentFields,
+ deriveFolderPath,
+ type InternalDocContentFields,
+ type InternalDocPreview,
+ loadBacklinkCount,
+ loadDocContent,
+} from './internal-doc-preview.ts';
+
+interface UseInternalDocPreviewParams {
+ /** Resolved document name, or null when the target is not a resolved doc. */
+ docName: string | null;
+ /** Optional heading anchor for a section-scoped excerpt. */
+ anchor: string | null;
+ /** When false, no reads run and the hook returns null (no card). */
+ enabled: boolean;
+}
+
+export function useInternalDocPreview({
+ docName,
+ anchor,
+ enabled,
+}: UseInternalDocPreviewParams): InternalDocPreview | null {
+ const { pageTitles, pageMeta } = usePageList();
+ // The hover panel is a reused singleton, so `docName` can change without a
+ // remount while the synchronous fields update in the same render. The async
+ // fields are therefore stored WITH the target they were loaded for and
+ // matched at render — the same binding as `useExternalLinkPreview` — so a
+ // chip-to-chip focus move can never paint the previous doc's excerpt / tags /
+ // backlinks under the new doc's title, not even for the one frame before a
+ // reset effect would have run.
+ const [contentEntry, setContentEntry] = useState<{
+ docName: string;
+ anchor: string | null;
+ fields: InternalDocContentFields;
+ } | null>(null);
+ const [backlinkEntry, setBacklinkEntry] = useState<{
+ docName: string;
+ count: number;
+ } | null>(null);
+
+ useEffect(() => {
+ if (!enabled || !docName) return;
+
+ let cancelled = false;
+ void loadDocContent(docName).then((content) => {
+ if (cancelled || content === null) return;
+ setContentEntry({ docName, anchor, fields: deriveContentFields(content, anchor) });
+ });
+ void loadBacklinkCount(docName).then((count) => {
+ if (cancelled || count === null) return;
+ setBacklinkEntry({ docName, count });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [docName, anchor, enabled]);
+
+ if (!enabled || !docName) return null;
+
+ const contentFields =
+ contentEntry !== null && contentEntry.docName === docName && contentEntry.anchor === anchor
+ ? contentEntry.fields
+ : null;
+ const backlinkCount =
+ backlinkEntry !== null && backlinkEntry.docName === docName ? backlinkEntry.count : null;
+
+ return {
+ docName,
+ title: pageTitles.get(docName) ?? docName,
+ folderPath: deriveFolderPath(docName),
+ lastEditedAt: pageMeta.get(docName)?.modified ?? null,
+ tags: contentFields?.tags,
+ excerpt: contentFields?.excerpt,
+ backlinkCount: backlinkCount ?? undefined,
+ };
+}
diff --git a/packages/app/src/lib/file-protocol-page.test.ts b/packages/app/src/lib/file-protocol-page.test.ts
new file mode 100644
index 000000000..657c456ea
--- /dev/null
+++ b/packages/app/src/lib/file-protocol-page.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, test } from 'bun:test';
+import { isFileProtocolPage } from './file-protocol-page';
+
+describe('isFileProtocolPage', () => {
+ test('true for a file: page (packaged Electron renderer)', () => {
+ expect(isFileProtocolPage({ protocol: 'file:' })).toBe(true);
+ });
+
+ test('false for http: (web, ok ui, dev desktop renderer on localhost)', () => {
+ expect(isFileProtocolPage({ protocol: 'http:' })).toBe(false);
+ });
+
+ test('false for https:', () => {
+ expect(isFileProtocolPage({ protocol: 'https:' })).toBe(false);
+ });
+
+ test('false when no window/location exists (unit tier has no DOM)', () => {
+ // Default parameter path: the unit-tier substrate runs without a DOM
+ // `window`, so the default resolves to undefined.
+ expect(isFileProtocolPage()).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/file-protocol-page.ts b/packages/app/src/lib/file-protocol-page.ts
new file mode 100644
index 000000000..2db0c09ef
--- /dev/null
+++ b/packages/app/src/lib/file-protocol-page.ts
@@ -0,0 +1,21 @@
+/**
+ * Whether the page itself was loaded over `file:` — the packaged Electron
+ * renderer (`loadFile` in `packages/desktop/src/main/index.ts`). A `file:`
+ * page's fetches carry `Origin: null`, which loopback-origin-only server
+ * routes (e.g. the link-preview anti-proxy gate in
+ * `packages/server/src/link-preview/request-gate.ts`) reject by design, so
+ * callers use this to hide affordances that can never work on that host.
+ * The DEV desktop renderer loads from http://localhost (loopback Origin) and
+ * is intentionally NOT matched.
+ *
+ * `loc` is injectable for tests only (mirrors the `external-link.ts`
+ * convention — plain `.test.ts` runs without a DOM `window`); production
+ * callers pass nothing.
+ */
+export function isFileProtocolPage(
+ loc: { protocol: string } | undefined = typeof window === 'undefined'
+ ? undefined
+ : window.location,
+): boolean {
+ return loc?.protocol === 'file:';
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index c8324ff08..b3f3dc1dd 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -55,6 +55,7 @@
"0Gd0NU": ["Shared"],
"0LBDjY": ["\"", ["0"], "\" uninstalled — back to a draft"],
"0NA4b3": ["Keep my version"],
+ "0NkNB5": [["0"], "mo ago"],
"0SBTff": ["Show terminal"],
"0TnCvC": ["Rename ", ["0"]],
"0YEbfk": ["Connect to AI tools"],
@@ -122,6 +123,7 @@
"2IYGkU": ["This doc has unpushed changes. Recipients will see the last pushed version."],
"2QM24L": ["All tags"],
"2RBzMG": ["Network error — check your connection and try again"],
+ "2Snes1": ["This sends the link's address off your machine"],
"2XQ8Ww": ["Open preview when agent edits"],
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
@@ -244,6 +246,7 @@
"57fiu8": ["(read-only — edit in source mode for now)"],
"5ALjdr": ["Move through visual-editor find results from the find field."],
"5Ajb15": ["The formula <0>c = √(a² + b²)</0> renders inline."],
+ "5AzM72": ["This setting is per-machine and isn't shared with collaborators."],
"5ClEAu": ["Inline hashtag for cross-doc grouping."],
"5D3Ior": ["Hide folder"],
"5DFPDh": [
@@ -265,6 +268,7 @@
"5QGTaA": ["Could not copy relative path"],
"5SwVv1": ["Not installed"],
"5Tk8Fb": ["Loading files"],
+ "5Umg9i": ["Disable external link previews"],
"5WDhAk": ["Link to a page or external URL."],
"5ZB7XC": ["File drop zone"],
"5e1Dri": ["The menu label agents pick this template by (required)."],
@@ -639,6 +643,7 @@
"EJuO7B": ["Connect a GitHub account to browse and sync your repositories."],
"ELYtNJ": [".ok folders"],
"EL_YRd": ["Mirror of <0>api-spec</0>"],
+ "ENpRJV": ["External link previews"],
"EOjU5V": ["Inline Math Properties"],
"ETyvvg": ["No language match."],
"EVnzPs": ["Edit with AI"],
@@ -782,6 +787,7 @@
"HXFyWD": ["Split diff"],
"HdkSiO": ["New file"],
"HfI1dR": ["I already have it locally →"],
+ "HjNrT0": [["0", "plural", { "one": ["#", " backlink"], "other": ["#", " backlinks"] }]],
"Hl89Qd": ["Loading templates"],
"HlmZBk": ["Documents response did not match expected shape."],
"Hnl9nT": ["Set where pasted and dropped files are stored for this project."],
@@ -897,6 +903,7 @@
"KkEAud": ["Create a file from the current document or folder context."],
"KmydK6": ["Bold"],
"KnoB--": ["Will be saved as <0>", ["sanitized"], "</0>."],
+ "KpOJFY": ["Enable external link previews"],
"Kr3VPS": ["Codex will still ask until you run \"ok init\" in a terminal for this project."],
"KsAPaB": ["This branch is checked out in:"],
"KszKI_": ["Skill level"],
@@ -988,8 +995,12 @@
"MmqnGI": ["No global skills yet."],
"Mnavhe": [["propPanelDescriptorLabel"], " Properties"],
"MqQoV-": ["Describe what you want to build, start a blank file, or scaffold from a template."],
+ "MqsbfN": ["Turn on external link previews?"],
"MrwYIK": ["Toggle a source comment through CodeMirror."],
"MsuXaI": ["Hide panel (", ["panelShortcut"], ")"],
+ "My0wYT": [
+ "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
+ ],
"My9uXI": [
"Updated \"",
["display"],
@@ -1180,12 +1191,14 @@
"RN62Q8": [
"We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, and open the Claude Desktop App for you."
],
+ "RO-yts": ["Failed to disable link previews — ", ["detail"]],
"RSqaSd": ["Project root"],
"RVZJWQ": ["Search projects..."],
"RXNu_r": ["Shared via git with everyone working on this project."],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],
"Rah7yq": ["What should the AI do? (optional)"],
+ "Rb1zMa": ["No excerpt"],
"RfHNf8": ["Open activity panel for ", ["tooltipName"]],
"RfaEio": ["Toggle source comment"],
"RgbKEe": ["You don't have access to this repository."],
@@ -1309,6 +1322,9 @@
"VBE2dw": [
"Build and keep track of the world behind your story. A home for your characters, places, factions, and the lore that ties them together, so details stay consistent as you write."
],
+ "VFQXPl": [
+ "External link previews show a card with the site name, page title, and description when you hover a link."
+ ],
"VIwCaD": ["Entry"],
"VM7H66": ["This file is binary and can't be shown as text."],
"VNgKZz": ["Advanced settings"],
@@ -1401,6 +1417,10 @@
"Xet9MX": ["Failed to load backlinks"],
"Xewl6B": ["Your local copy is behind. Pull the latest changes, then open the link again."],
"XfzqjK": ["template \"", ["name"], "\""],
+ "Xisk4u": ["Edited ", ["editedAgo"]],
+ "Xk0-VC": [
+ "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
+ ],
"Xl-UUg": ["guides/install or https://example.com"],
"XmJfZT": ["name"],
"XnlF3W": ["Add the next matching source selection."],
@@ -1441,6 +1461,7 @@
"YaeyFh": ["Pulls may overwrite uncommitted edits in your local files."],
"Yea-K5": ["Restore to this point"],
"Yi0VMG": ["Upload ", ["keyName"]],
+ "YjMLg2": ["Off — external links show only their URL. No requests leave this computer."],
"YjhKI5": ["Cloning..."],
"YlDuro": ["Fit height"],
"YsEYYS": [
@@ -1482,6 +1503,7 @@
"ZYtq3m": [
"Connect the AI tools you use to this specific project. These files live in the project folder, so anyone who opens it gets the same setup."
],
+ "ZatAO_": ["Failed to enable link previews — ", ["detail"]],
"Zf0w-R": [
"Take a piece of writing from a rough idea to a finished draft to something you're ready to share. Good for blog posts, essays, or anything you want to move through clear stages."
],
@@ -1566,6 +1588,7 @@
"ajz9F8": ["Couldn't load conflict content for ", ["filePath"], ". Try reloading the page."],
"aoa6xA": ["network error (is `ok ui` running?)"],
"arUUsK": ["Product updates"],
+ "ax9kie": ["Link preview settings not yet loaded — try again in a moment"],
"az8lvo": ["Off"],
"b3Thhd": ["Upload failed"],
"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],
@@ -1611,6 +1634,9 @@
"c8jBgX": ["Checking for updates on GitHub"],
"cEoyWz": ["Add item to ", ["keyName"]],
"cF9DyA": ["Reconnecting after server restart"],
+ "cGV6Mh": [
+ "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
+ ],
"cIptmH": ["In the Claude Desktop App"],
"cKjLuT": ["(project + user)"],
"cN1Gcp": ["A worktree folder for ", ["shareBranch"], " already exists."],
@@ -1778,6 +1804,7 @@
"This page doesn't exist yet. Open it to create the page in the editor and collapse the graph."
],
"ggs9f8": ["Search files, folders, or commands"],
+ "gh27t1": ["Link previews"],
"gijbne": ["Failed to rename path"],
"gk_-qj": ["Couldn't rename template: ", ["0"]],
"gljvbT": [["words", "plural", { "one": ["word"], "other": ["words"] }]],
@@ -2000,6 +2027,7 @@
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
"lWNpNB": ["Add cursors or select matching occurrences through CodeMirror."],
"lXKZGw": ["Heading 1"],
+ "lY27jj": [["0"], "y ago"],
"lZAiSP": ["Backlinks response did not match expected shape."],
"l_FAT6": ["Use letters, digits, <0>-</0> or <1>_</1> only."],
"l_UFPv": ["Properties"],
@@ -2009,6 +2037,9 @@
"ljHjfg": ["That branch is already open in another worktree."],
"lkYioO": ["Show or hide document panel"],
"ll2yNl": ["Content directory"],
+ "lmBPt0": [
+ "Only external links trigger a request. Links to other documents in this project preview from the local index and never leave your computer."
+ ],
"lond3p": ["Shows above the code body. Round-trips as `title=\"...\"` in markdown."],
"lrhetp": ["+ ", ["overflow"], " more"],
"ls1N1w": ["(missing)"],
@@ -2258,6 +2289,9 @@
"rQAQus": ["Couldn't save template: ", ["error"]],
"rQRrkB": ["yesterday"],
"rSoi6g": [["displayName"], " (", ["bin"], ") isn't installed or on your PATH."],
+ "rVJpLz": [
+ "On — hovering an external link sends its URL to the destination site to fetch a preview."
+ ],
"rVgSRB": ["Collapse ", ["docName"]],
"rVxu1k": ["No pages link here yet."],
"rXz97P": ["Numbered list of items."],
@@ -2489,6 +2523,7 @@
"xNyj3h": ["Reinstall for Claude Chat & Cowork"],
"xOTzt5": ["just now"],
"xSVO3J": ["What gets created"],
+ "xV5sXw": [["0"], "w ago"],
"xWEvuo": ["Ask AI"],
"xXo8FT": ["Save failed: ", ["error"]],
"xYMPyY": [
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 56d717be7..ffc9d4dc9 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -113,6 +113,11 @@ msgstr "(some may already be hidden by other rules)"
msgid "(user-level only)"
msgstr "(user-level only)"
+#. placeholder {0}: preview.backlinkCount
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0, plural, one {# backlink} other {# backlinks}}"
+msgstr "{0, plural, one {# backlink} other {# backlinks}}"
+
#. placeholder {0}: tag.count
#: src/components/CommandPalette.tsx
msgid "{0, plural, one {# doc} other {# docs}}"
@@ -177,21 +182,42 @@ msgstr "{0}/{1} — {2}"
msgid "{0}/{1} {2}"
msgstr "{0}/{1} {2}"
+#. placeholder {0}: Math.floor(diff / DAY_MS)
#. placeholder {0}: Math.floor(diffSec / 86400)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}d ago"
msgstr "{0}d ago"
+#. placeholder {0}: Math.floor(diff / HOUR_MS)
#. placeholder {0}: Math.floor(diffSec / 3600)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}h ago"
msgstr "{0}h ago"
+#. placeholder {0}: Math.floor(diff / MINUTE_MS)
#. placeholder {0}: Math.floor(diffSec / 60)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}m ago"
msgstr "{0}m ago"
+#. placeholder {0}: Math.floor(diff / MONTH_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}mo ago"
+msgstr "{0}mo ago"
+
+#. placeholder {0}: Math.floor(diff / WEEK_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}w ago"
+msgstr "{0}w ago"
+
+#. placeholder {0}: Math.floor(diff / YEAR_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}y ago"
+msgstr "{0}y ago"
+
#: src/components/EditorTabs.tsx
msgid "{accessibleLabel} (conflict)"
msgstr "{accessibleLabel} (conflict)"
@@ -1257,6 +1283,7 @@ msgstr "Can't safely edit this tool's config"
#: src/components/PublishToGitHubDialog.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
+#: src/components/settings/LinkPreviewsSection.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
@@ -2535,6 +2562,10 @@ msgstr "Diff layout"
msgid "Diff unavailable"
msgstr "Diff unavailable"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Disable external link previews"
+msgstr "Disable external link previews"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Disable git auto-sync"
msgstr "Disable git auto-sync"
@@ -2775,6 +2806,10 @@ msgstr "Edit wiki link"
msgid "Edit with AI"
msgstr "Edit with AI"
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "Edited {editedAgo}"
+msgstr "Edited {editedAgo}"
+
#: src/components/FolderTimelineCard.tsx
msgid "edited template"
msgstr "edited template"
@@ -2863,6 +2898,10 @@ msgstr "Empty starting content"
msgid "Enable auto-sync"
msgstr "Enable auto-sync"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Enable external link previews"
+msgstr "Enable external link previews"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Enable git auto-sync"
msgstr "Enable git auto-sync"
@@ -2978,6 +3017,14 @@ msgstr "Explore"
msgid "External link"
msgstr "External link"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "External link previews"
+msgstr "External link previews"
+
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "External link previews show a card with the site name, page title, and description when you hover a link."
+msgstr "External link previews show a card with the site name, page title, and description when you hover a link."
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "External wiki link"
msgstr "External wiki link"
@@ -3027,6 +3074,10 @@ msgstr "Failed to delete path"
msgid "Failed to delete property"
msgstr "Failed to delete property"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Failed to disable link previews — {detail}"
+msgstr "Failed to disable link previews — {detail}"
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to disable semantic search — {detail}"
msgstr "Failed to disable semantic search — {detail}"
@@ -3039,6 +3090,10 @@ msgstr "Failed to disable sync — {detail}"
msgid "Failed to duplicate path"
msgstr "Failed to duplicate path"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Failed to enable link previews — {detail}"
+msgstr "Failed to enable link previews — {detail}"
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to enable semantic search — {detail}"
msgstr "Failed to enable semantic search — {detail}"
@@ -3989,6 +4044,7 @@ msgstr "Jump to tab 1-8"
#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TimelinePanel.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "just now"
msgstr "just now"
@@ -4065,6 +4121,15 @@ msgstr "Link"
msgid "Link copied."
msgstr "Link copied."
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Link preview settings not yet loaded — try again in a moment"
+msgstr "Link preview settings not yet loaded — try again in a moment"
+
+#: src/components/settings/LinkPreviewsSection.tsx
+#: src/components/settings/SettingsDialogShell.tsx
+msgid "Link previews"
+msgstr "Link previews"
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Link target"
msgstr "Link target"
@@ -4662,6 +4727,10 @@ msgstr "No edits yet."
msgid "No emoji found."
msgstr "No emoji found."
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "No excerpt"
+msgstr "No excerpt"
+
#: src/components/FileSidebar.tsx
msgid "No file or folder selected"
msgstr "No file or folder selected"
@@ -4929,6 +4998,10 @@ msgstr "of {totalPages}"
msgid "Off"
msgstr "Off"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Off — external links show only their URL. No requests leave this computer."
+msgstr "Off — external links show only their URL. No requests leave this computer."
+
#: src/components/settings/SearchSection.tsx
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr "Off — search ranks by keyword only. No content leaves this computer."
@@ -4949,6 +5022,10 @@ msgstr "ok ui responded but server.lock has no port yet"
msgid "On"
msgstr "On"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "On — hovering an external link sends its URL to the destination site to fetch a preview."
+msgstr "On — hovering an external link sends its URL to the destination site to fetch a preview."
+
#: src/components/settings/SearchSection.tsx
msgid "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
msgstr "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
@@ -4971,6 +5048,10 @@ msgstr "One pattern per line — appended to <0>.okignore</0>."
msgid "Only collaborators"
msgstr "Only collaborators"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Only external links trigger a request. Links to other documents in this project preview from the local index and never leave your computer."
+msgstr "Only external links trigger a request. Links to other documents in this project preview from the local index and never leave your computer."
+
#: src/components/FileSidebar.tsx
#: src/components/NotInSidebarIndicator.tsx
msgid "Only markdown files"
@@ -5546,6 +5627,10 @@ msgstr "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or op
msgid "Preview unavailable: {errorDetail}"
msgstr "Preview unavailable: {errorDetail}"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
+msgstr "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr "Previous match"
@@ -6594,6 +6679,10 @@ msgstr "Show {0} more"
msgid "Show {hidden} more"
msgstr "Show {hidden} more"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
+msgstr "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
+
#: src/components/settings/OkignoreSection.tsx
msgid "Show advanced"
msgstr "Show advanced"
@@ -7513,6 +7602,14 @@ msgstr "This replaces the current skill content with the bundled version {0}. An
msgid "This sends content off your machine"
msgstr "This sends content off your machine"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "This sends the link's address off your machine"
+msgstr "This sends the link's address off your machine"
+
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "This setting is per-machine and isn't shared with collaborators."
+msgstr "This setting is per-machine and isn't shared with collaborators."
+
#: src/components/settings/SearchSection.tsx
msgid "This setting is per-machine and isn't shared with collaborators. It needs an API key set with <0>ok embeddings set-key</0>."
msgstr "This setting is per-machine and isn't shared with collaborators. It needs an API key set with <0>ok embeddings set-key</0>."
@@ -7644,10 +7741,15 @@ msgstr "Try again"
msgid "Turn off Only markdown files"
msgstr "Turn off Only markdown files"
+#: src/components/settings/LinkPreviewsSection.tsx
#: src/components/settings/SearchSection.tsx
msgid "Turn on"
msgstr "Turn on"
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Turn on external link previews?"
+msgstr "Turn on external link previews?"
+
#: src/components/settings/SearchSection.tsx
msgid "Turn on semantic search?"
msgstr "Turn on semantic search?"
@@ -8098,6 +8200,10 @@ msgstr "When enabled, the agent opens or refreshes the preview after each edit.
msgid "When the agent runs its scheduled work."
msgstr "When the agent runs its scheduled work."
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
+msgstr "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Where newly added attachments are placed."
msgstr "Where newly added attachments are placed."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 1642e3926..9276ba398 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -55,6 +55,7 @@
"0Gd0NU": ["Śĥàŕēď"],
"0LBDjY": ["\"", ["0"], "\" ũńĩńśţàĺĺēď — ƀàćķ ţō à ďŕàƒţ"],
"0NA4b3": ["Ķēēƥ ḿŷ vēŕśĩōń"],
+ "0NkNB5": [["0"], "ḿō àĝō"],
"0SBTff": ["Śĥōŵ ţēŕḿĩńàĺ"],
"0TnCvC": ["Ŕēńàḿē ", ["0"]],
"0YEbfk": ["Ćōńńēćţ ţō ÀĨ ţōōĺś"],
@@ -122,6 +123,7 @@
"2IYGkU": ["Ţĥĩś ďōć ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],
"2QM24L": ["Àĺĺ ţàĝś"],
"2RBzMG": ["Ńēţŵōŕķ ēŕŕōŕ — ćĥēćķ ŷōũŕ ćōńńēćţĩōń àńď ţŕŷ àĝàĩń"],
+ "2Snes1": ["Ţĥĩś śēńďś ţĥē ĺĩńķ'ś àďďŕēśś ōƒƒ ŷōũŕ ḿàćĥĩńē"],
"2XQ8Ww": ["Ōƥēń ƥŕēvĩēŵ ŵĥēń àĝēńţ ēďĩţś"],
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
@@ -244,6 +246,7 @@
"57fiu8": ["(ŕēàď-ōńĺŷ — ēďĩţ ĩń śōũŕćē ḿōďē ƒōŕ ńōŵ)"],
"5ALjdr": ["Ḿōvē ţĥŕōũĝĥ vĩśũàĺ-ēďĩţōŕ ƒĩńď ŕēśũĺţś ƒŕōḿ ţĥē ƒĩńď ƒĩēĺď."],
"5Ajb15": ["Ţĥē ƒōŕḿũĺà <0>ć = √(ಠ+ ƀ²)</0> ŕēńďēŕś ĩńĺĩńē."],
+ "5AzM72": ["Ţĥĩś śēţţĩńĝ ĩś ƥēŕ-ḿàćĥĩńē àńď ĩśń'ţ śĥàŕēď ŵĩţĥ ćōĺĺàƀōŕàţōŕś."],
"5ClEAu": ["Ĩńĺĩńē ĥàśĥţàĝ ƒōŕ ćŕōśś-ďōć ĝŕōũƥĩńĝ."],
"5D3Ior": ["Ĥĩďē ƒōĺďēŕ"],
"5DFPDh": [
@@ -265,6 +268,7 @@
"5QGTaA": ["Ćōũĺď ńōţ ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
"5SwVv1": ["Ńōţ ĩńśţàĺĺēď"],
"5Tk8Fb": ["Ĺōàďĩńĝ ƒĩĺēś"],
+ "5Umg9i": ["Ďĩśàƀĺē ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"5WDhAk": ["Ĺĩńķ ţō à ƥàĝē ōŕ ēxţēŕńàĺ ŨŔĹ."],
"5ZB7XC": ["Ƒĩĺē ďŕōƥ źōńē"],
"5e1Dri": ["Ţĥē ḿēńũ ĺàƀēĺ àĝēńţś ƥĩćķ ţĥĩś ţēḿƥĺàţē ƀŷ (ŕēǫũĩŕēď)."],
@@ -639,6 +643,7 @@
"EJuO7B": ["Ćōńńēćţ à ĜĩţĤũƀ àććōũńţ ţō ƀŕōŵśē àńď śŷńć ŷōũŕ ŕēƥōśĩţōŕĩēś."],
"ELYtNJ": [".ōķ ƒōĺďēŕś"],
"EL_YRd": ["Ḿĩŕŕōŕ ōƒ <0>àƥĩ-śƥēć</0>"],
+ "ENpRJV": ["Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],
"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],
"EVnzPs": ["Ēďĩţ ŵĩţĥ ÀĨ"],
@@ -782,6 +787,7 @@
"HXFyWD": ["Śƥĺĩţ ďĩƒƒ"],
"HdkSiO": ["Ńēŵ ƒĩĺē"],
"HfI1dR": ["Ĩ àĺŕēàďŷ ĥàvē ĩţ ĺōćàĺĺŷ →"],
+ "HjNrT0": [["0", "plural", { "one": ["#", " ƀàćķĺĩńķ"], "other": ["#", " ƀàćķĺĩńķś"] }]],
"Hl89Qd": ["Ĺōàďĩńĝ ţēḿƥĺàţēś"],
"HlmZBk": ["Ďōćũḿēńţś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"Hnl9nT": ["Śēţ ŵĥēŕē ƥàśţēď àńď ďŕōƥƥēď ƒĩĺēś àŕē śţōŕēď ƒōŕ ţĥĩś ƥŕōĴēćţ."],
@@ -897,6 +903,7 @@
"KkEAud": ["Ćŕēàţē à ƒĩĺē ƒŕōḿ ţĥē ćũŕŕēńţ ďōćũḿēńţ ōŕ ƒōĺďēŕ ćōńţēxţ."],
"KmydK6": ["ßōĺď"],
"KnoB--": ["Ŵĩĺĺ ƀē śàvēď àś <0>", ["sanitized"], "</0>."],
+ "KpOJFY": ["Ēńàƀĺē ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"Kr3VPS": ["Ćōďēx ŵĩĺĺ śţĩĺĺ àśķ ũńţĩĺ ŷōũ ŕũń \"ōķ ĩńĩţ\" ĩń à ţēŕḿĩńàĺ ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"KsAPaB": ["Ţĥĩś ƀŕàńćĥ ĩś ćĥēćķēď ōũţ ĩń:"],
"KszKI_": ["Śķĩĺĺ ĺēvēĺ"],
@@ -988,8 +995,12 @@
"MmqnGI": ["Ńō ĝĺōƀàĺ śķĩĺĺś ŷēţ."],
"Mnavhe": [["propPanelDescriptorLabel"], " Ƥŕōƥēŕţĩēś"],
"MqQoV-": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ƀũĩĺď, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],
+ "MqsbfN": ["Ţũŕń ōń ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś?"],
"MrwYIK": ["Ţōĝĝĺē à śōũŕćē ćōḿḿēńţ ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
"MsuXaI": ["Ĥĩďē ƥàńēĺ (", ["panelShortcut"], ")"],
+ "My0wYT": [
+ "Ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ, ĩţś ŨŔĹ ĩś śēńţ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ ţĥē ƥàĝē'ś ƥŕēvĩēŵ ḿēţàďàţà — ōńē ŕēǫũēśţ ƥēŕ ƥŕēvĩēŵēď ĺĩńķ."
+ ],
"My9uXI": [
"Ũƥďàţēď \"",
["display"],
@@ -1180,12 +1191,14 @@
"RN62Q8": [
"Ŵē'ĺĺ ƀũĩĺď <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>, śàvē ĩţ ţō <1>~/Ďōŵńĺōàďś</1>, àńď ōƥēń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ƒōŕ ŷōũ."
],
+ "RO-yts": ["Ƒàĩĺēď ţō ďĩśàƀĺē ĺĩńķ ƥŕēvĩēŵś — ", ["detail"]],
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
"RVZJWQ": ["Śēàŕćĥ ƥŕōĴēćţś..."],
"RXNu_r": ["Śĥàŕēď vĩà ĝĩţ ŵĩţĥ ēvēŕŷōńē ŵōŕķĩńĝ ōń ţĥĩś ƥŕōĴēćţ."],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],
"Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],
+ "Rb1zMa": ["Ńō ēxćēŕƥţ"],
"RfHNf8": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"]],
"RfaEio": ["Ţōĝĝĺē śōũŕćē ćōḿḿēńţ"],
"RgbKEe": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ŕēƥōśĩţōŕŷ."],
@@ -1309,6 +1322,9 @@
"VBE2dw": [
"ßũĩĺď àńď ķēēƥ ţŕàćķ ōƒ ţĥē ŵōŕĺď ƀēĥĩńď ŷōũŕ śţōŕŷ. À ĥōḿē ƒōŕ ŷōũŕ ćĥàŕàćţēŕś, ƥĺàćēś, ƒàćţĩōńś, àńď ţĥē ĺōŕē ţĥàţ ţĩēś ţĥēḿ ţōĝēţĥēŕ, śō ďēţàĩĺś śţàŷ ćōńśĩśţēńţ àś ŷōũ ŵŕĩţē."
],
+ "VFQXPl": [
+ "Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś śĥōŵ à ćàŕď ŵĩţĥ ţĥē śĩţē ńàḿē, ƥàĝē ţĩţĺē, àńď ďēśćŕĩƥţĩōń ŵĥēń ŷōũ ĥōvēŕ à ĺĩńķ."
+ ],
"VIwCaD": ["Ēńţŕŷ"],
"VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],
"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],
@@ -1401,6 +1417,10 @@
"Xet9MX": ["Ƒàĩĺēď ţō ĺōàď ƀàćķĺĩńķś"],
"Xewl6B": ["Ŷōũŕ ĺōćàĺ ćōƥŷ ĩś ƀēĥĩńď. Ƥũĺĺ ţĥē ĺàţēśţ ćĥàńĝēś, ţĥēń ōƥēń ţĥē ĺĩńķ àĝàĩń."],
"XfzqjK": ["ţēḿƥĺàţē \"", ["name"], "\""],
+ "Xisk4u": ["Ēďĩţēď ", ["editedAgo"]],
+ "Xk0-VC": [
+ "Ƥŕēvĩēŵś ōƒ ĺĩńķś ţō ōţĥēŕ ďōćũḿēńţś ĩń ţĥĩś ƥŕōĴēćţ àŕē àĺŵàŷś ōń àńď ŕēàď ƒŕōḿ ţĥē ĺōćàĺ ĩńďēx — ńōţĥĩńĝ ĺēàvēś ŷōũŕ ćōḿƥũţēŕ ƒōŕ ţĥōśē."
+ ],
"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],
"XmJfZT": ["ńàḿē"],
"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],
@@ -1441,6 +1461,7 @@
"YaeyFh": ["Ƥũĺĺś ḿàŷ ōvēŕŵŕĩţē ũńćōḿḿĩţţēď ēďĩţś ĩń ŷōũŕ ĺōćàĺ ƒĩĺēś."],
"Yea-K5": ["Ŕēśţōŕē ţō ţĥĩś ƥōĩńţ"],
"Yi0VMG": ["Ũƥĺōàď ", ["keyName"]],
+ "YjMLg2": ["Ōƒƒ — ēxţēŕńàĺ ĺĩńķś śĥōŵ ōńĺŷ ţĥēĩŕ ŨŔĹ. Ńō ŕēǫũēśţś ĺēàvē ţĥĩś ćōḿƥũţēŕ."],
"YjhKI5": ["Ćĺōńĩńĝ..."],
"YlDuro": ["Ƒĩţ ĥēĩĝĥţ"],
"YsEYYS": [
@@ -1482,6 +1503,7 @@
"ZYtq3m": [
"Ćōńńēćţ ţĥē ÀĨ ţōōĺś ŷōũ ũśē ţō ţĥĩś śƥēćĩƒĩć ƥŕōĴēćţ. Ţĥēśē ƒĩĺēś ĺĩvē ĩń ţĥē ƥŕōĴēćţ ƒōĺďēŕ, śō àńŷōńē ŵĥō ōƥēńś ĩţ ĝēţś ţĥē śàḿē śēţũƥ."
],
+ "ZatAO_": ["Ƒàĩĺēď ţō ēńàƀĺē ĺĩńķ ƥŕēvĩēŵś — ", ["detail"]],
"Zf0w-R": [
"Ţàķē à ƥĩēćē ōƒ ŵŕĩţĩńĝ ƒŕōḿ à ŕōũĝĥ ĩďēà ţō à ƒĩńĩśĥēď ďŕàƒţ ţō śōḿēţĥĩńĝ ŷōũ'ŕē ŕēàďŷ ţō śĥàŕē. Ĝōōď ƒōŕ ƀĺōĝ ƥōśţś, ēśśàŷś, ōŕ àńŷţĥĩńĝ ŷōũ ŵàńţ ţō ḿōvē ţĥŕōũĝĥ ćĺēàŕ śţàĝēś."
],
@@ -1566,6 +1588,7 @@
"ajz9F8": ["Ćōũĺďń'ţ ĺōàď ćōńƒĺĩćţ ćōńţēńţ ƒōŕ ", ["filePath"], ". Ţŕŷ ŕēĺōàďĩńĝ ţĥē ƥàĝē."],
"aoa6xA": ["ńēţŵōŕķ ēŕŕōŕ (ĩś `ōķ ũĩ` ŕũńńĩńĝ?)"],
"arUUsK": ["Ƥŕōďũćţ ũƥďàţēś"],
+ "ax9kie": ["Ĺĩńķ ƥŕēvĩēŵ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"az8lvo": ["Ōƒƒ"],
"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],
"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],
@@ -1611,6 +1634,9 @@
"c8jBgX": ["Ćĥēćķĩńĝ ƒōŕ ũƥďàţēś ōń ĜĩţĤũƀ"],
"cEoyWz": ["Àďď ĩţēḿ ţō ", ["keyName"]],
"cF9DyA": ["Ŕēćōńńēćţĩńĝ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
+ "cGV6Mh": [
+ "Śĥōŵ à ƥŕēvĩēŵ ćàŕď ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ ĩń ţĥē ēďĩţōŕ. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
+ ],
"cIptmH": ["Ĩń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ"],
"cKjLuT": ["(ƥŕōĴēćţ + ũśēŕ)"],
"cN1Gcp": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ", ["shareBranch"], " àĺŕēàďŷ ēxĩśţś."],
@@ -1778,6 +1804,7 @@
"Ţĥĩś ƥàĝē ďōēśń'ţ ēxĩśţ ŷēţ. Ōƥēń ĩţ ţō ćŕēàţē ţĥē ƥàĝē ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."
],
"ggs9f8": ["Śēàŕćĥ ƒĩĺēś, ƒōĺďēŕś, ōŕ ćōḿḿàńďś"],
+ "gh27t1": ["Ĺĩńķ ƥŕēvĩēŵś"],
"gijbne": ["Ƒàĩĺēď ţō ŕēńàḿē ƥàţĥ"],
"gk_-qj": ["Ćōũĺďń'ţ ŕēńàḿē ţēḿƥĺàţē: ", ["0"]],
"gljvbT": [["words", "plural", { "one": ["ŵōŕď"], "other": ["ŵōŕďś"] }]],
@@ -2000,6 +2027,7 @@
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
"lWNpNB": ["Àďď ćũŕśōŕś ōŕ śēĺēćţ ḿàţćĥĩńĝ ōććũŕŕēńćēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
"lXKZGw": ["Ĥēàďĩńĝ 1"],
+ "lY27jj": [["0"], "ŷ àĝō"],
"lZAiSP": ["ßàćķĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"l_FAT6": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>-</0> ōŕ <1>_</1> ōńĺŷ."],
"l_UFPv": ["Ƥŕōƥēŕţĩēś"],
@@ -2009,6 +2037,9 @@
"ljHjfg": ["Ţĥàţ ƀŕàńćĥ ĩś àĺŕēàďŷ ōƥēń ĩń àńōţĥēŕ ŵōŕķţŕēē."],
"lkYioO": ["Śĥōŵ ōŕ ĥĩďē ďōćũḿēńţ ƥàńēĺ"],
"ll2yNl": ["Ćōńţēńţ ďĩŕēćţōŕŷ"],
+ "lmBPt0": [
+ "Ōńĺŷ ēxţēŕńàĺ ĺĩńķś ţŕĩĝĝēŕ à ŕēǫũēśţ. Ĺĩńķś ţō ōţĥēŕ ďōćũḿēńţś ĩń ţĥĩś ƥŕōĴēćţ ƥŕēvĩēŵ ƒŕōḿ ţĥē ĺōćàĺ ĩńďēx àńď ńēvēŕ ĺēàvē ŷōũŕ ćōḿƥũţēŕ."
+ ],
"lond3p": ["Śĥōŵś àƀōvē ţĥē ćōďē ƀōďŷ. Ŕōũńď-ţŕĩƥś àś `ţĩţĺē=\"...\"` ĩń ḿàŕķďōŵń."],
"lrhetp": ["+ ", ["overflow"], " ḿōŕē"],
"ls1N1w": ["(ḿĩśśĩńĝ)"],
@@ -2258,6 +2289,9 @@
"rQAQus": ["Ćōũĺďń'ţ śàvē ţēḿƥĺàţē: ", ["error"]],
"rQRrkB": ["ŷēśţēŕďàŷ"],
"rSoi6g": [["displayName"], " (", ["bin"], ") ĩśń'ţ ĩńśţàĺĺēď ōŕ ōń ŷōũŕ ƤÀŢĤ."],
+ "rVJpLz": [
+ "Ōń — ĥōvēŕĩńĝ àń ēxţēŕńàĺ ĺĩńķ śēńďś ĩţś ŨŔĹ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ à ƥŕēvĩēŵ."
+ ],
"rVgSRB": ["Ćōĺĺàƥśē ", ["docName"]],
"rVxu1k": ["Ńō ƥàĝēś ĺĩńķ ĥēŕē ŷēţ."],
"rXz97P": ["Ńũḿƀēŕēď ĺĩśţ ōƒ ĩţēḿś."],
@@ -2489,6 +2523,7 @@
"xNyj3h": ["Ŕēĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ"],
"xOTzt5": ["Ĵũśţ ńōŵ"],
"xSVO3J": ["Ŵĥàţ ĝēţś ćŕēàţēď"],
+ "xV5sXw": [["0"], "ŵ àĝō"],
"xWEvuo": ["Àśķ ÀĨ"],
"xXo8FT": ["Śàvē ƒàĩĺēď: ", ["error"]],
"xYMPyY": [
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 6f69eca11..c5c4c279b 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -113,6 +113,11 @@ msgstr ""
msgid "(user-level only)"
msgstr ""
+#. placeholder {0}: preview.backlinkCount
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0, plural, one {# backlink} other {# backlinks}}"
+msgstr ""
+
#. placeholder {0}: tag.count
#: src/components/CommandPalette.tsx
msgid "{0, plural, one {# doc} other {# docs}}"
@@ -177,21 +182,42 @@ msgstr ""
msgid "{0}/{1} {2}"
msgstr ""
+#. placeholder {0}: Math.floor(diff / DAY_MS)
#. placeholder {0}: Math.floor(diffSec / 86400)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}d ago"
msgstr ""
+#. placeholder {0}: Math.floor(diff / HOUR_MS)
#. placeholder {0}: Math.floor(diffSec / 3600)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}h ago"
msgstr ""
+#. placeholder {0}: Math.floor(diff / MINUTE_MS)
#. placeholder {0}: Math.floor(diffSec / 60)
#: src/components/FolderTimelineCard.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "{0}m ago"
msgstr ""
+#. placeholder {0}: Math.floor(diff / MONTH_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}mo ago"
+msgstr ""
+
+#. placeholder {0}: Math.floor(diff / WEEK_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}w ago"
+msgstr ""
+
+#. placeholder {0}: Math.floor(diff / YEAR_MS)
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "{0}y ago"
+msgstr ""
+
#: src/components/EditorTabs.tsx
msgid "{accessibleLabel} (conflict)"
msgstr ""
@@ -1252,6 +1278,7 @@ msgstr ""
#: src/components/PublishToGitHubDialog.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SeedDialog.tsx
+#: src/components/settings/LinkPreviewsSection.tsx
#: src/components/settings/SearchSection.tsx
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
@@ -2530,6 +2557,10 @@ msgstr ""
msgid "Diff unavailable"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Disable external link previews"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Disable git auto-sync"
msgstr ""
@@ -2770,6 +2801,10 @@ msgstr ""
msgid "Edit with AI"
msgstr ""
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "Edited {editedAgo}"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "edited template"
msgstr ""
@@ -2858,6 +2893,10 @@ msgstr ""
msgid "Enable auto-sync"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Enable external link previews"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Enable git auto-sync"
msgstr ""
@@ -2973,6 +3012,14 @@ msgstr ""
msgid "External link"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "External link previews"
+msgstr ""
+
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "External link previews show a card with the site name, page title, and description when you hover a link."
+msgstr ""
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
msgid "External wiki link"
msgstr ""
@@ -3022,6 +3069,10 @@ msgstr ""
msgid "Failed to delete property"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Failed to disable link previews — {detail}"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to disable semantic search — {detail}"
msgstr ""
@@ -3034,6 +3085,10 @@ msgstr ""
msgid "Failed to duplicate path"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Failed to enable link previews — {detail}"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Failed to enable semantic search — {detail}"
msgstr ""
@@ -3984,6 +4039,7 @@ msgstr ""
#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TimelinePanel.tsx
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "just now"
msgstr ""
@@ -4060,6 +4116,15 @@ msgstr ""
msgid "Link copied."
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Link preview settings not yet loaded — try again in a moment"
+msgstr ""
+
+#: src/components/settings/LinkPreviewsSection.tsx
+#: src/components/settings/SettingsDialogShell.tsx
+msgid "Link previews"
+msgstr ""
+
#: src/editor/extensions/InternalLinkPropPanel.tsx
msgid "Link target"
msgstr ""
@@ -4657,6 +4722,10 @@ msgstr ""
msgid "No emoji found."
msgstr ""
+#: src/editor/link-preview/InternalDocPreviewCard.tsx
+msgid "No excerpt"
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid "No file or folder selected"
msgstr ""
@@ -4924,6 +4993,10 @@ msgstr ""
msgid "Off"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Off — external links show only their URL. No requests leave this computer."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Off — search ranks by keyword only. No content leaves this computer."
msgstr ""
@@ -4944,6 +5017,10 @@ msgstr ""
msgid "On"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "On — hovering an external link sends its URL to the destination site to fetch a preview."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."
msgstr ""
@@ -4966,6 +5043,10 @@ msgstr ""
msgid "Only collaborators"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Only external links trigger a request. Links to other documents in this project preview from the local index and never leave your computer."
+msgstr ""
+
#: src/components/FileSidebar.tsx
#: src/components/NotInSidebarIndicator.tsx
msgid "Only markdown files"
@@ -5541,6 +5622,10 @@ msgstr ""
msgid "Preview unavailable: {errorDetail}"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr ""
@@ -6589,6 +6674,10 @@ msgstr ""
msgid "Show {hidden} more"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
+msgstr ""
+
#: src/components/settings/OkignoreSection.tsx
msgid "Show advanced"
msgstr ""
@@ -7508,6 +7597,14 @@ msgstr ""
msgid "This sends content off your machine"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "This sends the link's address off your machine"
+msgstr ""
+
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "This setting is per-machine and isn't shared with collaborators."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "This setting is per-machine and isn't shared with collaborators. It needs an API key set with <0>ok embeddings set-key</0>."
msgstr ""
@@ -7639,10 +7736,15 @@ msgstr ""
msgid "Turn off Only markdown files"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
#: src/components/settings/SearchSection.tsx
msgid "Turn on"
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "Turn on external link previews?"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "Turn on semantic search?"
msgstr ""
@@ -8093,6 +8195,10 @@ msgstr ""
msgid "When the agent runs its scheduled work."
msgstr ""
+#: src/components/settings/LinkPreviewsSection.tsx
+msgid "When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Where newly added attachments are placed."
msgstr ""
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index fec26542e..6d28930eb 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -88,6 +88,11 @@ const EXEMPT_HANDLERS = new Set([
'handleBacklinks',
'handleBacklinkCounts',
'handleForwardLinks',
+ // POST /api/link-preview — read-only external metadata fetch for the editor
+ // hover card. No Y.Doc / vault mutation and no agent-authored content; its
+ // access control is the route's own anti-proxy gate plus the SSRF guard, not
+ // agent-identity attribution.
+ 'handleLinkPreview',
'handleLinkGraph',
'handleSearch',
// GET /api/semantic-status — read-only setup/coverage probe for the Settings
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 75761ffa7..2c65e5ab0 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -79,6 +79,9 @@ const EXEMPT_HANDLERS = new Set([
'handleBacklinks',
'handleBacklinkCounts',
'handleForwardLinks',
+ // POST /api/link-preview — read-only external metadata fetch; never writes a
+ // doc, so there is no in-conflict write to gate.
+ 'handleLinkPreview',
'handleLinkGraph',
'handleSearch',
// GET /api/semantic-status — read-only setup/coverage probe; no Y.Doc
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index 996a18d9c..5734ecbb1 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -195,7 +195,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
]);
});
- test('project-local-strict fields cover autoSync.enabled + appearance.sidebar.* + search.semantic.* + terminal.enabled', () => {
+ test('project-local-strict fields cover autoSync.enabled + appearance.sidebar.* + linkPreviews.enabled + search.semantic.* + terminal.enabled', () => {
// Project-local fields are per-machine, per-project: each teammate's
// choice never crosses the git boundary.
// `<projectDir>/.ok/local/config.yml` is gitignored and never mirrored
@@ -205,6 +205,9 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
// per-machine opt-in for embeddings search — enabling it sends content to
// a third-party provider (egress) and needs a local API key, so the choice
// (and its non-secret provider knobs) is inherently per-machine.
+ // `linkPreviews.enabled` is the per-machine opt-in for external link-hover
+ // previews — enabling it sends the hovered URL to the destination site
+ // (egress), so like semantic search the choice is inherently per-machine.
// `terminal.enabled` gates the in-app real OS shell: a full-privilege
// capability consented per-machine, never inherited via a clone.
const leaves: { path: string[]; schema: unknown }[] = [];
@@ -219,6 +222,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'appearance.sidebar.showOnlyMarkdownFiles',
'appearance.sidebar.showSkillsSection',
'autoSync.enabled',
+ 'linkPreviews.enabled',
'search.semantic.baseUrl',
'search.semantic.dimensions',
'search.semantic.enabled',
diff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.ts
index b76d1b070..fbc6359fe 100644
--- a/packages/core/src/config/schema-leaf.test.ts
+++ b/packages/core/src/config/schema-leaf.test.ts
@@ -59,6 +59,16 @@ describe('getLeafFieldMeta', () => {
});
});
+ test('returns project-local metadata for the linkPreviews.enabled egress opt-in', () => {
+ const meta = getLeafFieldMeta(ConfigSchema, ['linkPreviews', 'enabled']);
+ expect(meta).toEqual({
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description: expect.any(String),
+ });
+ });
+
test('returns undefined for an unresolved path', () => {
const meta = getLeafFieldMeta(ConfigSchema, ['content', 'nonexistent']);
expect(meta).toBeUndefined();
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index 065caa43d..a74ab349a 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -170,6 +170,20 @@ describe('appearance.sidebar view toggles', () => {
});
});
+describe('linkPreviews.enabled (external link-hover preview egress opt-in)', () => {
+ test('defaults to disabled when the block is absent', () => {
+ expect(ConfigSchema.parse({}).linkPreviews).toEqual({ enabled: false });
+ });
+
+ test('defaults enabled to false when linkPreviews is present but enabled is absent', () => {
+ expect(ConfigSchema.parse({ linkPreviews: {} }).linkPreviews.enabled).toBe(false);
+ });
+
+ test('accepts an explicit opt-in', () => {
+ expect(ConfigSchema.parse({ linkPreviews: { enabled: true } }).linkPreviews.enabled).toBe(true);
+ });
+});
+
describe('legacy upload.* keys remain non-authoritative', () => {
test('upload.* keys pass through looseObject without schema error', () => {
const result = ConfigSchema.safeParse({
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 4641c28ed..4d5d3c860 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -534,6 +534,26 @@ export const ConfigSchema = z.looseObject({
model: DEFAULT_EMBEDDINGS_MODEL,
},
}),
+ // PROJECT-LOCAL scope: external link-hover previews send the hovered URL to
+ // the destination site to fetch its metadata (egress), so — like semantic
+ // search — each teammate opts in on their own machine rather than inheriting
+ // one collaborator's egress choice through git. Default OFF; the feature
+ // ships dark. Internal (document-to-document) link previews are read entirely
+ // from the local index with no network request and are NOT gated by this key.
+ linkPreviews: z
+ .looseObject({
+ enabled: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ "Show a rich preview card (site name, page title, description, favicon) when you hover an external link in the editor. When ON, hovering an external link sends that link's URL to the destination site to fetch its preview metadata — outbound egress, one request per previewed link. Default OFF. Per-machine (project-local) — not shared with collaborators. Previews of links to other documents in this project are read from the local index with no network request and are always on.",
+ })
+ .default(false),
+ })
+ .default({ enabled: false }),
});
export type Config = z.infer<typeof ConfigSchema>;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 2f25d0d12..e948da79a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -619,6 +619,12 @@ export {
LinkGraphNodeSchema,
type LinkGraphSuccess,
LinkGraphSuccessSchema,
+ type LinkPreviewMetadata,
+ LinkPreviewMetadataSchema,
+ type LinkPreviewRequest,
+ LinkPreviewRequestSchema,
+ type LinkPreviewResponse,
+ LinkPreviewResponseSchema,
type LocalOpAuthEmptySuccess,
LocalOpAuthEmptySuccessSchema,
type LocalOpAuthHostRequest,
diff --git a/packages/core/src/schemas/api/index.ts b/packages/core/src/schemas/api/index.ts
index 9591d4d9d..0df13e4ca 100644
--- a/packages/core/src/schemas/api/index.ts
+++ b/packages/core/src/schemas/api/index.ts
@@ -25,6 +25,7 @@ export * from './client-logs.ts';
export * from './document-read.ts';
export * from './embed-detect.ts';
export * from './history.ts';
+export * from './link-preview.ts';
export * from './links-orphans.ts';
export * from './local-op.ts';
export * from './metrics.ts';
diff --git a/packages/core/src/schemas/api/link-preview.ts b/packages/core/src/schemas/api/link-preview.ts
new file mode 100644
index 000000000..30e461096
--- /dev/null
+++ b/packages/core/src/schemas/api/link-preview.ts
@@ -0,0 +1,59 @@
+/**
+ * Wire shape for the external link-preview card. Produced server-side by the
+ * SSRF-guarded fetch + bounded head-scan parse, served by `POST /api/link-preview`,
+ * and rendered by the editor hover panel. Lives in `packages/core` so producer
+ * and consumer bind to one shape.
+ *
+ * Every field except `domain` is optional: a site that exposes no OG/`<title>`
+ * tags still yields `{ domain }`, and the card renders whatever is present. The
+ * registrable domain is always derived from the request URL (never from fetched
+ * metadata) so a page cannot claim to be a site it is not. `faviconDataUri`, when
+ * present, is a self-contained `data:image/…` URI the server built from validated
+ * bytes — the card never hotlinks a remote image.
+ */
+
+import type { StandardSchemaV1 } from '@standard-schema/spec';
+import { z } from 'zod';
+
+export const LinkPreviewMetadataSchema = z
+ .object({
+ domain: z.string().min(1),
+ title: z.string().optional(),
+ description: z.string().optional(),
+ siteName: z.string().optional(),
+ faviconDataUri: z.string().optional(),
+ })
+ .loose() satisfies StandardSchemaV1;
+export type LinkPreviewMetadata = z.infer<typeof LinkPreviewMetadataSchema>;
+
+/**
+ * Request body for `POST /api/link-preview`: the hovered URL to preview. Only
+ * "is a string" is asserted here — every scheme/host/redirect check lives in
+ * the SSRF-guarded fetch downstream, which treats the value as hostile. An
+ * empty or malformed URL flows through to a `{ ok: false }` outcome (the guard
+ * rejects it) rather than being special-cased at the schema boundary.
+ */
+export const LinkPreviewRequestSchema = z
+ .object({ url: z.string() })
+ .loose() satisfies StandardSchemaV1;
+export type LinkPreviewRequest = z.infer<typeof LinkPreviewRequestSchema>;
+
+/**
+ * Response envelope for `POST /api/link-preview`. A well-formed, authorized
+ * request always returns HTTP 200 with this discriminated outcome: `ok: true`
+ * with the assembled card metadata, or `ok: false` with a bounded reason code
+ * the renderer treats as "fall back to the URL pill". On the wire the reason is
+ * deliberately coarse — `'disabled'` when the egress opt-in is off, `'blocked'`
+ * for every guard/fetch rejection — so the body cannot become an
+ * internal-network-topology oracle; the granular taxonomy stays in server logs
+ * and the local cache. Anti-proxy and body-shape rejections are separate
+ * RFC 9457 problem responses, not this envelope.
+ *
+ * Union members are `.loose()` per the `share.ts` forward-compat convention: a
+ * future additive field must not be stripped or rejected by an older client.
+ */
+export const LinkPreviewResponseSchema = z.discriminatedUnion('ok', [
+ z.object({ ok: z.literal(true), metadata: LinkPreviewMetadataSchema }).loose(),
+ z.object({ ok: z.literal(false), reason: z.string() }).loose(),
+]) satisfies StandardSchemaV1;
+export type LinkPreviewResponse = z.infer<typeof LinkPreviewResponseSchema>;
diff --git a/packages/server/package.json b/packages/server/package.json
index 8c54710da..df1562ed7 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -39,6 +39,7 @@
"file-type": "^22.0.1",
"happy-dom": "^20.10.2",
"ignore": "^5.3.2",
+ "ipaddr.js": "^2.3.0",
"just-bash": "^2.14.3",
"mermaid": "^11.14.0",
"mrmime": "^2.0.1",
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index fbe365f02..9f96dd825 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -102,6 +102,8 @@ import {
LINKABLE_ASSET_EXTENSIONS,
type LifecycleStatus,
LinkGraphSuccessSchema,
+ LinkPreviewRequestSchema,
+ LinkPreviewResponseSchema,
LocalOpAuthEmptySuccessSchema,
type LocalOpAuthHostRequest,
LocalOpAuthHostRequestSchema,
@@ -481,6 +483,10 @@ import {
import { validateBody, withValidation } from './http/request-validation.ts';
import { successResponse } from './http/success-response.ts';
import { initContent } from './init-project.ts';
+import { guardedFetch } from './link-preview/guarded-fetch.ts';
+import { buildLinkPreviewMetadata, type GuardedFetch } from './link-preview/metadata.ts';
+import { LinkPreviewCache, type LinkPreviewOutcome } from './link-preview/preview-cache.ts';
+import { classifyLinkPreviewRequest } from './link-preview/request-gate.ts';
import {
checkLocalOpSecurity,
createConcurrencyGuard,
@@ -2644,6 +2650,24 @@ export interface ApiExtensionOptions {
* Save-version and rollback do NOT mutate the parent git repo.
*/
projectDir?: string;
+ /**
+ * SSRF-guarded fetch used by `POST /api/link-preview` for both the page and
+ * the favicon. Defaults to the real `guardedFetch` chokepoint; tests inject a
+ * fake that returns chosen bytes so the route → parse → cache → envelope
+ * wiring can be exercised without real network egress. Production never sets
+ * it, so the guard is always the real one.
+ */
+ linkPreviewFetch?: GuardedFetch;
+ /**
+ * Fresh-read getter for the project-local `linkPreviews.enabled` egress
+ * opt-in — the same per-request fresh-read contract as
+ * `getSemanticSimilarityFloor`, so a runtime Settings toggle applies to the
+ * next hover without a restart. FAIL-CLOSED: when omitted, or when the read
+ * throws, `POST /api/link-preview` treats previews as disabled and performs
+ * no outbound fetch — the renderer-side gate is a UX optimization, never the
+ * enforcement point.
+ */
+ getLinkPreviewsEnabled?: () => boolean;
/**
* Basename-index resolver for `![[photo.png]]` wiki-embed refs. Threaded
* into every server-side `mdManager.parseWithFallback` call (managed-rename
@@ -2867,6 +2891,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
getSemanticSimilarityFloor,
embeddingsSecretsFile,
ephemeral = false,
+ linkPreviewFetch,
+ getLinkPreviewsEnabled,
} = options;
// Concurrency guard: at most 1 in-flight request per local-op endpoint
@@ -17457,6 +17483,147 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'semantic-status', method: 'GET', skipBodyParse: true },
);
+ // ───────────────────── Link preview (external hover cards) ─────────────────
+ // Fetches page metadata for an external link on the user's behalf, so it is
+ // guarded on two independent axes: an anti-proxy gate decides WHO may ask, and
+ // the SSRF-guarded fetch decides WHERE the server may reach. The gate refuses
+ // absent / `null` / non-loopback Origins that the shared /api/* allowlist would
+ // wave through, because an admitted caller would be a readable server-side
+ // request-forgery proxy for any local browser tab. Read-only — kept out of
+ // MUTATING_ROUTES.
+ const LINK_PREVIEW_HANDLER = 'link-preview';
+ // Ephemeral single-file mode keeps zero user-dir artifacts, so its cache stays
+ // in memory; otherwise it lives beside the other project-local sidecars.
+ const linkPreviewCacheDir = ephemeral
+ ? null
+ : resolve(projectDir ?? contentDir, '.ok', 'local', 'link-previews');
+ const linkPreviewCache = new LinkPreviewCache({ cacheDir: linkPreviewCacheDir });
+ // Load the disk cache once, lazily, before the first lookup. init() never
+ // throws; serializing it ahead of load() keeps a warm entry from being
+ // clobbered by a late disk read.
+ let linkPreviewCacheInit: Promise<void> | null = null;
+ const ensureLinkPreviewCacheReady = (): Promise<void> => {
+ linkPreviewCacheInit ??= linkPreviewCache.init();
+ return linkPreviewCacheInit;
+ };
+ const linkPreviewFetchImpl: GuardedFetch = linkPreviewFetch ?? guardedFetch;
+
+ // The cache-miss path: one SSRF-guarded page fetch, a bounded head-scan parse,
+ // and a favicon fetch through the SAME chokepoint. Never throws — the guard
+ // and the parser each absorb their own failures into a bounded reason.
+ async function computeLinkPreview(rawUrl: string): Promise<LinkPreviewOutcome> {
+ const fetched = await linkPreviewFetchImpl(rawUrl);
+ if (!fetched.ok) return { ok: false, reason: fetched.reason };
+ const metadata = await buildLinkPreviewMetadata({
+ html: new TextDecoder().decode(fetched.body),
+ requestUrl: rawUrl,
+ finalUrl: fetched.finalUrl,
+ fetch: linkPreviewFetchImpl,
+ });
+ return { ok: true, metadata };
+ }
+
+ // The egress opt-in is enforced HERE, not only in the renderer: the anti-proxy
+ // gate admits ANY loopback http(s) origin by design, so without this check a
+ // second local app could drive outbound fetches while the user has previews
+ // OFF. Fail-closed (absent getter or a throwing read = disabled) and evaluated
+ // fresh per request so a Settings toggle applies without a restart.
+ const linkPreviewsEnabled = (): boolean => {
+ try {
+ return getLinkPreviewsEnabled?.() === true;
+ } catch {
+ return false;
+ }
+ };
+
+ const handleLinkPreview = withValidation(
+ LinkPreviewRequestSchema,
+ async (_req, res, body) => {
+ try {
+ // Checked BEFORE the cache is touched so the disabled path can never
+ // record a negative entry that would outlive re-enabling.
+ if (!linkPreviewsEnabled()) {
+ // Outcome instrumentation: one greppable category per request.
+ // Category ONLY, never the URL, hostname, resolved IP, or fetched
+ // content.
+ log.debug({ outcome: 'disabled' }, '[link-preview] request outcome');
+ successResponse(
+ res,
+ 200,
+ LinkPreviewResponseSchema,
+ { ok: false, reason: 'disabled' },
+ { handler: LINK_PREVIEW_HANDLER },
+ );
+ return;
+ }
+ await ensureLinkPreviewCacheReady();
+ // Side flag on the compute closure: load() invokes compute only on a
+ // cache miss, so hit-vs-computed falls out here without widening the
+ // cache API.
+ let computed = false;
+ const outcome = await linkPreviewCache.load(body.url, () => {
+ computed = true;
+ return computeLinkPreview(body.url);
+ });
+ // Persist is best-effort and never throws; fire-and-forget so a slow disk
+ // write can't stall the response.
+ void linkPreviewCache.persist();
+ // Rejections cross the wire with ONE coarse reason. The granular guard
+ // taxonomy (private-ip / dns-failure / non-html / …) stays in local logs
+ // and the on-disk cache for debugging, but returning it would let a
+ // loopback caller pair chosen hostnames with reasons to enumerate
+ // internal names; the renderer ignores the field either way.
+ const wireOutcome: LinkPreviewOutcome = outcome.ok
+ ? outcome
+ : { ok: false, reason: 'blocked' };
+ // Outcome instrumentation: one greppable category per request
+ // (disabled / cache-hit / fetched-ok / fallback). A negative cache hit
+ // logs cache-hit (served without a fetch). Category ONLY, never the
+ // URL, hostname, resolved IP, or fetched content; the granular
+ // rejection taxonomy is already logged at the guarded-fetch chokepoint.
+ log.debug(
+ { outcome: computed ? (outcome.ok ? 'fetched-ok' : 'fallback') : 'cache-hit' },
+ '[link-preview] request outcome',
+ );
+ successResponse(res, 200, LinkPreviewResponseSchema, wireOutcome, {
+ handler: LINK_PREVIEW_HANDLER,
+ });
+ } catch (e) {
+ errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
+ handler: LINK_PREVIEW_HANDLER,
+ cause: e,
+ });
+ }
+ },
+ {
+ handler: LINK_PREVIEW_HANDLER,
+ method: 'POST',
+ // Reject a cross-origin / null-origin / non-JSON caller before the body is
+ // read, so a bypass request never reaches the outbound fetch.
+ preBodyGate: (req, res) => {
+ const verdict = classifyLinkPreviewRequest({
+ origin: req.headers.origin,
+ contentType: req.headers['content-type'],
+ });
+ if (verdict.ok) return true;
+ if (verdict.reason === 'origin') {
+ errorResponse(res, 403, 'urn:ok:error:invalid-origin', 'Origin not allowed.', {
+ handler: LINK_PREVIEW_HANDLER,
+ });
+ } else {
+ errorResponse(
+ res,
+ 400,
+ 'urn:ok:error:invalid-request',
+ 'Content-Type must be application/json.',
+ { handler: LINK_PREVIEW_HANDLER },
+ );
+ }
+ return false;
+ },
+ },
+ );
+
const routes: Record<string, (req: IncomingMessage, res: ServerResponse) => Promise<void>> = {
'/api/config': handleApiConfig,
'/api/asset': handleAsset,
@@ -17465,6 +17632,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/documents': handleDocumentList,
'/api/backlinks': handleBacklinks,
'/api/backlink-counts': handleBacklinkCounts,
+ '/api/link-preview': handleLinkPreview,
'/api/forward-links': handleForwardLinks,
'/api/link-graph': handleLinkGraph,
'/api/dead-links': handleDeadLinks,
diff --git a/packages/server/src/api-link-preview.test.ts b/packages/server/src/api-link-preview.test.ts
new file mode 100644
index 000000000..285cc3254
--- /dev/null
+++ b/packages/server/src/api-link-preview.test.ts
@@ -0,0 +1,464 @@
+import { afterEach, beforeEach, describe, expect, type Mock, spyOn, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import type { IncomingMessage, ServerResponse } from 'node:http';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createApiExtension } from './api-extension.ts';
+import type { GuardRejectReason } from './link-preview/guarded-fetch.ts';
+import type { GuardedFetch } from './link-preview/metadata.ts';
+import { PinoLogger } from './logger.ts';
+import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
+
+const PREVIEW_URL = '/api/link-preview';
+// 8-byte PNG signature (+ padding) — enough for the metadata layer's magic-byte
+// sniff to recognize the favicon bytes as a real image.
+const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00]);
+
+/**
+ * Stand-in for the SSRF-guarded chokepoint. It does NOT re-implement the guard —
+ * it is the network boundary the route calls, so the route → parse → cache →
+ * envelope wiring can be exercised without egress. The favicon fetch is
+ * identified by its image content-type predicate. `calls` records every fetch so
+ * a test can prove "no fetch on rejection" and "one fetch across two hovers".
+ */
+function makeFakeFetch(config: {
+ html?: string;
+ reason?: GuardRejectReason;
+ faviconBytes?: Uint8Array;
+}): { impl: GuardedFetch; calls: string[] } {
+ const calls: string[] = [];
+ const impl: GuardedFetch = async (url, options) => {
+ calls.push(url);
+ const isFaviconFetch = options?.allowContentType?.('image/png') === true;
+ if (isFaviconFetch) {
+ if (!config.faviconBytes) return { ok: false, reason: 'non-html' };
+ return { ok: true, body: config.faviconBytes, contentType: 'image/png', finalUrl: url };
+ }
+ if (config.reason) return { ok: false, reason: config.reason };
+ return {
+ ok: true,
+ body: new TextEncoder().encode(config.html ?? ''),
+ contentType: 'text/html',
+ finalUrl: url,
+ };
+ };
+ return { impl, calls };
+}
+
+interface Harness {
+ baseURL: string;
+ close: () => Promise<void>;
+}
+
+/**
+ * `getLinkPreviewsEnabled` defaults to `() => true` so the pre-existing gate /
+ * outcome tests exercise the enabled path; pass `null` to OMIT the option
+ * entirely (the fail-closed case), or a custom getter for the enforcement
+ * tests.
+ */
+async function startHarness(
+ contentDir: string,
+ linkPreviewFetch?: GuardedFetch,
+ getLinkPreviewsEnabled: (() => boolean) | null = () => true,
+): Promise<Harness> {
+ const ext = createApiExtension({
+ hocuspocus: {} as Parameters<typeof createApiExtension>[0]['hocuspocus'],
+ sessionManager: {} as Parameters<typeof createApiExtension>[0]['sessionManager'],
+ contentDir,
+ serverInstanceId: 'test-server',
+ getFileIndex: () => new Map(),
+ linkPreviewFetch,
+ ...(getLinkPreviewsEnabled === null ? {} : { getLinkPreviewsEnabled }),
+ });
+ const server: Server = createServer((req, res) => {
+ void (
+ ext as {
+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
+ }
+ ).onRequest({ request: req, response: res });
+ });
+ const { baseUrl } = await listenOnLoopback(server);
+ return {
+ baseURL: baseUrl,
+ close: () =>
+ new Promise<void>((resolve, reject) => {
+ server.close((err) => (err ? reject(err) : resolve()));
+ }),
+ };
+}
+
+interface PostOptions {
+ origin?: string | null;
+ contentType?: string | null;
+ method?: string;
+ body?: string;
+}
+
+function postPreview(baseURL: string, options: PostOptions = {}): Promise<Response> {
+ const headers: Record<string, string> = {};
+ if (options.origin != null) headers.Origin = options.origin;
+ if (options.contentType != null) headers['Content-Type'] = options.contentType;
+ return fetch(`${baseURL}${PREVIEW_URL}`, {
+ method: options.method ?? 'POST',
+ headers,
+ body: options.method === 'GET' ? undefined : (options.body ?? '{}'),
+ });
+}
+
+/** Per-describe scaffolding: a tmp content dir plus a single harness the test
+ * opens via `open()` and `afterEach` tears down. */
+function useHarness(): {
+ open: (
+ linkPreviewFetch?: GuardedFetch,
+ getLinkPreviewsEnabled?: (() => boolean) | null,
+ ) => Promise<Harness>;
+} {
+ let tmpDir = '';
+ let contentDir = '';
+ let opened: Harness | null = null;
+
+ beforeEach(() => {
+ tmpDir = mkdtempSync(join(tmpdir(), 'ok-link-preview-'));
+ contentDir = join(tmpDir, 'content');
+ mkdirSync(contentDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ if (opened) {
+ await opened.close();
+ opened = null;
+ }
+ rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ return {
+ open: async (
+ linkPreviewFetch?: GuardedFetch,
+ getLinkPreviewsEnabled: (() => boolean) | null = () => true,
+ ) => {
+ opened = await startHarness(contentDir, linkPreviewFetch, getLinkPreviewsEnabled);
+ return opened;
+ },
+ };
+}
+
+const jsonPost = (url: string) => ({
+ contentType: 'application/json',
+ body: JSON.stringify({ url }),
+});
+
+describe('POST /api/link-preview anti-proxy gate', () => {
+ const rig = useHarness();
+
+ test('rejects a cross-origin Origin without fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: 'https://evil.example',
+ ...jsonPost('https://example.com'),
+ });
+ expect(res.status).toBe(403);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('rejects Origin: null (sandboxed iframe) without fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: 'null',
+ ...jsonPost('https://example.com'),
+ });
+ expect(res.status).toBe(403);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('rejects an absent Origin without fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: null,
+ ...jsonPost('https://example.com'),
+ });
+ expect(res.status).toBe(403);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('rejects a GET without fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, { method: 'GET', origin: harness.baseURL });
+ expect(res.status).toBe(405);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('rejects a non-JSON content type without fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ contentType: 'text/plain',
+ body: JSON.stringify({ url: 'https://example.com' }),
+ });
+ expect(res.status).toBe(400);
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('rejects a body missing the url field before fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ contentType: 'application/json',
+ body: JSON.stringify({}),
+ });
+ expect(res.status).toBe(400);
+ expect(fake.calls).toHaveLength(0);
+ });
+});
+
+describe('POST /api/link-preview preview outcomes', () => {
+ const rig = useHarness();
+
+ test('returns card metadata for a well-formed same-origin POST', async () => {
+ const fake = makeFakeFetch({
+ html: '<head><title>Example Domain</title><meta name="description" content="A demo page"></head>',
+ });
+ const harness = await rig.open(fake.impl);
+
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/page'),
+ });
+
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { ok: boolean; metadata?: Record<string, string> };
+ expect(body.ok).toBe(true);
+ expect(body.metadata?.domain).toBe('example.com');
+ expect(body.metadata?.title).toBe('Example Domain');
+ expect(body.metadata?.description).toBe('A demo page');
+ expect(fake.calls).toContain('https://example.com/page');
+ });
+
+ test('carries a validated favicon through as a data URI', async () => {
+ const fake = makeFakeFetch({
+ html: '<title>Iconic</title><link rel="icon" href="/favicon.ico">',
+ faviconBytes: PNG_BYTES,
+ });
+ const harness = await rig.open(fake.impl);
+
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/'),
+ });
+
+ const body = (await res.json()) as { ok: boolean; metadata?: { faviconDataUri?: string } };
+ expect(body.ok).toBe(true);
+ expect(body.metadata?.faviconDataUri).toStartWith('data:image/png;base64,');
+ });
+
+ test('a guard rejection crosses the wire with the single coarse reason', async () => {
+ // The guard produced the granular 'private-ip' (kept in logs + cache), but
+ // the response must not distinguish it from any other rejection — a
+ // loopback caller could otherwise enumerate internal names by pairing
+ // chosen hostnames with reasons.
+ const fake = makeFakeFetch({ reason: 'private-ip' });
+ const harness = await rig.open(fake.impl);
+
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://intranet.example'),
+ });
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: false, reason: 'blocked' });
+ });
+
+ test('distinct guard reasons are indistinguishable on the wire', async () => {
+ const dnsFake = makeFakeFetch({ reason: 'dns-failure' });
+ const harness = await rig.open(dnsFake.impl);
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://does-not-resolve.example'),
+ });
+ expect(await res.json()).toEqual({ ok: false, reason: 'blocked' });
+ });
+
+ test('serves the cache-hit fast path without re-fetching', async () => {
+ const fake = makeFakeFetch({ html: '<title>Cached</title>' });
+ const harness = await rig.open(fake.impl);
+ const url = 'https://example.com/cached';
+
+ const first = await postPreview(harness.baseURL, { origin: harness.baseURL, ...jsonPost(url) });
+ const second = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost(url),
+ });
+
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ const firstBody = await first.json();
+ const secondBody = await second.json();
+ expect(secondBody).toEqual(firstBody);
+ // The page URL was fetched exactly once; the second hover was served warm.
+ expect(fake.calls.filter((u) => u === url)).toHaveLength(1);
+ });
+});
+
+describe('POST /api/link-preview server-side linkPreviews.enabled enforcement', () => {
+ const rig = useHarness();
+
+ test('previews disabled: non-ok envelope, zero outbound fetches', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl, () => false);
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/'),
+ });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: false, reason: 'disabled' });
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('getter omitted entirely: fail-closed, zero outbound fetches', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl, null);
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/'),
+ });
+ expect(await res.json()).toEqual({ ok: false, reason: 'disabled' });
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('a throwing config read is fail-closed, zero outbound fetches', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl, () => {
+ throw new Error('config read failed');
+ });
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/'),
+ });
+ expect(await res.json()).toEqual({ ok: false, reason: 'disabled' });
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('the disabled short-circuit never poisons the cache: enabling serves a fresh preview', async () => {
+ const fake = makeFakeFetch({ html: '<title>Fresh</title>' });
+ let enabled = false;
+ // Fresh-read contract: the getter is consulted per request, so flipping the
+ // flag mid-harness models a runtime Settings toggle without a restart.
+ const harness = await rig.open(fake.impl, () => enabled);
+ const url = 'https://example.com/toggled';
+
+ const off = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost(url),
+ });
+ expect(await off.json()).toEqual({ ok: false, reason: 'disabled' });
+ expect(fake.calls).toHaveLength(0);
+
+ enabled = true;
+ const on = await postPreview(harness.baseURL, { origin: harness.baseURL, ...jsonPost(url) });
+ const body = (await on.json()) as { ok: boolean; metadata?: { title?: string } };
+ expect(body.ok).toBe(true);
+ expect(body.metadata?.title).toBe('Fresh');
+ });
+});
+
+describe('POST /api/link-preview real SSRF chokepoint', () => {
+ // No injected fetch: these exercise the production guardedFetch end-to-end
+ // through the route, proving the real chokepoint is wired in.
+ const rig = useHarness();
+
+ test('rejects a private-IP target with a structured failure', async () => {
+ const harness = await rig.open();
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('http://127.0.0.1:9'),
+ });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: false, reason: 'blocked' });
+ });
+
+ test('treats an empty url as a structured failure', async () => {
+ const harness = await rig.open();
+ const res = await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost(''),
+ });
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as { ok: boolean; reason?: string };
+ expect(body.ok).toBe(false);
+ expect(typeof body.reason).toBe('string');
+ });
+});
+
+describe('POST /api/link-preview outcome instrumentation', () => {
+ const rig = useHarness();
+
+ // Spy at the prototype: api-extension.ts holds a module-level
+ // `getLogger('api')` binding, and sibling test files' configure()/reset()
+ // calls clear the factory's instance cache, so an instance-level spy taken
+ // here could wrap a DIFFERENT logger than the one the route actually uses.
+ let debugSpy: Mock<PinoLogger['debug']>;
+
+ beforeEach(() => {
+ debugSpy = spyOn(PinoLogger.prototype, 'debug');
+ });
+
+ afterEach(() => {
+ debugSpy.mockRestore();
+ });
+
+ /** The `outcome` categories logged by the route, in emission order. */
+ function loggedOutcomes(): unknown[] {
+ return debugSpy.mock.calls
+ .filter(([, message]) => message === '[link-preview] request outcome')
+ .map(([data]) => (data as { outcome?: unknown }).outcome);
+ }
+
+ test('the disabled short-circuit logs its outcome category', async () => {
+ const fake = makeFakeFetch({ html: '<title>never</title>' });
+ const harness = await rig.open(fake.impl, () => false);
+
+ await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://example.com/'),
+ });
+
+ expect(loggedOutcomes()).toEqual(['disabled']);
+ });
+
+ test('a fresh fetch logs fetched-ok and the warm re-hover logs cache-hit', async () => {
+ const fake = makeFakeFetch({ html: '<title>Logged</title>' });
+ const harness = await rig.open(fake.impl);
+ const url = 'https://example.com/logged';
+
+ await postPreview(harness.baseURL, { origin: harness.baseURL, ...jsonPost(url) });
+ await postPreview(harness.baseURL, { origin: harness.baseURL, ...jsonPost(url) });
+
+ expect(loggedOutcomes()).toEqual(['fetched-ok', 'cache-hit']);
+ });
+
+ test('a guard rejection logs fallback, and the record is the category alone', async () => {
+ const fake = makeFakeFetch({ reason: 'private-ip' });
+ const harness = await rig.open(fake.impl);
+
+ await postPreview(harness.baseURL, {
+ origin: harness.baseURL,
+ ...jsonPost('https://intranet.example/secret-path'),
+ });
+
+ expect(loggedOutcomes()).toEqual(['fallback']);
+ // Hygiene invariant: the outcome record carries the category and nothing
+ // else. The URL / hostname / resolved IP must never reach these lines.
+ const outcomeCalls = debugSpy.mock.calls.filter(
+ ([, message]) => message === '[link-preview] request outcome',
+ );
+ for (const [data] of outcomeCalls) {
+ expect(Object.keys(data as Record<string, unknown>)).toEqual(['outcome']);
+ }
+ });
+});
diff --git a/packages/server/src/link-preview/guarded-fetch.test.ts b/packages/server/src/link-preview/guarded-fetch.test.ts
new file mode 100644
index 000000000..aac37542a
--- /dev/null
+++ b/packages/server/src/link-preview/guarded-fetch.test.ts
@@ -0,0 +1,338 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createServer, type Server } from 'node:http';
+import { gzipSync } from 'node:zlib';
+import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';
+import {
+ DEFAULT_MAX_BYTES,
+ DEFAULT_MAX_REDIRECTS,
+ DEFAULT_TIMEOUT_MS,
+ guardedFetch,
+ type HostResolver,
+} from './guarded-fetch.ts';
+import { isPublicUnicastIp } from './ip-classifier.ts';
+
+// Force a hostname to a chosen address so the real validator can be exercised
+// without touching DNS. Anything that isn't a named internal host resolves to
+// the loopback rig.
+const forceResolve =
+ (map: Record<string, string>): HostResolver =>
+ async (hostname) => {
+ const address = map[hostname] ?? '127.0.0.1';
+ return [{ address, family: address.includes(':') ? 6 : 4 }];
+ };
+
+describe('guardedFetch admission (real classifier, no network reached)', () => {
+ test.each([
+ 'ftp://example.com/',
+ 'file:///etc/passwd',
+ 'gopher://example.com/',
+ 'data:text/html,x',
+ ])('rejects non-http(s) scheme %p as bad-scheme', async (url) => {
+ expect(await guardedFetch(url)).toEqual({ ok: false, reason: 'bad-scheme' });
+ });
+
+ test.each([
+ 'http://127.0.0.1/',
+ 'http://169.254.169.254/',
+ 'http://10.0.0.1/',
+ 'http://192.168.1.1/',
+ 'http://[::1]/',
+ // Encoded loopback spellings the classifier canonicalizes before deciding.
+ 'http://0x7f000001/',
+ 'http://2130706433/',
+ 'http://0177.0.0.1/',
+ ])('rejects private/reserved IP literal %p as private-ip', async (url) => {
+ expect(await guardedFetch(url)).toEqual({ ok: false, reason: 'private-ip' });
+ });
+
+ test('rejects a public hostname that DNS-resolves to loopback (no address override → real guard)', async () => {
+ const result = await guardedFetch('http://totally-public.example/', {
+ resolve: forceResolve({ 'totally-public.example': '127.0.0.1' }),
+ });
+ expect(result).toEqual({ ok: false, reason: 'private-ip' });
+ });
+
+ test('rejects a public hostname that resolves to a link-local metadata address', async () => {
+ const result = await guardedFetch('http://metadata.example/', {
+ resolve: forceResolve({ 'metadata.example': '169.254.169.254' }),
+ });
+ expect(result).toEqual({ ok: false, reason: 'private-ip' });
+ });
+
+ test('rejects when ANY resolved record is private, even if another is public', async () => {
+ const resolve: HostResolver = async () => [
+ { address: '93.184.216.34', family: 4 },
+ { address: '10.0.0.1', family: 4 },
+ ];
+ expect(await guardedFetch('http://mixed.example/', { resolve })).toEqual({
+ ok: false,
+ reason: 'private-ip',
+ });
+ });
+
+ test('rejects an empty DNS resolution as dns-failure', async () => {
+ const resolve: HostResolver = async () => [];
+ expect(await guardedFetch('http://void.example/', { resolve })).toEqual({
+ ok: false,
+ reason: 'dns-failure',
+ });
+ });
+
+ test('rejects a DNS resolution error as dns-failure', async () => {
+ const resolve: HostResolver = async () => {
+ throw new Error('NXDOMAIN');
+ };
+ expect(await guardedFetch('http://broken-dns.example/', { resolve })).toEqual({
+ ok: false,
+ reason: 'dns-failure',
+ });
+ });
+
+ test('rejects an unparseable URL as fetch-error', async () => {
+ expect(await guardedFetch('not a url')).toEqual({ ok: false, reason: 'fetch-error' });
+ });
+
+ test('caps are the specified defaults', () => {
+ expect(DEFAULT_MAX_BYTES).toBe(512 * 1024);
+ expect(DEFAULT_TIMEOUT_MS).toBe(5000);
+ expect(DEFAULT_MAX_REDIRECTS).toBe(3);
+ });
+});
+
+describe('guardedFetch against a loopback rig (real socket)', () => {
+ let server: Server;
+ let port: number;
+ let lastRequest: {
+ host?: string;
+ ua?: string;
+ acceptEncoding?: string;
+ cookie?: string;
+ authorization?: string;
+ referer?: string;
+ } | null = null;
+
+ // The rig binds loopback; a public hostname resolves to it via the injected
+ // resolver, and the guard is told to treat that one loopback address as
+ // public so post-admission behavior can be exercised over a real socket.
+ // Every OTHER address (including redirect targets) still runs the real
+ // classifier, so the SSRF property is decided by the real guard.
+ const rigResolver = forceResolve({ 'internal.example': '10.0.0.1' });
+ const allowRigLoopback = (ip: string) => ip === '127.0.0.1' || isPublicUnicastIp(ip);
+ const withRig = { resolve: rigResolver, isAddressAllowed: allowRigLoopback };
+
+ beforeAll(async () => {
+ server = createServer((req, res) => {
+ const path = req.url ?? '/';
+ if (path === '/ok') {
+ lastRequest = {
+ host: req.headers.host,
+ ua: req.headers['user-agent'],
+ acceptEncoding: req.headers['accept-encoding'],
+ cookie: req.headers.cookie,
+ authorization: req.headers.authorization,
+ referer: req.headers.referer,
+ };
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end('hello');
+ return;
+ }
+ if (path === '/redirect-once') {
+ res.writeHead(302, { Location: '/final' });
+ res.end();
+ return;
+ }
+ if (path === '/final') {
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.end('final page');
+ return;
+ }
+ if (path === '/redirect-internal-literal') {
+ res.writeHead(302, { Location: 'http://169.254.169.254/' });
+ res.end();
+ return;
+ }
+ if (path === '/redirect-internal-host') {
+ res.writeHead(302, { Location: 'http://internal.example/' });
+ res.end();
+ return;
+ }
+ if (path === '/loop') {
+ res.writeHead(302, { Location: '/loop' });
+ res.end();
+ return;
+ }
+ if (path === '/redirect-no-location') {
+ res.writeHead(302);
+ res.end();
+ return;
+ }
+ if (path === '/oversized') {
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.end('x'.repeat(4096));
+ return;
+ }
+ if (path === '/gzip') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'gzip' });
+ res.end(gzipSync('<html>compressed hello</html>'));
+ return;
+ }
+ if (path === '/gzip-bomb') {
+ // Tiny on the wire, far past the cap once decompressed — the guard
+ // must count DECOMPRESSED bytes to catch it.
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'gzip' });
+ res.end(gzipSync('x'.repeat(64 * 1024)));
+ return;
+ }
+ if (path === '/unknown-encoding') {
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Encoding': 'zstd' });
+ res.end('opaque');
+ return;
+ }
+ if (path === '/nonhtml') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end('{"not":"html"}');
+ return;
+ }
+ if (path === '/slow') {
+ const timer = setTimeout(() => {
+ if (!res.writableEnded) {
+ res.writeHead(200, { 'Content-Type': 'text/html' });
+ res.end('too late');
+ }
+ }, 2000);
+ res.on('close', () => clearTimeout(timer));
+ return;
+ }
+ res.writeHead(404);
+ res.end();
+ });
+ ({ port } = await listenOnLoopback(server));
+ });
+
+ afterAll(() => {
+ server.close();
+ });
+
+ test('allows a public-resolving host and returns the pinned response', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/ok`, withRig);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.contentType).toBe('text/html');
+ expect(new TextDecoder().decode(result.body)).toBe('hello');
+ expect(result.finalUrl).toBe(`http://rig.example:${port}/ok`);
+ });
+
+ test('pins the connection while preserving Host and sending no credentials', async () => {
+ lastRequest = null;
+ const result = await guardedFetch(`http://rig.example:${port}/ok`, withRig);
+ expect(result.ok).toBe(true);
+ // The socket connected to the validated IP but the Host header carries the
+ // original name — proof the pin swapped the connect target, not the identity.
+ expect(lastRequest?.host).toBe(`rig.example:${port}`);
+ expect(lastRequest?.ua).toBe('OpenKnowledge-LinkPreview/1.x');
+ expect(lastRequest?.cookie).toBeUndefined();
+ expect(lastRequest?.authorization).toBeUndefined();
+ expect(lastRequest?.referer).toBeUndefined();
+ });
+
+ test('requests an identity encoding (transport does not auto-negotiate compression)', async () => {
+ lastRequest = null;
+ const result = await guardedFetch(`http://rig.example:${port}/ok`, withRig);
+ expect(result.ok).toBe(true);
+ expect(lastRequest?.acceptEncoding).toBe('identity');
+ });
+
+ test('drops URL userinfo instead of forwarding it as credentials', async () => {
+ lastRequest = null;
+ const result = await guardedFetch(`http://user:[email protected]:${port}/ok`, withRig);
+ expect(result.ok).toBe(true);
+ expect(lastRequest?.authorization).toBeUndefined();
+ });
+
+ test('decompresses a gzip response that ignored Accept-Encoding: identity', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/gzip`, withRig);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(new TextDecoder().decode(result.body)).toBe('<html>compressed hello</html>');
+ });
+
+ test('caps the DECOMPRESSED size, not the wire size (gzip-bomb guard)', async () => {
+ // The compressed payload is well under the cap; only decompressed
+ // accounting can reject it.
+ const result = await guardedFetch(`http://rig.example:${port}/gzip-bomb`, {
+ ...withRig,
+ maxBytes: 8 * 1024,
+ });
+ expect(result).toEqual({ ok: false, reason: 'oversized' });
+ });
+
+ test('rejects a content-encoding it cannot size-guard', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/unknown-encoding`, withRig);
+ expect(result).toEqual({ ok: false, reason: 'fetch-error' });
+ });
+
+ test('follows a same-host redirect within the hop limit', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/redirect-once`, withRig);
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(new TextDecoder().decode(result.body)).toBe('final page');
+ expect(result.finalUrl).toBe(`http://rig.example:${port}/final`);
+ });
+
+ test('rejects a redirect to an internal IP literal (re-validated per hop)', async () => {
+ const result = await guardedFetch(
+ `http://rig.example:${port}/redirect-internal-literal`,
+ withRig,
+ );
+ expect(result).toEqual({ ok: false, reason: 'private-ip' });
+ });
+
+ test('rejects a redirect to a host that resolves internally', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/redirect-internal-host`, withRig);
+ expect(result).toEqual({ ok: false, reason: 'private-ip' });
+ });
+
+ test('rejects a 3xx without a Location header as fetch-error', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/redirect-no-location`, withRig);
+ expect(result).toEqual({ ok: false, reason: 'fetch-error' });
+ });
+
+ test('rejects a redirect chain that exceeds the hop limit', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/loop`, {
+ ...withRig,
+ maxRedirects: 1,
+ });
+ expect(result).toEqual({ ok: false, reason: 'redirect-limit' });
+ });
+
+ test('aborts a response body that exceeds the size cap', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/oversized`, {
+ ...withRig,
+ maxBytes: 1024,
+ });
+ expect(result).toEqual({ ok: false, reason: 'oversized' });
+ });
+
+ test('rejects a non-HTML content type', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/nonhtml`, withRig);
+ expect(result).toEqual({ ok: false, reason: 'non-html' });
+ });
+
+ test('allows a non-HTML content type when the predicate opts in (favicon reuse)', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/nonhtml`, {
+ ...withRig,
+ allowContentType: (mimeType) => mimeType === 'application/json',
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.contentType).toBe('application/json');
+ });
+
+ test('times out a slow response', async () => {
+ const result = await guardedFetch(`http://rig.example:${port}/slow`, {
+ ...withRig,
+ timeoutMs: 200,
+ });
+ expect(result).toEqual({ ok: false, reason: 'timeout' });
+ });
+});
diff --git a/packages/server/src/link-preview/guarded-fetch.ts b/packages/server/src/link-preview/guarded-fetch.ts
new file mode 100644
index 000000000..313064e9d
--- /dev/null
+++ b/packages/server/src/link-preview/guarded-fetch.ts
@@ -0,0 +1,460 @@
+/**
+ * The single outbound-fetch chokepoint for link previews. Every remote request
+ * — the page fetch, the favicon fetch, and every redirect hop — passes through
+ * here so the SSRF guard cannot be bypassed.
+ *
+ * The transport is node:http/node:https `request()`, NOT `fetch`, because the
+ * pin must behave identically on both runtimes this server runs under (Bun in
+ * dev/CI, Node in the packaged desktop and the npm CLI). Bun's `fetch` accepts
+ * a `tls.serverName` extension for SNI-preserving IP pins, but Node's `fetch`
+ * silently ignores it, which turns the pinned HTTPS handshake into
+ * SNI=IP-literal and fails certificate validation on every external target.
+ * `request()` honors the same pinning options on both runtimes (verified
+ * empirically on Node 22 and Bun 1.3).
+ *
+ * The guard is TOCTOU-safe by construction. A hostname is resolved once via
+ * the injectable resolver and EVERY resolved address is validated as public
+ * unicast (ip-classifier). The request then keeps the original hostname URL —
+ * so SNI, certificate validation (a name mismatch rejects the fetch), and the
+ * automatic `Host` header all run against the real name — while the socket is
+ * pinned to the validated address through the request's `lookup` option, which
+ * answers with ONLY that address. The runtime performs no second DNS lookup,
+ * so there is no window in which a name could re-resolve to an internal
+ * address between the check and the connect. (Both runtimes may call `lookup`
+ * in the all-addresses form; the pin answers whichever form was requested.)
+ * IP-literal hosts skip resolution and are classified directly (encoded forms
+ * canonicalized first, and the request URL is rebuilt on the canonical literal
+ * so the runtime dials it as an IP rather than resolving it as a name).
+ *
+ * Redirects are never auto-followed — `request()` returns the 3xx — and we
+ * re-run the full scheme+resolve+validate admission on each hop's target,
+ * bounded to a small hop count. Response reads are bounded on both time
+ * (AbortSignal) and DECOMPRESSED size, and admit only allowlisted content
+ * types. Decompression contract: the request advertises
+ * `Accept-Encoding: identity`; if a server compresses anyway, the body is
+ * streamed through node:zlib (gzip/deflate/br) and the byte cap is applied to
+ * the DECOMPRESSED output — the decompression-bomb guard — while unknown
+ * encodings are rejected outright. No credentials ever leave: no cookie,
+ * authorization, or referer header, and userinfo in the URL is dropped when
+ * the request URL is rebuilt from parts (it never reaches the transport, which
+ * would otherwise turn it into a basic-auth header).
+ *
+ * Failures return a bounded reason code and never a partial body. Reason codes
+ * are the ONLY thing logged — never the hostname, resolved IP, or fetched
+ * content — so local logs can't become an internal-network-topology oracle.
+ */
+
+import { lookup } from 'node:dns/promises';
+import { request as httpRequest, type IncomingMessage } from 'node:http';
+import { request as httpsRequest, type RequestOptions } from 'node:https';
+import type { LookupFunction } from 'node:net';
+import type { Transform } from 'node:stream';
+import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib';
+import { getLogger } from '../logger.ts';
+import { classifyHost, isPublicUnicastIp } from './ip-classifier.ts';
+
+const logger = getLogger('link-preview.guarded-fetch');
+
+const USER_AGENT = 'OpenKnowledge-LinkPreview/1.x';
+
+/** Decompressed-body ceiling; reads abort once a response exceeds it. */
+export const DEFAULT_MAX_BYTES = 512 * 1024;
+/** Total wall-clock budget across all redirect hops and the body read. */
+export const DEFAULT_TIMEOUT_MS = 5000;
+/** Redirect hops followed before a chain is rejected. */
+export const DEFAULT_MAX_REDIRECTS = 3;
+
+/**
+ * Bounded taxonomy of rejection causes. Deliberately coarse so it is safe to
+ * log: no member encodes the target host, resolved address, or body.
+ */
+export type GuardRejectReason =
+ | 'bad-scheme'
+ | 'private-ip'
+ | 'dns-failure'
+ | 'redirect-limit'
+ | 'oversized'
+ | 'non-html'
+ | 'timeout'
+ | 'fetch-error';
+
+/** @lintignore Union member of the exported GuardedFetchResult; no direct importer. */
+export interface GuardedFetchSuccess {
+ ok: true;
+ /** Decompressed response bytes, guaranteed within the byte cap. */
+ body: Uint8Array;
+ /** Lowercased mime type with parameters stripped (e.g. `text/html`). */
+ contentType: string;
+ /** The final hostname-bearing URL after redirects (domain derivation seam). */
+ finalUrl: string;
+}
+
+/** @lintignore Union member of the exported GuardedFetchResult; no direct importer. */
+export interface GuardedFetchFailure {
+ ok: false;
+ reason: GuardRejectReason;
+}
+
+export type GuardedFetchResult = GuardedFetchSuccess | GuardedFetchFailure;
+
+/**
+ * One resolved DNS record; mirrors the fields of a getaddrinfo lookup.
+ * @lintignore Referenced by the exported HostResolver type; no direct importer.
+ */
+export interface ResolvedAddress {
+ address: string;
+ family: 4 | 6;
+}
+
+/**
+ * DNS seam. Production wires the platform resolver (getaddrinfo, all records);
+ * tests substitute a resolver that forces a hostname to a chosen address so the
+ * validator can be exercised without real DNS.
+ */
+export type HostResolver = (hostname: string) => Promise<ResolvedAddress[]>;
+
+export interface GuardedFetchOptions {
+ /**
+ * Response content-type admission predicate (lowercased, no parameters).
+ * Defaults to HTML only; the favicon path passes an image predicate.
+ */
+ allowContentType?: (mimeType: string) => boolean;
+ /** Overrides {@link DEFAULT_MAX_BYTES}. */
+ maxBytes?: number;
+ /** Overrides {@link DEFAULT_TIMEOUT_MS}. */
+ timeoutMs?: number;
+ /** Overrides {@link DEFAULT_MAX_REDIRECTS}. */
+ maxRedirects?: number;
+ /** DNS seam; defaults to the platform getaddrinfo resolver. */
+ resolve?: HostResolver;
+ /**
+ * Resolved-address admission predicate; defaults to the public-unicast
+ * classifier. Overridden ONLY by integration tests, to admit the loopback
+ * address of a local rig so post-admission behavior (caps, redirects,
+ * content-type) can be exercised against a real socket. Production never
+ * passes it, and every redirect target still runs the real classifier, so
+ * the SSRF property is proven by the tests that omit this override.
+ */
+ isAddressAllowed?: (ip: string) => boolean;
+}
+
+interface AdmittedTarget {
+ /**
+ * Sanitized URL the request is issued against: rebuilt from parts so
+ * userinfo and fragment never survive. Keeps the original hostname (SNI,
+ * cert validation, and the Host header derive from it) except for IP-literal
+ * hosts, where it carries the canonical literal the runtime dials directly.
+ */
+ requestUrl: string;
+ /**
+ * The single validated address the socket must dial, enforced via the
+ * request's `lookup` option; absent for IP-literal hosts (the runtime
+ * connects to the literal without any DNS).
+ */
+ pinnedAddress: ResolvedAddress | undefined;
+ /** Original hostname for explicit TLS SNI; absent for IP literals. */
+ serverName: string | undefined;
+ /** Hostname-bearing URL used as the base for resolving redirect Locations. */
+ logicalUrl: string;
+}
+
+type AdmitResult = { ok: true; target: AdmittedTarget } | { ok: false; reason: GuardRejectReason };
+
+const defaultResolve: HostResolver = async (hostname) => {
+ const records = await lookup(hostname, { all: true, family: 0 });
+ return records.map((record) => ({
+ address: record.address,
+ family: record.family === 6 ? 6 : 4,
+ }));
+};
+
+/**
+ * Rebuild the request URL against an explicit host, preserving scheme, port,
+ * path, and query while dropping userinfo and fragment. Building from parts
+ * (rather than string-editing the original) is what guarantees no embedded
+ * credentials survive into the outbound request.
+ */
+function buildSanitizedUrl(url: URL, host: string): string {
+ const port = url.port ? `:${url.port}` : '';
+ return `${url.protocol}//${host}${port}${url.pathname}${url.search}`;
+}
+
+async function admit(
+ rawUrl: string,
+ resolve: HostResolver,
+ isAddressAllowed: (ip: string) => boolean,
+): Promise<AdmitResult> {
+ let url: URL;
+ try {
+ url = new URL(rawUrl);
+ } catch {
+ return { ok: false, reason: 'fetch-error' };
+ }
+
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ return { ok: false, reason: 'bad-scheme' };
+ }
+
+ const classification = classifyHost(url.hostname);
+ if (classification.kind === 'ip-literal') {
+ if (!classification.allowed) return { ok: false, reason: 'private-ip' };
+ const connectHost =
+ classification.family === 6 ? `[${classification.canonical}]` : classification.canonical;
+ return {
+ ok: true,
+ target: {
+ requestUrl: buildSanitizedUrl(url, connectHost),
+ pinnedAddress: undefined,
+ serverName: undefined,
+ logicalUrl: url.toString(),
+ },
+ };
+ }
+
+ let records: ResolvedAddress[];
+ try {
+ records = await resolve(url.hostname);
+ } catch {
+ return { ok: false, reason: 'dns-failure' };
+ }
+ if (records.length === 0) return { ok: false, reason: 'dns-failure' };
+ for (const record of records) {
+ if (!isAddressAllowed(record.address)) return { ok: false, reason: 'private-ip' };
+ }
+
+ const chosen = records[0];
+ return {
+ ok: true,
+ target: {
+ requestUrl: buildSanitizedUrl(url, url.hostname),
+ pinnedAddress: {
+ address: chosen.address,
+ family: chosen.family === 6 || chosen.address.includes(':') ? 6 : 4,
+ },
+ serverName: url.hostname,
+ logicalUrl: url.toString(),
+ },
+ };
+}
+
+/**
+ * Connection pin: answer every runtime lookup with ONLY the validated address.
+ * Both runtimes may ask in the all-addresses form (happy-eyeballs), and both
+ * reject a scalar answer to an `all` question, so the shape must follow the
+ * question.
+ */
+function pinnedLookup(pinned: ResolvedAddress): LookupFunction {
+ return (_hostname, options, callback) => {
+ if (options.all) {
+ callback(null, [{ address: pinned.address, family: pinned.family }]);
+ } else {
+ callback(null, pinned.address, pinned.family);
+ }
+ };
+}
+
+function isRedirectStatus(status: number): boolean {
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
+}
+
+function parseMimeType(header: string | undefined): string {
+ if (!header) return '';
+ return (header.split(';', 1)[0] ?? '').trim().toLowerCase();
+}
+
+/** A request/read that failed because the shared deadline fired reads as a timeout. */
+function classifyFetchError(err: unknown, signal: AbortSignal): GuardRejectReason {
+ if (signal.aborted) return 'timeout';
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
+ return 'timeout';
+ }
+ return 'fetch-error';
+}
+
+/** Best-effort release of an unread response (redirect / rejected body). */
+function discardMessage(message: IncomingMessage): void {
+ try {
+ message.destroy();
+ } catch {
+ // The stream may already be closed by the remote/runtime; a cleanup
+ // destroy that throws has no bearing on the guard decision.
+ }
+}
+
+type IssueResult =
+ | { ok: true; response: IncomingMessage }
+ | { ok: false; reason: GuardRejectReason };
+
+function issueRequest(target: AdmittedTarget, signal: AbortSignal): Promise<IssueResult> {
+ return new Promise((settle) => {
+ let settled = false;
+ const resolveOnce = (result: IssueResult) => {
+ if (settled) return;
+ settled = true;
+ settle(result);
+ };
+
+ const isHttps = target.requestUrl.startsWith('https:');
+ const options: RequestOptions = {
+ method: 'GET',
+ // One socket per request, never pooled: a keep-alive agent could reuse a
+ // connection across hops whose pinned addresses differ.
+ agent: false,
+ signal,
+ headers: {
+ 'User-Agent': USER_AGENT,
+ Accept: 'text/html',
+ 'Accept-Encoding': 'identity',
+ },
+ };
+ if (target.pinnedAddress) options.lookup = pinnedLookup(target.pinnedAddress);
+ if (isHttps && target.serverName) options.servername = target.serverName;
+
+ try {
+ const req = (isHttps ? httpsRequest : httpRequest)(target.requestUrl, options, (response) => {
+ // Swallow-guard: a mid-body socket error must reach the body reader's
+ // listener, not crash the process as an unhandled stream error in the
+ // window before that listener attaches.
+ response.on('error', () => {});
+ resolveOnce({ ok: true, response });
+ });
+ req.on('error', (err) => resolveOnce({ ok: false, reason: classifyFetchError(err, signal) }));
+ req.end();
+ } catch (err) {
+ resolveOnce({ ok: false, reason: classifyFetchError(err, signal) });
+ }
+ });
+}
+
+/**
+ * Streaming decoder for a response that compressed despite
+ * `Accept-Encoding: identity`. Returns `'identity'` for an uncompressed body,
+ * a zlib transform for the encodings we can safely decode, or `null` for
+ * anything else (rejected — an undecodable body can't be admitted and an
+ * unknown coding can't be size-guarded).
+ */
+function makeDecompressor(encoding: string): Transform | 'identity' | null {
+ if (encoding === '' || encoding === 'identity') return 'identity';
+ if (encoding === 'gzip' || encoding === 'x-gzip') return createGunzip();
+ if (encoding === 'deflate') return createInflate();
+ if (encoding === 'br') return createBrotliDecompress();
+ return null;
+}
+
+function readCappedBody(
+ message: IncomingMessage,
+ maxBytes: number,
+ signal: AbortSignal,
+): Promise<{ ok: true; body: Uint8Array } | { ok: false; reason: GuardRejectReason }> {
+ const encoding = (message.headers['content-encoding'] ?? '').trim().toLowerCase();
+ const decompressor = makeDecompressor(encoding);
+ if (decompressor === null) {
+ discardMessage(message);
+ return Promise.resolve({ ok: false, reason: 'fetch-error' });
+ }
+ // The cap below counts bytes AFTER this pipe, so it bounds the decompressed
+ // size — a tiny compressed bomb still aborts at the cap.
+ const source = decompressor === 'identity' ? message : message.pipe(decompressor);
+
+ return new Promise((settle) => {
+ const chunks: Buffer[] = [];
+ let received = 0;
+ let settled = false;
+
+ const teardown = () => {
+ signal.removeEventListener('abort', onAbort);
+ discardMessage(message);
+ if (source !== message) (source as Transform).destroy();
+ };
+ const resolveOnce = (
+ result: { ok: true; body: Uint8Array } | { ok: false; reason: GuardRejectReason },
+ ) => {
+ if (settled) return;
+ settled = true;
+ teardown();
+ settle(result);
+ };
+ const onAbort = () => resolveOnce({ ok: false, reason: 'timeout' });
+ signal.addEventListener('abort', onAbort, { once: true });
+
+ // `pipe` does not forward source errors; surface them on the terminal read.
+ if (source !== message) {
+ message.on('error', (err) =>
+ resolveOnce({ ok: false, reason: classifyFetchError(err, signal) }),
+ );
+ }
+ source.on('data', (chunk: Buffer) => {
+ received += chunk.byteLength;
+ if (received > maxBytes) {
+ resolveOnce({ ok: false, reason: 'oversized' });
+ return;
+ }
+ chunks.push(chunk);
+ });
+ source.on('end', () => resolveOnce({ ok: true, body: new Uint8Array(Buffer.concat(chunks)) }));
+ source.on('error', (err) =>
+ resolveOnce({ ok: false, reason: classifyFetchError(err, signal) }),
+ );
+ });
+}
+
+function rejectWith(reason: GuardRejectReason): GuardedFetchFailure {
+ logger.debug({ reason }, 'link-preview guarded fetch rejected');
+ return { ok: false, reason };
+}
+
+/**
+ * Fetch a URL under the SSRF guard. Returns the bounded response body plus the
+ * derived content-type and final URL on success, or a bounded reason code on
+ * any violation — never a partial body.
+ */
+export async function guardedFetch(
+ rawUrl: string,
+ options: GuardedFetchOptions = {},
+): Promise<GuardedFetchResult> {
+ const allowContentType = options.allowContentType ?? ((mimeType) => mimeType === 'text/html');
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
+ const resolve = options.resolve ?? defaultResolve;
+ const isAddressAllowed = options.isAddressAllowed ?? isPublicUnicastIp;
+
+ const signal = AbortSignal.timeout(timeoutMs);
+ let logicalUrl = rawUrl;
+ let redirects = 0;
+
+ while (true) {
+ const admitted = await admit(logicalUrl, resolve, isAddressAllowed);
+ if (!admitted.ok) return rejectWith(admitted.reason);
+ const { target } = admitted;
+
+ const issued = await issueRequest(target, signal);
+ if (!issued.ok) return rejectWith(issued.reason);
+ const response = issued.response;
+ const status = response.statusCode ?? 0;
+
+ if (isRedirectStatus(status)) {
+ const location = response.headers.location;
+ discardMessage(response);
+ if (location === undefined) return rejectWith('fetch-error');
+ if (redirects >= maxRedirects) return rejectWith('redirect-limit');
+ redirects += 1;
+ try {
+ logicalUrl = new URL(location, target.logicalUrl).toString();
+ } catch {
+ return rejectWith('fetch-error');
+ }
+ continue;
+ }
+
+ const contentType = parseMimeType(response.headers['content-type']);
+ if (!allowContentType(contentType)) {
+ discardMessage(response);
+ return rejectWith('non-html');
+ }
+
+ const bodyResult = await readCappedBody(response, maxBytes, signal);
+ if (!bodyResult.ok) return rejectWith(bodyResult.reason);
+ return { ok: true, body: bodyResult.body, contentType, finalUrl: target.logicalUrl };
+ }
+}
diff --git a/packages/server/src/link-preview/html-metadata.test.ts b/packages/server/src/link-preview/html-metadata.test.ts
new file mode 100644
index 000000000..6a9b135d7
Binary files /dev/null and b/packages/server/src/link-preview/html-metadata.test.ts differ
diff --git a/packages/server/src/link-preview/html-metadata.ts b/packages/server/src/link-preview/html-metadata.ts
new file mode 100644
index 000000000..b0778e353
--- /dev/null
+++ b/packages/server/src/link-preview/html-metadata.ts
@@ -0,0 +1,443 @@
+/**
+ * Parse the fetched page's `<head>` into normalized preview fields, and derive
+ * the shown domain from the request URL. The HTML arrives as untrusted bytes,
+ * so this layer is deliberately narrow: only a handful of known tags are read,
+ * every text field runs through {@link sanitizeText}, and the domain never comes
+ * from the fetched markup — only from the URL the user actually hovered.
+ *
+ * The head is read by a hand-rolled bounded scanner rather than a DOM, a parser
+ * dependency, or a runtime built-in. The production server runs under Node (the
+ * desktop app spawns it with ELECTRON_RUN_AS_NODE=1; the npm CLI is a node
+ * script) while tests run under Bun, so an engine-specific parser (Bun's
+ * HTMLRewriter) is silently absent in production; one portable scanner keeps a
+ * single parse path on both runtimes. The scan is single-pass and
+ * index-monotonic (indexOf/charCode, no regex over the markup), so hostile
+ * input stays linear-time; input size is capped by the fetch layer.
+ */
+
+/** Display caps; fetched text is truncated to keep the card bounded. */
+const MAX_TITLE = 200;
+const MAX_DESCRIPTION = 500;
+const MAX_SITE_NAME = 100;
+
+/**
+ * The known metadata fields read from the head. Every field is optional: a page
+ * with no usable tags returns `{}` and the caller falls back to domain-only.
+ * `faviconHref` is the raw icon href (relative or absolute) for the favicon
+ * fetcher to resolve — it is a URL, not display text, so it is not sanitized
+ * here (the `URL` constructor validates it at resolution time).
+ */
+export interface RawHtmlMetadata {
+ title?: string;
+ description?: string;
+ siteName?: string;
+ faviconHref?: string;
+}
+
+const NAMED_ENTITIES: Record<string, string> = {
+ amp: '&',
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ apos: "'",
+ nbsp: ' ',
+ copy: '©',
+ reg: '®',
+ trade: '™',
+ mdash: '—',
+ ndash: '–',
+ hellip: '…',
+ lsquo: '‘',
+ rsquo: '’',
+ ldquo: '“',
+ rdquo: '”',
+};
+
+function decodeCodePoint(code: number): string | null {
+ // Reject out-of-range and lone surrogates so decoding can't emit an
+ // ill-formed scalar; `String.fromCodePoint` cannot throw after this guard.
+ if (!Number.isInteger(code) || code < 0 || code > 0x10ffff) return null;
+ if (code >= 0xd800 && code <= 0xdfff) return null;
+ return String.fromCodePoint(code);
+}
+
+/**
+ * Decode the core named entities plus decimal/hex numeric character references.
+ * The head scanner hands text and attribute values back raw (entities
+ * undecoded), so this runs BEFORE control-character stripping — otherwise a
+ * numeric-encoded bidi override such as `&#x202e;` would survive stripping and
+ * reach the card. The long tail of named entities is intentionally left literal
+ * (rare in titles); they render harmlessly as text.
+ */
+function decodeHtmlEntities(input: string): string {
+ return input.replace(
+ /&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,
+ (match, body: string) => {
+ if (body.startsWith('#')) {
+ const isHex = body[1] === 'x' || body[1] === 'X';
+ const code = Number.parseInt(body.slice(isHex ? 2 : 1), isHex ? 16 : 10);
+ return decodeCodePoint(code) ?? match;
+ }
+ return NAMED_ENTITIES[body.toLowerCase()] ?? match;
+ },
+ );
+}
+
+// Bidi overrides/isolates and zero-width/format controls that can visually
+// reorder or hide text to misrepresent the destination.
+function isFormatControl(code: number): boolean {
+ return (
+ code === 0x061c ||
+ (code >= 0x200b && code <= 0x200f) ||
+ code === 0x2028 ||
+ code === 0x2029 ||
+ (code >= 0x202a && code <= 0x202e) ||
+ (code >= 0x2060 && code <= 0x2064) ||
+ (code >= 0x2066 && code <= 0x2069) ||
+ code === 0xfeff
+ );
+}
+
+// C0/C1 controls and DEL.
+function isControl(code: number): boolean {
+ return code <= 0x1f || (code >= 0x7f && code <= 0x9f);
+}
+
+/**
+ * Drop format/bidi controls and turn C0/C1 controls into spaces (so text on
+ * either side stays separated). Matched by code point rather than a regex both
+ * to keep control characters out of the source and to make the intent explicit.
+ */
+function stripUnsafeChars(input: string): string {
+ let out = '';
+ for (const ch of input) {
+ const code = ch.codePointAt(0) ?? 0;
+ if (isFormatControl(code)) continue;
+ out += isControl(code) ? ' ' : ch;
+ }
+ return out;
+}
+
+function truncate(text: string, maxLen: number): string {
+ // Count by code point so a surrogate pair (emoji) is never split at the cap.
+ const chars = Array.from(text);
+ if (chars.length <= maxLen) return text;
+ return `${chars
+ .slice(0, maxLen - 1)
+ .join('')
+ .trimEnd()}…`;
+}
+
+/**
+ * Turn a raw fetched string into safe, bounded display text: decode entities,
+ * remove format/control characters, collapse whitespace, then cap length. An
+ * empty result signals an absent field (the caller omits it).
+ */
+function sanitizeText(raw: string, maxLen: number): string {
+ const decoded = decodeHtmlEntities(raw);
+ const stripped = stripUnsafeChars(decoded);
+ const collapsed = stripped.replace(/\s+/g, ' ').trim();
+ return truncate(collapsed, maxLen);
+}
+
+function relTokens(rel: string): string[] {
+ return rel.trim().toLowerCase().split(/\s+/);
+}
+
+// ---------------------------------------------------------------------------
+// Bounded head scanner
+//
+// The scanner walks the markup once, tag by tag, and stops at `</head>` or
+// `<body>` so nothing below the head can spoof the card. All structural
+// matching (tag names, close-tag searches) runs against an ASCII-lowercased
+// copy of the input so `<TITLE>` and `</SCRIPT>` match case-insensitively;
+// extracted text and attribute values slice from the original string. Only
+// A-Z is folded (never full Unicode lowercasing, which can change string
+// length and would misalign the two views).
+// ---------------------------------------------------------------------------
+
+function asciiLowerCase(input: string): string {
+ return input.replace(/[A-Z]+/g, (run) => run.toLowerCase());
+}
+
+function isWhitespaceCode(code: number): boolean {
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d;
+}
+
+/**
+ * Elements whose content is raw text (or inert markup) to a browser: nothing
+ * inside them may contribute tags, so the scanner skips their content wholesale
+ * until the matching close tag. This is what keeps
+ * `<script>document.title="<title>evil</title>"</script>` from contributing a
+ * title. `noscript` is deliberately absent: its head content is real metadata
+ * markup (`meta`/`link`/`style` are valid there) for non-scripting agents.
+ */
+const RAW_TEXT_TAGS = new Set([
+ 'script',
+ 'style',
+ 'template',
+ 'textarea',
+ 'iframe',
+ 'xmp',
+ 'noembed',
+ 'noframes',
+ 'plaintext',
+]);
+
+/** Read a tag name (letters/digits/hyphen) from the lowercased view. */
+function readTagName(lower: string, start: number): { name: string; end: number } {
+ let i = start;
+ while (i < lower.length) {
+ const c = lower.charCodeAt(i);
+ const isNameChar = (c >= 0x61 && c <= 0x7a) || (c >= 0x30 && c <= 0x39) || c === 0x2d;
+ if (!isNameChar) break;
+ i++;
+ }
+ return { name: lower.slice(start, i), end: i };
+}
+
+/**
+ * Scan a tag's attributes from just after the tag name to just past its `>`,
+ * returning that end index. Handles double-quoted, single-quoted, and unquoted
+ * values, `=` spacing variants, and self-closing `/`; a quoted value may
+ * contain `>` without ending the tag. When `attrs` is provided, each
+ * attribute's first occurrence is recorded (duplicates ignored, matching how
+ * browsers resolve repeated attributes); names come from the lowercased view,
+ * values from the original string. An unterminated tag consumes to the end of
+ * input.
+ */
+function scanAttributes(
+ html: string,
+ lower: string,
+ start: number,
+ attrs: Map<string, string> | null,
+): number {
+ const len = lower.length;
+ let i = start;
+ while (i < len) {
+ let c = lower.charCodeAt(i);
+ if (isWhitespaceCode(c) || c === 0x2f /* / */) {
+ i++;
+ continue;
+ }
+ if (c === 0x3e /* > */) return i + 1;
+ const nameStart = i;
+ while (i < len) {
+ c = lower.charCodeAt(i);
+ if (isWhitespaceCode(c) || c === 0x3d /* = */ || c === 0x3e || c === 0x2f) break;
+ i++;
+ }
+ const name = lower.slice(nameStart, i);
+ while (i < len && isWhitespaceCode(lower.charCodeAt(i))) i++;
+ let value = '';
+ if (i < len && lower.charCodeAt(i) === 0x3d) {
+ i++;
+ while (i < len && isWhitespaceCode(lower.charCodeAt(i))) i++;
+ if (i < len) {
+ const quote = lower.charCodeAt(i);
+ if (quote === 0x22 /* " */ || quote === 0x27 /* ' */) {
+ i++;
+ const close = lower.indexOf(quote === 0x22 ? '"' : "'", i);
+ value = html.slice(i, close === -1 ? len : close);
+ i = close === -1 ? len : close + 1;
+ } else {
+ const valueStart = i;
+ while (i < len) {
+ c = lower.charCodeAt(i);
+ if (isWhitespaceCode(c) || c === 0x3e) break;
+ i++;
+ }
+ value = html.slice(valueStart, i);
+ }
+ }
+ }
+ if (attrs && name && !attrs.has(name)) attrs.set(name, value);
+ }
+ return len;
+}
+
+/**
+ * Find a raw-text element's close tag: the first case-insensitive `</name`
+ * followed by `>`, `/`, whitespace, or end of input (so `</scripty` does not
+ * close a script). Returns the content end (start of the close tag) and the
+ * index just past the close tag's `>`, or `null` when the element never
+ * closes, in which case the rest of the input is inert raw text.
+ */
+function findCloseTag(
+ lower: string,
+ tagName: string,
+ from: number,
+): { textEnd: number; end: number } | null {
+ const needle = `</${tagName}`;
+ let i = from;
+ while (i < lower.length) {
+ const at = lower.indexOf(needle, i);
+ if (at === -1) return null;
+ const afterIdx = at + needle.length;
+ const after = afterIdx < lower.length ? lower.charCodeAt(afterIdx) : -1;
+ if (after === 0x3e || after === 0x2f || after === -1 || isWhitespaceCode(after)) {
+ const gt = lower.indexOf('>', afterIdx);
+ return { textEnd: at, end: gt === -1 ? lower.length : gt + 1 };
+ }
+ i = at + 1;
+ }
+ return null;
+}
+
+/**
+ * Extract the preview fields from a page's head. Title prefers `og:title` over
+ * `<title>`; description prefers `og:description` over the `description` meta;
+ * site name is `og:site_name`. Only content inside the head (before `</head>`
+ * or `<body>`) counts, so a stray `<title>`/`<meta>` in the body cannot spoof
+ * the card; a document with no explicit `<head>` (title before `<body>`) still
+ * yields its head fields. Script/style content and HTML comments are skipped
+ * wholesale, so markup-shaped strings inside them cannot contribute fields.
+ */
+export function extractHtmlMetadata(html: string): RawHtmlMetadata {
+ let rawTitle = '';
+ const metaContent = new Map<string, string>();
+ let faviconHref: string | undefined;
+
+ try {
+ const lower = asciiLowerCase(html);
+ const len = lower.length;
+ let i = 0;
+ while (i < len) {
+ const lt = lower.indexOf('<', i);
+ if (lt === -1) break;
+ const next = lt + 1 < len ? lower.charCodeAt(lt + 1) : -1;
+
+ if (next === 0x21 /* ! */) {
+ if (lower.startsWith('<!--', lt)) {
+ // Comment: nothing inside may contribute fields. Searching from
+ // lt + 2 lets the abrupt closings `<!-->` and `<!--->` terminate
+ // instead of swallowing the markup after them; an unterminated
+ // comment swallows the rest of the input.
+ const close = lower.indexOf('-->', lt + 2);
+ if (close === -1) break;
+ i = close + 3;
+ } else {
+ // <!doctype ...> and other markup declarations.
+ const gt = lower.indexOf('>', lt + 2);
+ if (gt === -1) break;
+ i = gt + 1;
+ }
+ continue;
+ }
+
+ if (next === 0x3f /* ? */) {
+ const gt = lower.indexOf('>', lt + 2);
+ if (gt === -1) break;
+ i = gt + 1;
+ continue;
+ }
+
+ if (next === 0x2f /* / */) {
+ const { name, end } = readTagName(lower, lt + 2);
+ if (name === 'head') break;
+ const gt = lower.indexOf('>', end);
+ if (gt === -1) break;
+ i = gt + 1;
+ continue;
+ }
+
+ if (!(next >= 0x61 && next <= 0x7a)) {
+ // A '<' that opens no tag ('<<', '< ', trailing '<') is literal text.
+ i = lt + 1;
+ continue;
+ }
+
+ const { name, end: nameEnd } = readTagName(lower, lt + 1);
+
+ if (name === 'body') break;
+
+ if (name === 'title') {
+ const contentStart = scanAttributes(html, lower, nameEnd, null);
+ const close = findCloseTag(lower, 'title', contentStart);
+ if (close === null) {
+ // Unterminated title: the rest of the input is its text (sanitize
+ // caps the displayed length).
+ rawTitle += html.slice(contentStart);
+ break;
+ }
+ rawTitle += html.slice(contentStart, close.textEnd);
+ i = close.end;
+ continue;
+ }
+
+ if (RAW_TEXT_TAGS.has(name)) {
+ const contentStart = scanAttributes(html, lower, nameEnd, null);
+ const close = findCloseTag(lower, name, contentStart);
+ if (close === null) break;
+ i = close.end;
+ continue;
+ }
+
+ if (name === 'meta') {
+ const attrs = new Map<string, string>();
+ i = scanAttributes(html, lower, nameEnd, attrs);
+ const content = attrs.get('content');
+ if (content) {
+ const property = attrs.get('property');
+ const metaName = attrs.get('name');
+ if (property) metaContent.set(property.toLowerCase(), content);
+ else if (metaName) metaContent.set(metaName.toLowerCase(), content);
+ }
+ continue;
+ }
+
+ if (name === 'link') {
+ const attrs = new Map<string, string>();
+ i = scanAttributes(html, lower, nameEnd, attrs);
+ // First icon link wins; ignore the rest so a head stuffed with
+ // <link> tags cannot grow this unbounded.
+ if (faviconHref === undefined) {
+ const href = attrs.get('href');
+ const rel = attrs.get('rel');
+ if (href && rel && relTokens(rel).includes('icon')) faviconHref = href;
+ }
+ continue;
+ }
+
+ // Any other open tag (html, head, base, ...): step past it.
+ i = scanAttributes(html, lower, nameEnd, null);
+ }
+ } catch {
+ // The bytes are untrusted; if the scan fails on a hostile document, return
+ // whatever was captured before the throw rather than propagating into the
+ // request handler.
+ }
+
+ const title = sanitizeText(metaContent.get('og:title') ?? rawTitle, MAX_TITLE);
+ const description = sanitizeText(
+ metaContent.get('og:description') ?? metaContent.get('description') ?? '',
+ MAX_DESCRIPTION,
+ );
+ const siteName = sanitizeText(metaContent.get('og:site_name') ?? '', MAX_SITE_NAME);
+
+ const result: RawHtmlMetadata = {};
+ if (title) result.title = title;
+ if (description) result.description = description;
+ if (siteName) result.siteName = siteName;
+ if (faviconHref) result.faviconHref = faviconHref;
+ return result;
+}
+
+/**
+ * The domain shown on the card, derived from the request URL only. `URL`
+ * normalizes IDN hosts to punycode, so a look-alike Unicode host renders as its
+ * ASCII `xn--` form. A leading `www.` is dropped for cleanliness, but only when
+ * a registrable label remains (so `www.com` stays `www.com`).
+ */
+export function deriveDomain(requestUrl: string): string {
+ let host: string;
+ try {
+ host = new URL(requestUrl).hostname;
+ } catch {
+ // Reached only if a caller passes an unparseable string; a fetch already
+ // validated production URLs. Fall back so the domain field stays non-empty.
+ return requestUrl;
+ }
+ if (host.startsWith('www.') && host.slice(4).includes('.')) host = host.slice(4);
+ return host;
+}
diff --git a/packages/server/src/link-preview/ip-classifier.test.ts b/packages/server/src/link-preview/ip-classifier.test.ts
new file mode 100644
index 000000000..b83a6b7bd
--- /dev/null
+++ b/packages/server/src/link-preview/ip-classifier.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, test } from 'bun:test';
+import { classifyHost, isPublicUnicastIp } from './ip-classifier.ts';
+
+describe('isPublicUnicastIp', () => {
+ const PUBLIC_UNICAST = [
+ '93.184.216.34',
+ '8.8.8.8',
+ '1.1.1.1',
+ // 172.16/12 is private; 172.15/16 sits just below it and is public.
+ '172.15.0.1',
+ '2001:4860:4860::8888',
+ ];
+ test.each(PUBLIC_UNICAST)('allows public unicast %s', (ip) => {
+ expect(isPublicUnicastIp(ip)).toBe(true);
+ });
+
+ const BLOCKED = [
+ // loopback
+ '127.0.0.1',
+ '::1',
+ // RFC1918 private
+ '10.0.0.1',
+ '172.16.0.1',
+ '172.31.255.255',
+ '192.168.1.1',
+ // link-local, including the cloud metadata endpoint
+ '169.254.169.254',
+ '169.254.0.1',
+ 'fe80::1',
+ // unique-local (fc00::/7)
+ 'fc00::1',
+ 'fd12:3456::1',
+ // multicast
+ '224.0.0.1',
+ 'ff02::1',
+ // unspecified / "all zeros"
+ '0.0.0.0',
+ '::',
+ // carrier-grade NAT, reserved test/benchmark blocks, 6to4
+ '100.64.0.1',
+ '192.0.2.1',
+ '198.18.0.1',
+ '2002::1',
+ // IPv4-mapped IPv6 — blocked wholesale, even wrapping a public v4 address
+ '::ffff:127.0.0.1',
+ '::ffff:93.184.216.34',
+ ];
+ test.each(BLOCKED)('rejects non-unicast %s', (ip) => {
+ expect(isPublicUnicastIp(ip)).toBe(false);
+ });
+
+ const NOT_AN_IP = ['example.com', 'not-an-ip', '', ' ', '256.256.256.256', 'localhost'];
+ test.each(NOT_AN_IP)('rejects non-IP input %p without throwing', (value) => {
+ expect(isPublicUnicastIp(value)).toBe(false);
+ });
+});
+
+describe('classifyHost', () => {
+ // Every alternate spelling of loopback must canonicalize to 127.0.0.1 and be
+ // denied — this is the core anti-bypass property. If canonicalization
+ // regressed (e.g. a pre-filter routed these to DNS resolution), the canonical
+ // assertion breaks even though `allowed` might not.
+ const LOOPBACK_SPELLINGS = [
+ '127.0.0.1',
+ '2130706433', // decimal
+ '0177.0.0.1', // octal
+ '0x7f000001', // hex
+ '017700000001', // octal long
+ '127.1', // short form
+ '0x7f.1', // mixed hex + short form
+ ];
+ test.each(LOOPBACK_SPELLINGS)('canonicalizes %s to blocked 127.0.0.1', (host) => {
+ expect(classifyHost(host)).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '127.0.0.1',
+ family: 4,
+ });
+ });
+
+ test('classifies other blocked IPv4 literals with their canonical form', () => {
+ expect(classifyHost('10.0.0.1')).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '10.0.0.1',
+ family: 4,
+ });
+ expect(classifyHost('169.254.169.254')).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '169.254.169.254',
+ family: 4,
+ });
+ expect(classifyHost('0.0.0.0')).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '0.0.0.0',
+ family: 4,
+ });
+ });
+
+ test('classifies blocked IPv6 literals, stripping brackets', () => {
+ expect(classifyHost('::1')).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '::1',
+ family: 6,
+ });
+ expect(classifyHost('[::1]')).toEqual({
+ kind: 'ip-literal',
+ allowed: false,
+ canonical: '::1',
+ family: 6,
+ });
+ expect(classifyHost('fc00::1')).toMatchObject({
+ kind: 'ip-literal',
+ allowed: false,
+ family: 6,
+ });
+ // IPv4-mapped IPv6 stays blocked.
+ expect(classifyHost('::ffff:127.0.0.1')).toMatchObject({
+ kind: 'ip-literal',
+ allowed: false,
+ family: 6,
+ });
+ });
+
+ test('allows public unicast literals and reports family for pinning', () => {
+ expect(classifyHost('93.184.216.34')).toEqual({
+ kind: 'ip-literal',
+ allowed: true,
+ canonical: '93.184.216.34',
+ family: 4,
+ });
+ expect(classifyHost('8.8.8.8')).toEqual({
+ kind: 'ip-literal',
+ allowed: true,
+ canonical: '8.8.8.8',
+ family: 4,
+ });
+ expect(classifyHost('2001:4860:4860::8888')).toEqual({
+ kind: 'ip-literal',
+ allowed: true,
+ canonical: '2001:4860:4860::8888',
+ family: 6,
+ });
+ expect(classifyHost('[2001:4860:4860::8888]')).toEqual({
+ kind: 'ip-literal',
+ allowed: true,
+ canonical: '2001:4860:4860::8888',
+ family: 6,
+ });
+ });
+
+ // DNS names — including spellings that resolve to loopback — are deferred to
+ // the caller's resolve-then-validate step, not decided here.
+ const HOSTNAMES = ['example.com', 'sub.example.com', 'localhost', '127.0.0.1.', 'not-an-ip'];
+ test.each(HOSTNAMES)('defers DNS name %p to resolution', (host) => {
+ expect(classifyHost(host)).toEqual({ kind: 'hostname' });
+ });
+
+ const GARBAGE = ['', ' ', '[', '[]', '::ffff:', 'http://x', '999.999'];
+ test.each(GARBAGE)('never throws on malformed host %p', (host) => {
+ const result = classifyHost(host);
+ expect(['hostname', 'ip-literal']).toContain(result.kind);
+ });
+});
diff --git a/packages/server/src/link-preview/ip-classifier.ts b/packages/server/src/link-preview/ip-classifier.ts
new file mode 100644
index 000000000..6db2ecadf
--- /dev/null
+++ b/packages/server/src/link-preview/ip-classifier.ts
@@ -0,0 +1,80 @@
+/**
+ * SSRF IP classifier — the pure allow/deny decision for whether an outbound
+ * link-preview fetch may target a given host or resolved address.
+ *
+ * Allowlist semantics: a target is permitted ONLY when it is a public unicast
+ * address. Every other range ipaddr.js recognizes — loopback, RFC1918 private,
+ * link-local (which includes the 169.254.169.254 cloud-metadata endpoint),
+ * unique-local, carrier-grade NAT, multicast, unspecified, IPv4-mapped-IPv6,
+ * and any reserved range added upstream later — is denied by default. Denying
+ * IPv4-mapped-IPv6 (::ffff:a.b.c.d) wholesale is deliberate: it is a known SSRF
+ * bypass spelling, and the allowlist rejects it without special-casing because
+ * its range is never 'unicast'. Same unicast-only posture as the editor's
+ * clipboard URL-portability classifier.
+ *
+ * IP-literal hosts are canonicalized before classification so a blocked address
+ * spelled as decimal (2130706433), octal (0177.0.0.1), hex (0x7f000001),
+ * short-form (127.1), or IPv4-mapped-IPv6 (::ffff:127.0.0.1) cannot slip past a
+ * naive equality check; ipaddr.js does the numeric canonicalization in parse().
+ *
+ * Pure and total: no I/O, and any malformed input yields a deny/hostname
+ * outcome instead of throwing. A host this module reports as 'hostname' is not
+ * trusted — the caller must still resolve it and run every resolved address
+ * back through isPublicUnicastIp (a name like `localhost` or `127.0.0.1.` is a
+ * hostname here yet resolves to loopback).
+ */
+
+import ipaddr from 'ipaddr.js';
+
+type ParsedIp = ipaddr.IPv4 | ipaddr.IPv6;
+
+/** Outcome of interpreting a URL host as either an IP literal or a DNS name. */
+export type HostClassification =
+ | { kind: 'hostname' }
+ | { kind: 'ip-literal'; allowed: boolean; canonical: string; family: 4 | 6 };
+
+/**
+ * Parse a host as an IP literal in any spelling ipaddr.js accepts (dotted quad,
+ * decimal/octal/hex integers, short forms, IPv6, optionally bracketed IPv6).
+ * Returns null for anything that is not an IP literal (a DNS name) or that
+ * fails to parse. The string boundary is the only place this module touches
+ * untyped, potentially hostile input, so the parse guard lives here.
+ */
+function parseIpLiteral(host: string): ParsedIp | null {
+ const bare =
+ host.length >= 2 && host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
+ try {
+ if (ipaddr.IPv4.isValid(bare)) return ipaddr.IPv4.parse(bare);
+ if (ipaddr.IPv6.isValid(bare)) return ipaddr.IPv6.parse(bare);
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+/**
+ * True only when `ip` is a public unicast address. Intended for validating each
+ * address returned by DNS resolution before a connection is pinned to it.
+ * Returns false (deny) for private/reserved ranges and for any string that is
+ * not a parseable IP.
+ */
+export function isPublicUnicastIp(ip: string): boolean {
+ const parsed = parseIpLiteral(ip);
+ return parsed !== null && parsed.range() === 'unicast';
+}
+
+/**
+ * Classify a URL host. An IP literal is canonicalized and range-checked here; a
+ * DNS name is reported as 'hostname' so the caller resolves it and validates
+ * each resolved address with isPublicUnicastIp.
+ */
+export function classifyHost(host: string): HostClassification {
+ const parsed = parseIpLiteral(host);
+ if (parsed === null) return { kind: 'hostname' };
+ return {
+ kind: 'ip-literal',
+ allowed: parsed.range() === 'unicast',
+ canonical: parsed.toString(),
+ family: parsed.kind() === 'ipv6' ? 6 : 4,
+ };
+}
diff --git a/packages/server/src/link-preview/metadata.test.ts b/packages/server/src/link-preview/metadata.test.ts
new file mode 100644
index 000000000..6539d46c4
--- /dev/null
+++ b/packages/server/src/link-preview/metadata.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, test } from 'bun:test';
+import type { GuardedFetchOptions, GuardedFetchResult } from './guarded-fetch.ts';
+import { buildLinkPreviewMetadata, type GuardedFetch } from './metadata.ts';
+
+function bytes(...values: number[]): Uint8Array {
+ return new Uint8Array(values);
+}
+
+// Minimal valid magic-number headers for each accepted raster format.
+const PNG = bytes(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01, 0x02, 0x03);
+const JPEG = bytes(0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10);
+const GIF = bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00);
+const BMP = bytes(0x42, 0x4d, 0x10, 0x00, 0x00, 0x00);
+const WEBP = bytes(0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50);
+const ICO = bytes(0x00, 0x00, 0x01, 0x00, 0x01, 0x00);
+const HTML_BYTES = new TextEncoder().encode('<!doctype html><script>alert(1)</script>');
+
+function okResult(body: Uint8Array, contentType = 'image/png'): GuardedFetchResult {
+ return { ok: true, body, contentType, finalUrl: 'https://site.example/favicon.ico' };
+}
+
+/** Injected fetch that returns a fixed result and records the URLs + options it saw. */
+function recordingFetch(result: GuardedFetchResult): {
+ fetch: GuardedFetch;
+ calls: string[];
+ options: Array<GuardedFetchOptions | undefined>;
+} {
+ const calls: string[] = [];
+ const options: Array<GuardedFetchOptions | undefined> = [];
+ const fetch: GuardedFetch = async (url, opts) => {
+ calls.push(url);
+ options.push(opts);
+ return result;
+ };
+ return { fetch, calls, options };
+}
+
+const BASE = {
+ requestUrl: 'https://site.example/page',
+ finalUrl: 'https://site.example/page',
+};
+
+describe('buildLinkPreviewMetadata favicon', () => {
+ test('encodes a validated image as a data URI whose bytes round-trip', async () => {
+ const { fetch } = recordingFetch(okResult(PNG));
+ const meta = await buildLinkPreviewMetadata({ html: '<html></html>', ...BASE, fetch });
+ expect(meta.faviconDataUri).toStartWith('data:image/png;base64,');
+ const decoded = new Uint8Array(Buffer.from(meta.faviconDataUri?.split(',')[1] ?? '', 'base64'));
+ expect(decoded).toEqual(PNG);
+ });
+
+ const FORMATS: Array<[string, Uint8Array]> = [
+ ['image/png', PNG],
+ ['image/jpeg', JPEG],
+ ['image/gif', GIF],
+ ['image/bmp', BMP],
+ ['image/webp', WEBP],
+ ['image/x-icon', ICO],
+ ];
+ test.each(FORMATS)('sniffs %s from its magic bytes', async (mime, header) => {
+ const { fetch } = recordingFetch(okResult(header, 'application/octet-stream'));
+ const meta = await buildLinkPreviewMetadata({ html: '<html></html>', ...BASE, fetch });
+ // The data-URI type comes from the sniffed bytes, not the response header.
+ expect(meta.faviconDataUri).toStartWith(`data:${mime};base64,`);
+ });
+
+ test('rejects non-image bytes even when the response claims an image type', async () => {
+ // Hostile origin: Content-Type says image/png, body is HTML/script.
+ const { fetch } = recordingFetch(okResult(HTML_BYTES, 'image/png'));
+ const meta = await buildLinkPreviewMetadata({ html: '<html></html>', ...BASE, fetch });
+ expect(meta.faviconDataUri).toBeUndefined();
+ });
+
+ test('omits the favicon (partial success) when the guarded fetch fails', async () => {
+ const { fetch } = recordingFetch({ ok: false, reason: 'timeout' });
+ const meta = await buildLinkPreviewMetadata({
+ html: '<html><head><title>Kept</title></head></html>',
+ ...BASE,
+ fetch,
+ });
+ expect(meta.faviconDataUri).toBeUndefined();
+ expect(meta.title).toBe('Kept');
+ });
+
+ test('resolves a relative favicon href against the final (post-redirect) URL', async () => {
+ const { fetch, calls } = recordingFetch(okResult(PNG));
+ await buildLinkPreviewMetadata({
+ html: '<html><head><link rel="icon" href="/assets/fav.png"></head></html>',
+ requestUrl: 'https://site.example/page',
+ finalUrl: 'https://cdn.site.example/landing',
+ fetch,
+ });
+ expect(calls).toEqual(['https://cdn.site.example/assets/fav.png']);
+ });
+
+ test('falls back to /favicon.ico at the origin when no icon link is present', async () => {
+ const { fetch, calls } = recordingFetch(okResult(PNG));
+ await buildLinkPreviewMetadata({
+ html: '<html><head><title>No icon link</title></head></html>',
+ requestUrl: 'https://site.example/deep/page',
+ finalUrl: 'https://site.example/deep/page',
+ fetch,
+ });
+ expect(calls).toEqual(['https://site.example/favicon.ico']);
+ });
+
+ test('caps the favicon fetch with a shorter timeout than the page budget', async () => {
+ // The favicon is non-essential, so its fetch is given a tighter 2.5s
+ // deadline than the page fetch's 5s default — bounding a hover's worst case.
+ const { fetch, options } = recordingFetch(okResult(PNG));
+ await buildLinkPreviewMetadata({ html: '<html></html>', ...BASE, fetch });
+ expect(options[0]?.timeoutMs).toBe(2500);
+ });
+});
+
+describe('buildLinkPreviewMetadata assembly', () => {
+ test('assembles every field for a fully-populated page', async () => {
+ const { fetch } = recordingFetch(okResult(PNG));
+ const html = `<html><head>
+ <meta property="og:title" content="Example Title">
+ <meta property="og:description" content="Example description.">
+ <meta property="og:site_name" content="Example">
+ <link rel="icon" href="/favicon.png">
+ </head><body></body></html>`;
+ const meta = await buildLinkPreviewMetadata({ html, ...BASE, fetch });
+ expect(meta).toEqual({
+ domain: 'site.example',
+ title: 'Example Title',
+ description: 'Example description.',
+ siteName: 'Example',
+ faviconDataUri: meta.faviconDataUri,
+ });
+ expect(meta.faviconDataUri).toStartWith('data:image/png;base64,');
+ });
+
+ test('yields domain-only when the page has no head tags and the favicon fails', async () => {
+ const { fetch } = recordingFetch({ ok: false, reason: 'non-html' });
+ const meta = await buildLinkPreviewMetadata({
+ html: '<html><body>nothing</body></html>',
+ requestUrl: 'https://www.example.org/x',
+ finalUrl: 'https://www.example.org/x',
+ fetch,
+ });
+ expect(meta).toEqual({ domain: 'example.org' });
+ });
+});
diff --git a/packages/server/src/link-preview/metadata.ts b/packages/server/src/link-preview/metadata.ts
new file mode 100644
index 000000000..ed0489ccd
--- /dev/null
+++ b/packages/server/src/link-preview/metadata.ts
@@ -0,0 +1,162 @@
+/**
+ * Assemble the external link-preview card and fetch its one image — the favicon
+ * — first-party through the SSRF-guarded chokepoint. The favicon is the sole
+ * exception to "no remote bytes in the card": the server fetches it, decides its
+ * type by sniffing magic bytes (never the response's own `Content-Type`), and
+ * returns it as a self-contained `data:` URI so the renderer issues no network
+ * request for it. Any favicon failure is a partial success — the metadata is
+ * returned without the icon rather than failing the whole card.
+ */
+
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import {
+ type GuardedFetchOptions,
+ type GuardedFetchResult,
+ guardedFetch,
+} from './guarded-fetch.ts';
+import { deriveDomain, extractHtmlMetadata } from './html-metadata.ts';
+
+/** Favicons are small; a response larger than this is almost certainly not one. */
+const FAVICON_MAX_BYTES = 100 * 1024;
+
+/**
+ * Favicon fetch budget, deliberately shorter than the page fetch's 5s default.
+ * The favicon is non-essential (its failure degrades to a partial success), so
+ * a slow icon host must not be allowed to double a hover's worst-case latency.
+ */
+const FAVICON_TIMEOUT_MS = 2500;
+
+/**
+ * The SSRF-guarded fetch seam. Production passes the real {@link guardedFetch};
+ * tests substitute a function that returns chosen bytes so the sniff + data-URI
+ * assembly can be exercised without real network I/O.
+ */
+export type GuardedFetch = (
+ url: string,
+ options?: GuardedFetchOptions,
+) => Promise<GuardedFetchResult>;
+
+/**
+ * Identify a raster image from its leading bytes, returning the media type for
+ * the data URI or `null` for anything unrecognized. The type is decided by the
+ * bytes, not by any server-supplied header, so a hostile origin cannot pass off
+ * non-image bytes (e.g. HTML) as an image the renderer would treat as trusted.
+ * SVG is intentionally excluded: it carries no fixed magic number and can embed
+ * script, unlike these fixed-signature raster formats.
+ */
+function sniffImageMime(bytes: Uint8Array): string | null {
+ const b = bytes;
+ if (
+ b.length >= 8 &&
+ b[0] === 0x89 &&
+ b[1] === 0x50 &&
+ b[2] === 0x4e &&
+ b[3] === 0x47 &&
+ b[4] === 0x0d &&
+ b[5] === 0x0a &&
+ b[6] === 0x1a &&
+ b[7] === 0x0a
+ ) {
+ return 'image/png';
+ }
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg';
+ if (
+ b.length >= 6 &&
+ b[0] === 0x47 &&
+ b[1] === 0x49 &&
+ b[2] === 0x46 &&
+ b[3] === 0x38 &&
+ (b[4] === 0x37 || b[4] === 0x39) &&
+ b[5] === 0x61
+ ) {
+ return 'image/gif';
+ }
+ if (b.length >= 2 && b[0] === 0x42 && b[1] === 0x4d) return 'image/bmp';
+ if (
+ b.length >= 12 &&
+ b[0] === 0x52 &&
+ b[1] === 0x49 &&
+ b[2] === 0x46 &&
+ b[3] === 0x46 &&
+ b[8] === 0x57 &&
+ b[9] === 0x45 &&
+ b[10] === 0x42 &&
+ b[11] === 0x50
+ ) {
+ return 'image/webp';
+ }
+ if (b.length >= 4 && b[0] === 0x00 && b[1] === 0x00 && b[2] === 0x01 && b[3] === 0x00) {
+ return 'image/x-icon';
+ }
+ return null;
+}
+
+function isImageContentType(mimeType: string): boolean {
+ return mimeType.startsWith('image/');
+}
+
+/**
+ * Resolve the favicon URL: the parsed `<link rel=icon>` href (relative or
+ * absolute) against the page URL, else the origin's `/favicon.ico`. Returns
+ * `null` when a hostile href fails to parse, so no fetch is attempted.
+ */
+function resolveFaviconUrl(faviconHref: string | undefined, baseUrl: string): string | null {
+ try {
+ return new URL(faviconHref ?? '/favicon.ico', baseUrl).toString();
+ } catch {
+ return null;
+ }
+}
+
+async function fetchFavicon(
+ faviconUrl: string,
+ fetchImpl: GuardedFetch,
+): Promise<string | undefined> {
+ const result = await fetchImpl(faviconUrl, {
+ allowContentType: isImageContentType,
+ maxBytes: FAVICON_MAX_BYTES,
+ // Shorter than the page fetch's 5s so a single hover's outbound work is
+ // bounded at ~7.5s worst case (5s page + 2.5s favicon) rather than ~10s.
+ timeoutMs: FAVICON_TIMEOUT_MS,
+ });
+ if (!result.ok) return undefined;
+ const mimeType = sniffImageMime(result.body);
+ if (!mimeType) return undefined;
+ return `data:${mimeType};base64,${Buffer.from(result.body).toString('base64')}`;
+}
+
+export interface BuildLinkPreviewMetadataInput {
+ /** Decoded HTML body of the fetched page. */
+ html: string;
+ /** The URL the user hovered; the shown domain is derived from this. */
+ requestUrl: string;
+ /** The post-redirect URL the HTML came from; the favicon resolves against it. */
+ finalUrl: string;
+ /** SSRF-guarded fetch used for the favicon; defaults to the real chokepoint. */
+ fetch?: GuardedFetch;
+}
+
+/**
+ * Parse the page head, fetch + validate the favicon, and assemble the card's
+ * metadata. The domain is always present (from the request URL); every other
+ * field is included only when non-empty, so a bare page yields `{ domain }`.
+ * This never throws: the parse, domain derivation, and guarded fetch each
+ * absorb their own failures.
+ */
+export async function buildLinkPreviewMetadata(
+ input: BuildLinkPreviewMetadataInput,
+): Promise<LinkPreviewMetadata> {
+ const fields = extractHtmlMetadata(input.html);
+ const faviconUrl = resolveFaviconUrl(fields.faviconHref, input.finalUrl);
+ const faviconDataUri = faviconUrl
+ ? await fetchFavicon(faviconUrl, input.fetch ?? guardedFetch)
+ : undefined;
+
+ return {
+ domain: deriveDomain(input.requestUrl),
+ ...(fields.title !== undefined ? { title: fields.title } : {}),
+ ...(fields.description !== undefined ? { description: fields.description } : {}),
+ ...(fields.siteName !== undefined ? { siteName: fields.siteName } : {}),
+ ...(faviconDataUri !== undefined ? { faviconDataUri } : {}),
+ };
+}
diff --git a/packages/server/src/link-preview/preview-cache.test.ts b/packages/server/src/link-preview/preview-cache.test.ts
new file mode 100644
index 000000000..f8a467d8c
--- /dev/null
+++ b/packages/server/src/link-preview/preview-cache.test.ts
@@ -0,0 +1,291 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import {
+ LinkPreviewCache,
+ type LinkPreviewCacheOptions,
+ type LinkPreviewOutcome,
+ normalizePreviewUrl,
+} from './preview-cache.ts';
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ok-linkpreview-cache-'));
+});
+afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function makeCache(over: Partial<LinkPreviewCacheOptions> = {}): LinkPreviewCache {
+ return new LinkPreviewCache({ cacheDir: dir, ...over });
+}
+
+function ok(domain: string, extra: Partial<LinkPreviewMetadata> = {}): LinkPreviewOutcome {
+ return { ok: true, metadata: { domain, ...extra } };
+}
+
+/** A compute closure plus a call counter — the seam that proves hit vs miss. */
+function counter(outcome: LinkPreviewOutcome): [() => Promise<LinkPreviewOutcome>, () => number] {
+ let n = 0;
+ return [
+ async () => {
+ n += 1;
+ return outcome;
+ },
+ () => n,
+ ];
+}
+
+/** A compute that fails the test if it runs — asserts a lookup was a cache hit. */
+const mustNotFetch = async (): Promise<LinkPreviewOutcome> => {
+ throw new Error('expected a cache hit, but compute ran');
+};
+
+describe('normalizePreviewUrl', () => {
+ test('strips the fragment and userinfo, keeps scheme+host+path+query', () => {
+ expect(normalizePreviewUrl('https://ex.com/p?q=1#a')).toBe(
+ normalizePreviewUrl('https://ex.com/p?q=1#b'),
+ );
+ expect(normalizePreviewUrl('https://ex.com/p?q=1#frag')).toBe('https://ex.com/p?q=1');
+ expect(normalizePreviewUrl('https://user:[email protected]/p')).toBe('https://ex.com/p');
+ });
+
+ test('returns null for an unparseable URL', () => {
+ expect(normalizePreviewUrl('not a url')).toBeNull();
+ });
+});
+
+describe('LinkPreviewCache', () => {
+ test('success → persist → re-init serves the metadata from disk (round-trip)', async () => {
+ const cache = makeCache();
+ await cache.init();
+ const metadata: LinkPreviewMetadata = {
+ domain: 'example.com',
+ title: 'Example',
+ description: 'A description',
+ siteName: 'Example Site',
+ faviconDataUri: 'data:image/png;base64,iVBORw0KGgo=',
+ };
+ await cache.load('https://example.com/page', counter({ ok: true, metadata })[0]);
+ await cache.persist();
+ expect(existsSync(join(dir, 'manifest.json'))).toBe(true);
+ expect(readdirSync(join(dir, 'meta')).length).toBe(1);
+
+ const reopened = makeCache();
+ await reopened.init();
+ // Fragment differs but normalizes to the same key — still a disk hit.
+ expect(await reopened.load('https://example.com/page#section', mustNotFetch)).toEqual({
+ ok: true,
+ metadata,
+ });
+ });
+
+ test('caches a negative outcome and serves it without recomputing', async () => {
+ const cache = makeCache();
+ await cache.init();
+ const first = await cache.load(
+ 'https://n.com/',
+ counter({ ok: false, reason: 'private-ip' })[0],
+ );
+ expect(first).toEqual({ ok: false, reason: 'private-ip' });
+
+ // A later hover offering a *different* outcome must still get the cached failure.
+ const [compute, calls] = counter(ok('n.com'));
+ expect(await cache.load('https://n.com/', compute)).toEqual({
+ ok: false,
+ reason: 'private-ip',
+ });
+ expect(calls()).toBe(0);
+ });
+
+ test('a success past its TTL is a miss and recomputes', async () => {
+ let clock = 1_000_000;
+ const cache = makeCache({ successTtlMs: 5000, now: () => clock });
+ await cache.init();
+ const [first, firstCalls] = counter(ok('s.com'));
+ await cache.load('https://s.com/', first);
+ expect(firstCalls()).toBe(1);
+
+ const [withinTtl, withinCalls] = counter(ok('s.com'));
+ await cache.load('https://s.com/', withinTtl);
+ expect(withinCalls()).toBe(0); // still fresh → hit
+
+ clock += 6000; // past the 5s success TTL
+ const [afterTtl, afterCalls] = counter(ok('s.com'));
+ await cache.load('https://s.com/', afterTtl);
+ expect(afterCalls()).toBe(1); // expired → recompute
+ });
+
+ test('a negative past its short TTL recomputes so a dead link recovers', async () => {
+ let clock = 1_000_000;
+ const cache = makeCache({ negativeTtlMs: 1000, now: () => clock });
+ await cache.init();
+ await cache.load('https://nt.com/', counter({ ok: false, reason: 'timeout' })[0]);
+
+ clock += 2000; // past the 1s negative TTL
+ const [compute, calls] = counter(ok('nt.com'));
+ expect(await cache.load('https://nt.com/', compute)).toEqual(ok('nt.com'));
+ expect(calls()).toBe(1);
+ });
+
+ test('coalesces concurrent identical lookups into a single compute (single-flight)', async () => {
+ const cache = makeCache();
+ await cache.init();
+ let resolveGate!: (o: LinkPreviewOutcome) => void;
+ const gate = new Promise<LinkPreviewOutcome>((resolve) => {
+ resolveGate = resolve;
+ });
+ let calls = 0;
+ const compute = () => {
+ calls += 1;
+ return gate;
+ };
+
+ const p1 = cache.load('https://x.com/', compute);
+ const p2 = cache.load('https://x.com/', compute);
+ resolveGate(ok('x.com'));
+ const [r1, r2] = await Promise.all([p1, p2]);
+
+ expect(calls).toBe(1);
+ expect(r1).toEqual(ok('x.com'));
+ expect(r2).toEqual(ok('x.com'));
+ });
+
+ test('clears the in-flight slot when compute throws (no stuck key, no caching)', async () => {
+ const cache = makeCache();
+ await cache.init();
+ await expect(
+ cache.load('https://y.com/', async () => {
+ throw new Error('boom');
+ }),
+ ).rejects.toThrow('boom');
+
+ // The failed compute was not cached and the slot is free → the next load runs.
+ const [compute, calls] = counter(ok('y.com'));
+ expect(await cache.load('https://y.com/', compute)).toEqual(ok('y.com'));
+ expect(calls()).toBe(1);
+ });
+
+ test('evicts the least-recently-used entry past the size cap', async () => {
+ const cache = makeCache({ maxEntries: 2 });
+ await cache.init();
+ await cache.load('https://a.com/', counter(ok('a.com'))[0]);
+ await cache.load('https://b.com/', counter(ok('b.com'))[0]);
+ await cache.load('https://c.com/', counter(ok('c.com'))[0]); // evicts a (oldest)
+ expect(cache.size).toBe(2);
+
+ const [reA, reACalls] = counter(ok('a.com'));
+ await cache.load('https://a.com/', reA);
+ expect(reACalls()).toBe(1); // a was evicted → recompute
+
+ // c was accessed more recently than b, so it survived — a hit.
+ await cache.load('https://c.com/', mustNotFetch);
+
+ await cache.persist();
+ // Only the two live entries have blobs on disk; the evicted one is GC'd.
+ expect(readdirSync(join(dir, 'meta')).length).toBe(2);
+ });
+
+ test('a hit bumps recency so the next eviction drops the older un-accessed key', async () => {
+ const cache = makeCache({ maxEntries: 2 });
+ await cache.init();
+ await cache.load('https://a.com/', counter(ok('a.com'))[0]); // {a}
+ await cache.load('https://b.com/', counter(ok('b.com'))[0]); // {a,b}
+ await cache.load('https://a.com/', mustNotFetch); // hit bumps a → {b,a}
+ await cache.load('https://c.com/', counter(ok('c.com'))[0]); // adding c evicts b (now oldest) → {a,c}
+
+ // The bump moved a's recency above b, so b — not a — was the eviction victim.
+ // Assert a's survival before recomputing b, since recomputing b would itself
+ // evict the next-oldest entry.
+ await cache.load('https://a.com/', mustNotFetch); // a survived → hit
+ const [reB, reBCalls] = counter(ok('b.com'));
+ await cache.load('https://b.com/', reB);
+ expect(reBCalls()).toBe(1); // b was evicted → recompute
+ });
+
+ test('a corrupt manifest is treated as empty and never throws', async () => {
+ writeFileSync(join(dir, 'manifest.json'), 'not-json{{{');
+ const cache = makeCache();
+ await cache.init(); // must not throw
+ expect(cache.size).toBe(0);
+
+ const [compute, calls] = counter(ok('c.com'));
+ await cache.load('https://c.com/', compute);
+ expect(calls()).toBe(1); // empty cache → computes
+ });
+
+ test('a success blob that no longer matches the schema drops the entry', async () => {
+ const cache = makeCache();
+ await cache.init();
+ await cache.load('https://b.com/page', counter(ok('b.com'))[0]);
+ await cache.persist();
+ const [blob] = readdirSync(join(dir, 'meta'));
+ writeFileSync(join(dir, 'meta', blob as string), '{"unexpected":true}'); // valid JSON, wrong shape
+
+ const reopened = makeCache();
+ await reopened.init(); // drops the entry, no throw
+ const [compute, calls] = counter(ok('b.com'));
+ await reopened.load('https://b.com/page', compute);
+ expect(calls()).toBe(1); // unusable blob → recompute
+ });
+
+ test('drops an already-expired entry on init (no resurrection)', async () => {
+ let clock = 1_000_000;
+ const cache = makeCache({ negativeTtlMs: 1000, now: () => clock });
+ await cache.init();
+ await cache.load('https://g.com/', counter({ ok: false, reason: 'timeout' })[0]);
+ await cache.persist();
+
+ clock += 2000; // the persisted entry is now stale
+ const reopened = makeCache({ negativeTtlMs: 1000, now: () => clock });
+ await reopened.init();
+ expect(reopened.size).toBe(0);
+ const [compute, calls] = counter(ok('g.com'));
+ await reopened.load('https://g.com/', compute);
+ expect(calls()).toBe(1);
+ });
+
+ test('memory-only mode (cacheDir null) caches in memory and never touches disk', async () => {
+ const cache = new LinkPreviewCache({ cacheDir: null });
+ await cache.init();
+ const [compute, calls] = counter(ok('m.com'));
+ await cache.load('https://m.com/', compute);
+ await cache.load('https://m.com/', compute); // hit
+ expect(calls()).toBe(1);
+ await expect(cache.persist()).resolves.toBeUndefined(); // no-op, no throw
+ expect(readdirSync(dir).length).toBe(0);
+ });
+
+ test('wipe clears memory and the on-disk cache directory', async () => {
+ const cache = makeCache();
+ await cache.init();
+ await cache.load('https://w.com/', counter(ok('w.com'))[0]);
+ await cache.persist();
+ expect(existsSync(join(dir, 'manifest.json'))).toBe(true);
+
+ await cache.wipe();
+ expect(existsSync(dir)).toBe(false);
+
+ const [compute, calls] = counter(ok('w.com'));
+ await cache.load('https://w.com/', compute);
+ expect(calls()).toBe(1); // memory cleared → recompute
+ });
+
+ test('persist is best-effort when the cache directory is unwritable', async () => {
+ // A regular file where the cache dir should be → mkdir(meta) fails with ENOTDIR.
+ const blocker = join(dir, 'blocker');
+ writeFileSync(blocker, 'x');
+ const cache = new LinkPreviewCache({ cacheDir: join(blocker, 'nested') });
+ await cache.init(); // no throw
+
+ await cache.load('https://e.com/', counter(ok('e.com'))[0]);
+ await expect(cache.persist()).resolves.toBeUndefined(); // swallows the fs error
+
+ // The failed flush left the in-memory cache intact — still a hit.
+ const [compute, calls] = counter(ok('e.com'));
+ expect(await cache.load('https://e.com/', compute)).toEqual(ok('e.com'));
+ expect(calls()).toBe(0);
+ });
+});
diff --git a/packages/server/src/link-preview/preview-cache.ts b/packages/server/src/link-preview/preview-cache.ts
new file mode 100644
index 000000000..011445be0
--- /dev/null
+++ b/packages/server/src/link-preview/preview-cache.ts
@@ -0,0 +1,400 @@
+/**
+ * Persistent, best-effort cache for external link previews.
+ *
+ * Lives under `<projectDir>/.ok/local/link-previews/` (git-ignored, never synced).
+ * A hover fetch is comparatively expensive (SSRF-guarded network round-trip +
+ * HTML parse + favicon fetch), so a repeated hover of the same link — and a
+ * document's second open — should serve from disk with no network at all.
+ *
+ * Layout mirrors the vector cache (manifest index + payload blobs):
+ * link-previews/
+ * manifest.json { schemaVersion, entries: { <normalizedUrl>: entry } }
+ * meta/<sha256(url)>.json the LinkPreviewMetadata for a success entry
+ *
+ * The manifest holds only the small index (status + timestamps); the potentially
+ * large success payload — its favicon `data:` URI can approach the fetch cap —
+ * lives in a per-URL blob, so a hot LRU-touch never rewrites favicon bytes.
+ *
+ * The key is the normalized URL (scheme+host+path+query, fragment and userinfo
+ * stripped), so `#a` / `#b` variants and credentialed forms of one page share
+ * one entry.
+ *
+ * Recency is Map insertion order: a hit deletes-and-reinserts the key so the
+ * oldest key is always `entries.keys().next()`, and eviction past the size cap
+ * drops from the front. Success entries live ~7 days, failures ~1 hour (so a
+ * dead link is not re-hammered); an expired entry reads as a miss and is dropped.
+ *
+ * Every disk operation is wrapped in try/catch and degrades to a recompute — a
+ * corrupt manifest or blob is a miss, never a throw into the caller. Reads come
+ * back through the metadata schema, so a tampered blob that no longer matches the
+ * shape is dropped rather than trusted. Concurrent identical lookups coalesce to
+ * a single in-flight compute.
+ */
+
+import { createHash } from 'node:crypto';
+import { existsSync, readdirSync } from 'node:fs';
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { type LinkPreviewMetadata, LinkPreviewMetadataSchema } from '@inkeep/open-knowledge-core';
+import {
+ tracedMkdir,
+ tracedRename,
+ tracedRmSync,
+ tracedUnlinkSync,
+ tracedWriteFile,
+} from '../fs-traced.ts';
+import { getLogger } from '../logger.ts';
+
+const log = getLogger('link-preview.cache');
+
+/** On-disk manifest layout version — bump on any structural format change. */
+const MANIFEST_SCHEMA_VERSION = 1;
+const META_SUBDIR = 'meta';
+const MANIFEST_NAME = 'manifest.json';
+
+/** A cached success serves this long before it is re-fetched. */
+const DEFAULT_SUCCESS_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+/** A cached failure serves this long — short, so a transiently-dead link recovers. */
+const DEFAULT_NEGATIVE_TTL_MS = 60 * 60 * 1000;
+/** Entries retained before the least-recently-used is evicted. */
+const DEFAULT_MAX_ENTRIES = 256;
+
+/**
+ * The result of a preview lookup: the assembled card metadata, or a bounded
+ * reason code for a failure. This is exactly the envelope the route returns and
+ * the value the cache persists.
+ */
+export type LinkPreviewOutcome =
+ | { ok: true; metadata: LinkPreviewMetadata }
+ | { ok: false; reason: string };
+
+interface CacheEntry {
+ status: 'ok' | 'negative';
+ fetchedAt: number;
+ expiresAt: number;
+ /** Present only on a negative entry. */
+ reason?: string;
+}
+
+interface ManifestFile {
+ schemaVersion: number;
+ entries: Record<string, CacheEntry>;
+}
+
+export interface LinkPreviewCacheOptions {
+ /** Cache home (`<projectDir>/.ok/local/link-previews`), or `null` for memory-only (tests). */
+ cacheDir: string | null;
+ /** Overrides {@link DEFAULT_MAX_ENTRIES}. */
+ maxEntries?: number;
+ /** Overrides {@link DEFAULT_SUCCESS_TTL_MS}. */
+ successTtlMs?: number;
+ /** Overrides {@link DEFAULT_NEGATIVE_TTL_MS}. */
+ negativeTtlMs?: number;
+ /** Clock seam; defaults to `Date.now`. Injected so TTL tests need no sleeps. */
+ now?: () => number;
+}
+
+/**
+ * Normalize a URL to its cache key: scheme + host + path + query, with the
+ * fragment and any userinfo removed. Returns `null` for an unparseable URL, so
+ * a caller declines to cache rather than keying on a malformed string.
+ */
+export function normalizePreviewUrl(rawUrl: string): string | null {
+ try {
+ const url = new URL(rawUrl);
+ url.hash = '';
+ url.username = '';
+ url.password = '';
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
+
+function hashKey(key: string): string {
+ return createHash('sha256').update(key, 'utf-8').digest('hex');
+}
+
+export class LinkPreviewCache {
+ private readonly cacheDir: string | null;
+ private readonly metaDir: string | null;
+ private readonly manifestPath: string | null;
+ private readonly maxEntries: number;
+ private readonly successTtlMs: number;
+ private readonly negativeTtlMs: number;
+ private readonly now: () => number;
+
+ /** normalizedUrl → index entry, in LRU order (oldest first). */
+ private readonly entries = new Map<string, CacheEntry>();
+ /** normalizedUrl → success payload (mirrors the `ok` entries). */
+ private readonly payloads = new Map<string, LinkPreviewMetadata>();
+ /** normalizedUrl whose success blob is already on disk (skip re-write on persist). */
+ private readonly persistedKeys = new Set<string>();
+ /** In-flight computes, keyed by normalizedUrl — the single-flight seam. */
+ private readonly inFlight = new Map<string, Promise<LinkPreviewOutcome>>();
+
+ private dirty = false;
+ private persisting = false;
+ private persistPending = false;
+
+ constructor(options: LinkPreviewCacheOptions) {
+ this.cacheDir = options.cacheDir;
+ this.metaDir = options.cacheDir ? join(options.cacheDir, META_SUBDIR) : null;
+ this.manifestPath = options.cacheDir ? join(options.cacheDir, MANIFEST_NAME) : null;
+ this.maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
+ this.successTtlMs = options.successTtlMs ?? DEFAULT_SUCCESS_TTL_MS;
+ this.negativeTtlMs = options.negativeTtlMs ?? DEFAULT_NEGATIVE_TTL_MS;
+ this.now = options.now ?? Date.now;
+ }
+
+ /**
+ * Load the manifest + referenced success blobs into memory, dropping any
+ * entry already past its TTL or whose blob is missing/unreadable. Never throws:
+ * an absent, corrupt, or version-mismatched cache starts empty.
+ */
+ async init(): Promise<void> {
+ if (!this.cacheDir || !this.manifestPath || !this.metaDir) return;
+ let manifest: ManifestFile | null = null;
+ try {
+ if (existsSync(this.manifestPath)) {
+ manifest = JSON.parse(await readFile(this.manifestPath, 'utf-8')) as ManifestFile;
+ }
+ } catch (err) {
+ log.warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[link-preview] unreadable cache manifest — starting empty',
+ );
+ return;
+ }
+ if (!manifest || manifest.schemaVersion !== MANIFEST_SCHEMA_VERSION || !manifest.entries) {
+ return;
+ }
+
+ const now = this.now();
+ for (const [key, entry] of Object.entries(manifest.entries)) {
+ if (!entry || (entry.status !== 'ok' && entry.status !== 'negative')) continue;
+ if (typeof entry.expiresAt !== 'number' || now >= entry.expiresAt) continue;
+ if (entry.status === 'ok') {
+ const payload = await this.readBlob(key);
+ if (!payload) continue; // no usable payload → not a serveable success
+ this.payloads.set(key, payload);
+ this.persistedKeys.add(key);
+ }
+ this.entries.set(key, entry);
+ }
+ }
+
+ /**
+ * Return the cached outcome for `rawUrl` if fresh, otherwise run `compute`
+ * once — coalescing concurrent identical lookups onto a single in-flight
+ * promise — and cache its result. A negative cache hit returns the stored
+ * failure without recomputing.
+ */
+ async load(
+ rawUrl: string,
+ compute: () => Promise<LinkPreviewOutcome>,
+ ): Promise<LinkPreviewOutcome> {
+ const key = normalizePreviewUrl(rawUrl);
+ if (key === null) return compute(); // unkeyable → run once, don't cache
+
+ const fresh = this.getFresh(key);
+ if (fresh) return fresh;
+
+ const existing = this.inFlight.get(key);
+ if (existing) return existing;
+
+ const promise = (async () => {
+ const outcome = await compute();
+ this.record(key, outcome);
+ return outcome;
+ })();
+ // Detach cleanup from the returned promise so a thrown compute still frees
+ // the single-flight slot without turning the rejection into an unhandled one
+ // for coalesced awaiters.
+ const tracked = promise.finally(() => {
+ this.inFlight.delete(key);
+ });
+ this.inFlight.set(key, tracked);
+ return tracked;
+ }
+
+ /** Fresh (unexpired) cached outcome for a normalized key, bumping its recency. */
+ private getFresh(key: string): LinkPreviewOutcome | undefined {
+ const entry = this.entries.get(key);
+ if (!entry) return undefined;
+ if (this.now() >= entry.expiresAt) {
+ this.drop(key);
+ this.dirty = true;
+ return undefined;
+ }
+ // LRU touch: reinsert at the end so the oldest key stays at the front.
+ this.entries.delete(key);
+ this.entries.set(key, entry);
+ if (entry.status === 'negative') {
+ return { ok: false, reason: entry.reason ?? 'error' };
+ }
+ const metadata = this.payloads.get(key);
+ if (!metadata) {
+ // A success index with no payload can't be served — treat as a miss.
+ this.drop(key);
+ this.dirty = true;
+ return undefined;
+ }
+ return { ok: true, metadata };
+ }
+
+ private record(key: string, outcome: LinkPreviewOutcome): void {
+ const fetchedAt = this.now();
+ // A record always follows a miss/expiry, so any prior blob is stale.
+ this.persistedKeys.delete(key);
+ this.entries.delete(key);
+ this.payloads.delete(key);
+ if (outcome.ok) {
+ this.entries.set(key, { status: 'ok', fetchedAt, expiresAt: fetchedAt + this.successTtlMs });
+ this.payloads.set(key, outcome.metadata);
+ } else {
+ this.entries.set(key, {
+ status: 'negative',
+ fetchedAt,
+ expiresAt: fetchedAt + this.negativeTtlMs,
+ reason: outcome.reason,
+ });
+ }
+ this.dirty = true;
+ this.evict();
+ }
+
+ /** Drop the least-recently-used entries until the cap is satisfied. */
+ private evict(): void {
+ while (this.entries.size > this.maxEntries) {
+ const oldest = this.entries.keys().next().value;
+ if (oldest === undefined) break;
+ this.drop(oldest);
+ this.dirty = true;
+ }
+ }
+
+ private drop(key: string): void {
+ this.entries.delete(key);
+ this.payloads.delete(key);
+ this.persistedKeys.delete(key);
+ }
+
+ /**
+ * Flush the manifest + any unwritten success blobs to disk and GC orphaned
+ * blob files. Best-effort: an unwritable cache logs and returns rather than
+ * throwing. Concurrent calls coalesce so two fires can't race one manifest.
+ */
+ async persist(): Promise<void> {
+ if (!this.cacheDir) return;
+ if (this.persisting) {
+ this.persistPending = true;
+ return;
+ }
+ this.persisting = true;
+ try {
+ do {
+ this.persistPending = false;
+ await this.writeToDisk();
+ } while (this.persistPending && this.dirty);
+ } finally {
+ this.persisting = false;
+ }
+ }
+
+ private async writeToDisk(): Promise<void> {
+ if (!this.cacheDir || !this.manifestPath || !this.metaDir) return;
+ if (!this.dirty) return;
+ try {
+ await tracedMkdir(this.metaDir, { recursive: true });
+
+ const referencedHashes = new Set<string>();
+ for (const [key, entry] of this.entries) {
+ if (entry.status !== 'ok') continue;
+ referencedHashes.add(hashKey(key));
+ if (this.persistedKeys.has(key)) continue;
+ const metadata = this.payloads.get(key);
+ if (!metadata) continue;
+ await tracedWriteFile(join(this.metaDir, `${hashKey(key)}.json`), JSON.stringify(metadata));
+ this.persistedKeys.add(key);
+ }
+
+ const manifest: ManifestFile = {
+ schemaVersion: MANIFEST_SCHEMA_VERSION,
+ entries: Object.fromEntries(this.entries),
+ };
+ const tmp = `${this.manifestPath}.tmp`;
+ await tracedWriteFile(tmp, JSON.stringify(manifest));
+ await tracedRename(tmp, this.manifestPath);
+
+ for (const file of readdirSync(this.metaDir)) {
+ if (!file.endsWith('.json')) continue;
+ const hash = file.slice(0, -'.json'.length);
+ if (!referencedHashes.has(hash)) {
+ tracedUnlinkSync(join(this.metaDir, file));
+ }
+ }
+ this.dirty = false;
+ } catch (err) {
+ // Persistence is best-effort: an unwritable cache degrades to a recompute
+ // next boot, it must never fail a preview request.
+ log.warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[link-preview] failed to persist cache',
+ );
+ }
+ }
+
+ /** Forget everything in memory; the disk store is untouched. */
+ clearMemory(): void {
+ this.entries.clear();
+ this.payloads.clear();
+ this.persistedKeys.clear();
+ this.inFlight.clear();
+ this.dirty = false;
+ }
+
+ /** Wipe memory + the on-disk cache directory (best-effort). */
+ async wipe(): Promise<void> {
+ this.clearMemory();
+ if (!this.cacheDir) return;
+ try {
+ tracedRmSync(this.cacheDir, { recursive: true, force: true });
+ } catch (err) {
+ log.warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[link-preview] failed to wipe cache',
+ );
+ }
+ }
+
+ /** Number of live entries (coverage / cap assertions). */
+ get size(): number {
+ return this.entries.size;
+ }
+
+ /**
+ * Read + validate a success blob. Returns `null` when the blob is absent,
+ * unreadable, or no longer matches the metadata shape (a tampered or
+ * schema-drifted file is dropped, not trusted).
+ */
+ private async readBlob(key: string): Promise<LinkPreviewMetadata | null> {
+ if (!this.metaDir) return null;
+ const blobPath = join(this.metaDir, `${hashKey(key)}.json`);
+ try {
+ if (!existsSync(blobPath)) return null;
+ const parsed = LinkPreviewMetadataSchema.safeParse(
+ JSON.parse(await readFile(blobPath, 'utf-8')),
+ );
+ return parsed.success ? parsed.data : null;
+ } catch (err) {
+ // Mirror the manifest-level warn: a corrupt/unreadable blob is a miss, not
+ // a throw. Reason only — never the URL/host/content (topology-leak hygiene).
+ log.warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ '[link-preview] unreadable cache blob — treating as miss',
+ );
+ return null;
+ }
+ }
+}
diff --git a/packages/server/src/link-preview/request-gate.test.ts b/packages/server/src/link-preview/request-gate.test.ts
new file mode 100644
index 000000000..998f161d8
--- /dev/null
+++ b/packages/server/src/link-preview/request-gate.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ classifyLinkPreviewRequest,
+ isJsonContentType,
+ isLoopbackHttpOrigin,
+} from './request-gate.ts';
+
+describe('isLoopbackHttpOrigin', () => {
+ test.each([
+ ['http://localhost', true],
+ ['http://localhost:5173', true],
+ ['https://localhost', true],
+ ['http://127.0.0.1', true],
+ ['http://127.0.0.1:8080', true],
+ ['http://127.13.99.4', true],
+ ['http://[::1]', true],
+ ['http://[::1]:5173', true],
+ ] as const)('admits loopback http(s) origin %s', (origin, expected) => {
+ expect(isLoopbackHttpOrigin(origin)).toBe(expected);
+ });
+
+ test.each([
+ // The two the shared gate would wave through — the whole point of this gate.
+ [undefined, 'absent Origin'],
+ ['null', 'opaque / sandboxed-iframe Origin'],
+ // Non-loopback and lookalike authorities.
+ ['https://evil.com', 'public origin'],
+ ['http://127.0.0.1.evil.com', 'loopback-prefixed rebind lookalike'],
+ ['http://localhost.evil.com', 'localhost-prefixed lookalike'],
+ // Wrong scheme / unparseable.
+ ['file:///Users/x/app/index.html', 'file scheme (packaged renderer)'],
+ ['ftp://localhost', 'non-http scheme'],
+ ['not a url', 'unparseable'],
+ ['', 'empty string'],
+ ] as const)('rejects %s (%s)', (origin, _why) => {
+ expect(isLoopbackHttpOrigin(origin)).toBe(false);
+ });
+});
+
+describe('isJsonContentType', () => {
+ test.each([
+ ['application/json', true],
+ ['application/json; charset=utf-8', true],
+ ['APPLICATION/JSON', true],
+ [' application/json ', true],
+ ] as const)('admits JSON content type %s', (ct, expected) => {
+ expect(isJsonContentType(ct)).toBe(expected);
+ });
+
+ test.each([
+ [undefined, 'missing'],
+ ['', 'empty'],
+ ['text/plain', 'simple-request text'],
+ ['text/plain;charset=UTF-8', 'simple-request text with charset'],
+ ['multipart/form-data; boundary=x', 'simple-request multipart'],
+ ['application/x-www-form-urlencoded', 'simple-request form'],
+ ['application/json-patch+json', 'json-adjacent but not json'],
+ ] as const)('rejects %s content type (%s)', (ct, _why) => {
+ expect(isJsonContentType(ct)).toBe(false);
+ });
+});
+
+describe('classifyLinkPreviewRequest', () => {
+ test('admits a loopback-origin JSON POST', () => {
+ expect(
+ classifyLinkPreviewRequest({
+ origin: 'http://127.0.0.1:5173',
+ contentType: 'application/json',
+ }),
+ ).toEqual({ ok: true });
+ });
+
+ test.each([
+ [undefined, 'absent Origin'],
+ ['null', 'null Origin (sandboxed iframe)'],
+ ['https://evil.com', 'cross-origin'],
+ ] as const)('refuses %s for reason=origin (%s)', (origin, _why) => {
+ expect(classifyLinkPreviewRequest({ origin, contentType: 'application/json' })).toEqual({
+ ok: false,
+ reason: 'origin',
+ });
+ });
+
+ test.each([
+ [undefined, 'missing content type'],
+ ['text/plain', 'text/plain bypass'],
+ ['multipart/form-data', 'multipart bypass'],
+ ] as const)('refuses %s for reason=content-type (%s)', (contentType, _why) => {
+ expect(classifyLinkPreviewRequest({ origin: 'http://localhost:5173', contentType })).toEqual({
+ ok: false,
+ reason: 'content-type',
+ });
+ });
+
+ test('origin is judged before content type', () => {
+ // A null origin with a non-JSON body is refused for the origin, the more
+ // informative reason — not masked by the content-type check.
+ expect(classifyLinkPreviewRequest({ origin: 'null', contentType: 'text/plain' })).toEqual({
+ ok: false,
+ reason: 'origin',
+ });
+ });
+});
diff --git a/packages/server/src/link-preview/request-gate.ts b/packages/server/src/link-preview/request-gate.ts
new file mode 100644
index 000000000..a9d86becf
--- /dev/null
+++ b/packages/server/src/link-preview/request-gate.ts
@@ -0,0 +1,84 @@
+/**
+ * Anti-proxy admission for `POST /api/link-preview` — pure header logic, kept
+ * out of the route handler so the security decision can be exercised directly.
+ *
+ * This gate is deliberately STRICTER than the shared `/api/*` origin allowlist.
+ * The shared gate accepts an absent Origin and the opaque `"null"` Origin, so a
+ * sandboxed iframe (opaque origin) or a no-Origin simple request could reach a
+ * route through it. This endpoint performs outbound fetches on the user's
+ * behalf, so a caller that slipped through would be a readable server-side
+ * request-forgery proxy for any local browser tab. To close that door the gate
+ * admits ONLY a same-machine http(s) loopback Origin, and rejects absent /
+ * `"null"` / non-loopback Origins outright; it also requires an
+ * `application/json` content type so a CORS "simple request" (which can carry
+ * only `text/plain` / form encodings and thus dodges the JSON preflight) cannot
+ * be used as a bypass.
+ *
+ * Trade-off worth knowing: a packaged Electron renderer loaded from `file://`
+ * presents Origin `"null"` and is therefore refused here just like an attacker
+ * would be — the two are indistinguishable at the HTTP layer. That renderer
+ * degrades to the plain URL pill; it is not served a preview. Loosening the
+ * gate to admit `"null"` to serve it would reopen the readable-proxy hole, so
+ * the strict form is intentional.
+ */
+
+/**
+ * Why a request was refused, so the caller can pick the right problem type.
+ * @lintignore Referenced by the exported LinkPreviewGateVerdict type; no direct importer.
+ */
+export type LinkPreviewGateRejection = 'origin' | 'content-type';
+
+export type LinkPreviewGateVerdict = { ok: true } | { ok: false; reason: LinkPreviewGateRejection };
+
+/**
+ * A loopback http(s) Origin — the only Origin this endpoint serves. Absent and
+ * the opaque `"null"` Origin both return false (rejected): they are the exact
+ * shapes the shared gate would wave through. Hostname is compared after URL
+ * parsing so a crafted authority like `http://127.0.0.1.evil.com` (hostname
+ * `127.0.0.1.evil.com`) does not match the loopback set.
+ */
+export function isLoopbackHttpOrigin(origin: string | undefined): boolean {
+ if (!origin || origin === 'null') return false;
+ let parsed: URL;
+ try {
+ parsed = new URL(origin);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
+ const host = parsed.hostname;
+ return (
+ host === 'localhost' ||
+ // WHATWG URL keeps the brackets on an IPv6 hostname, so the loopback IPv6
+ // literal presents as `[::1]` here — never a bare `::1`.
+ host === '[::1]' ||
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)
+ );
+}
+
+/**
+ * True only for an `application/json` content type (with or without parameters
+ * like `; charset=utf-8`). A missing type, `text/plain`, and the multipart /
+ * form encodings all return false — those are the simple-request media types a
+ * cross-origin caller can send without triggering a CORS preflight.
+ */
+export function isJsonContentType(contentType: string | undefined): boolean {
+ if (!contentType) return false;
+ const base = contentType.split(';', 1)[0]?.trim().toLowerCase();
+ return base === 'application/json';
+}
+
+/**
+ * Decide whether a request may proceed to the preview fetch. Returns the reason
+ * on refusal so the route can map it to the matching RFC 9457 problem type.
+ * Origin is checked before content type so a cross-origin caller is refused for
+ * the more informative reason.
+ */
+export function classifyLinkPreviewRequest(headers: {
+ origin: string | undefined;
+ contentType: string | undefined;
+}): LinkPreviewGateVerdict {
+ if (!isLoopbackHttpOrigin(headers.origin)) return { ok: false, reason: 'origin' };
+ if (!isJsonContentType(headers.contentType)) return { ok: false, reason: 'content-type' };
+ return { ok: true };
+}
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index af4d7deae..10ab117ee 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -613,6 +613,22 @@ export function createServer(options: ServerOptions): ServerInstance {
});
}
+ // Same project-local, fresh-read contract as `readSemanticSearchConfig`, for
+ // the link-preview egress opt-in: `linkPreviews.enabled` must never be honored
+ // from a committed/shared config layer (one collaborator must not switch on
+ // egress for everyone who clones), and a Settings toggle must apply to the
+ // next hover without a restart. An absent or invalid config reads as disabled
+ // (`readConfigSafely` degrades to schema defaults), keeping the route
+ // fail-closed.
+ function readLinkPreviewsEnabled(): boolean {
+ const local = readConfigSafely({
+ absPath: resolveConfigPath('project-local', projectDir, configHomedirOverride),
+ sideline: false,
+ warn: (message) => log.warn({ message }, '[config] could not read project-local config'),
+ });
+ return local.value.linkPreviews?.enabled === true;
+ }
+
// Provider identity for the cache key + the service's re-warm trigger. A change
// here (provider/model/dims) re-loads the embedder and invalidates the cache.
function semanticProviderFingerprint(cfg: ResolvedSemanticConfig): string {
@@ -1571,6 +1587,7 @@ export function createServer(options: ServerOptions): ServerInstance {
},
semanticSearch,
getSemanticSimilarityFloor: () => readSemanticSearchConfig().similarityFloor,
+ getLinkPreviewsEnabled: readLinkPreviewsEnabled,
embeddingsSecretsFile: secretsFilePath(configHomedirOverride),
ephemeral,
onReferencedAssetsCacheInvalidator: (invalidate) => {