Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions apps/pi-extension/server/serverAnnotate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ import {
HTML_ASSET_DOCUMENT_CSP,
HTML_ASSET_ERROR_CSP,
HTML_ASSET_ROUTE_PREFIX,
prependNoNetworkMarker,
buildHtmlAssetErrorDocument,
encodeHtmlAssetPath,
htmlAssetBaseHref,
Expand Down Expand Up @@ -197,18 +198,21 @@ function createHtmlAssetRegistry(

function rewriteHtml(htmlContent: string, htmlFilePath: string): string {
if (/^https?:\/\//i.test(htmlFilePath)) return htmlContent;
// Outside the session's roots the viewer's srcdoc frame gets no network
// either (HTML_NO_NETWORK_MARKER), as the asset route's document does (mirrors the Bun registry).
const outside = isOutside(htmlFilePath);
try {
const { root, basePath, docDir } = htmlAssetContext(htmlFilePath, folderPath);
const token = register(root, docDir, isOutside(htmlFilePath));
const token = register(root, docDir, outside);
return rewriteHtmlAssetReferences(
htmlContent,
(assetPath) => `${HTML_ASSET_ROUTE_PREFIX}/${token}/${encodeHtmlAssetPath(assetPath)}`,
// Root-relative on purpose: a srcdoc document resolves its own
// <base href> against the PARENT's URL, which is this server.
{ baseHref: htmlAssetBaseHref(token) + (basePath ? `${encodeHtmlAssetPath(basePath)}/` : ""), assetBasePath: basePath },
{ baseHref: htmlAssetBaseHref(token) + (basePath ? `${encodeHtmlAssetPath(basePath)}/` : ""), assetBasePath: basePath, noNetwork: outside },
);
} catch {
return htmlContent;
return outside ? prependNoNetworkMarker(htmlContent) : htmlContent;
}
}

Expand Down
3 changes: 3 additions & 0 deletions apps/pi-extension/vendor.sh
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ printf '// @generated — DO NOT EDIT. Source: packages/ui/components/html-viewe
# bridge-script.ts imports the sandbox shim (a dependency-free string constant too).
printf '// @generated — DO NOT EDIT. Source: packages/ui/components/html-viewer/sandboxShim.ts\n' \
| cat - "../../packages/ui/components/html-viewer/sandboxShim.ts" > "generated/sandboxShim.ts"
# ...and the link guard (dependency-free too).
printf '// @generated — DO NOT EDIT. Source: packages/ui/components/html-viewer/linkGuard.ts\n' \
| cat - "../../packages/ui/components/html-viewer/linkGuard.ts" > "generated/linkGuard.ts"

# Vendor the moved AI context types and the model catalog from core into generated/ai/.
for f in ai-context model-catalog; do
Expand Down
2 changes: 1 addition & 1 deletion docs/agent-guides/guides-and-shared-ui.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/agent-guides/server-and-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ During normal plan review, an Archive sidebar tab provides the same browsing via
| `/api/reference/obsidian/doc` | GET | Read a vault markdown file (`?vaultPath=<path>&path=<file>`). For every reader the file must be inside the vault as written (`403`), a regular file (a FIFO is `403`) that is Markdown by its real path (`403`), and within the 2MB cap (`413`). A reader off this machine must also stay inside the vault after symlink resolution, while a page on this machine may follow a symlink out of the vault, as before: `vaultDocRefusal` |
| `/api/reference/files` | GET | List a folder's annotatable files as a nested tree with git status (`?dirPath=<path>`), the Files sidebar's added folders; `/api/reference/files/stream` watches them (below) |
| `/api/plan/vscode-diff` | POST | Open diff in VS Code (body: baseVersion) |
| `/api/doc` | GET | Serve linked .md/.mdx file (`?path=<path>`). When the hook reports the plan's own file (Claude Code's `planFilePath`, trusted only when its contents equal the plan), `/api/plan` advertises `planDir` and a request with `base=<planDir>` is also served from that directory, but only for paths that are exactly one of the plan's link targets (`[x](target)`, `[[target]]`, HTML `href`, ignoring links inside code; both sides compared with `?query`/`#fragment` dropped, percent-decoding and `./` collapsed, and the file served is the one that normalized target names; `resolvePlanLinkedDoc` in `packages/shared/doc-resolve.ts`) — other files there, such as other plans in `~/.claude/plans/`, stay unreachable. A linked file beside the plan shadows a project document of the same relative name; everything else resolves against the project roots exactly as without a base. Bun plan server only (Pi plans live under the project root). **Who may read what (#2291, both runtimes, plan and annotate servers):** a tab on this machine opens a **document** anywhere, so a document in a folder added under Settings → Files opens, and so does one the current document links outside the project. "Document" is `isAnyPathDocument` (`packages/shared/doc-resolve.ts`): `.md`, `.mdx`, `.html`/`.htm`, `.adoc`/`.asciidoc`, diagram sources and the configured `markdownExtensions`, for the requested name AND its real path. Code files, `.txt` and data/config formats (`.yaml`, `.json`, `.toml`, …) keep the roots for every reader, and for every reader the real file must be of the type its name is served as (`key.md -> ~/.ssh/id_ed25519` is `403` inside the roots too; `isDocServeAllowed`). "This machine" is `isThisMachineReader` (`packages/shared/this-machine-reader.ts`): not remote mode, not a GitHub Codespace (`CODESPACES=true`, whose port forwarder presents `Host: localhost`), `PLANNOTATOR_ALLOWED_HOSTS` unset, a loopback or `*.localhost` Host and `X-Forwarded-Host`, no `Forwarded` / `X-Real-IP` / `tailscale serve` header, and any `X-Forwarded-For` loopback only. Every other reader keeps the roots, symlink check included: `403` outside them. **A forwarder that adds none of those marks looks local:** a raw TCP forwarder (`socat`, an SSH `-L` into a session that is not in remote mode) or a bare nginx `proxy_pass` that sets Host to loopback gives whoever reaches it the documents anywhere on this machine. So does a VS Code dev tunnel, which is not detected. Run a session that others reach in remote mode (`PLANNOTATOR_REMOTE=1`), which keeps the roots. **HTML opened outside the roots** gets a narrow asset root (`isInsideRoots` on the annotate asset registries, `refusesOutsideRootHtmlAsset` in `packages/shared/html-assets-node.ts`). It serves only render types (images, media, CSS, fonts, scripts, nested HTML), never a hidden path, the dotenv family or a data file (`.json`, `.xml`, `.webmanifest`), and `Access-Control-Allow-Origin: *` goes only on fonts. So module scripts and the page's own `fetch()` do not work there, and a built page that puts `crossorigin` on its module scripts or stylesheets (Vite or Astro output) must sit inside the session's folders or be opened with `plannotator annotate`. That root answers only a tab on this machine (`404` for any other reader), and an HTML document served from it gets `connect-src 'none'` (`OUTSIDE_ROOT_HTML_DOCUMENT_CSP`). `/api/share-html` reads with the `/api/doc` gate: the same-origin check, the reader rule above, a regular file by its real path and the 2MB cap. HTML inside the roots, such as the file or folder passed to `plannotator annotate`, keeps its folder's assets as before. Another site's page is refused first (`403 cross_origin`, the writes' `isSameOriginRequest`), here and on the annotate version routes. Per-document drafts (`/api/draft/document`) accept exactly the documents `/api/doc` serves the same reader; the draft index offered on reload, `/api/doc/exists` and Open in App stay on the roots. The 2MB cap applies to every reader |
| `/api/doc` | GET | Serve linked .md/.mdx file (`?path=<path>`). When the hook reports the plan's own file (Claude Code's `planFilePath`, trusted only when its contents equal the plan), `/api/plan` advertises `planDir` and a request with `base=<planDir>` is also served from that directory, but only for paths that are exactly one of the plan's link targets (`[x](target)`, `[[target]]`, HTML `href`, ignoring links inside code; both sides compared with `?query`/`#fragment` dropped, percent-decoding and `./` collapsed, and the file served is the one that normalized target names; `resolvePlanLinkedDoc` in `packages/shared/doc-resolve.ts`) — other files there, such as other plans in `~/.claude/plans/`, stay unreachable. A linked file beside the plan shadows a project document of the same relative name; everything else resolves against the project roots exactly as without a base. Bun plan server only (Pi plans live under the project root). **Who may read what (#2291, both runtimes, plan and annotate servers):** a tab on this machine opens a **document** anywhere, so a document in a folder added under Settings → Files opens, and so does one the current document links outside the project. "Document" is `isAnyPathDocument` (`packages/shared/doc-resolve.ts`): `.md`, `.mdx`, `.html`/`.htm`, `.adoc`/`.asciidoc`, diagram sources and the configured `markdownExtensions`, for the requested name AND its real path. Code files, `.txt` and data/config formats (`.yaml`, `.json`, `.toml`, …) keep the roots for every reader, and for every reader the real file must be of the type its name is served as (`key.md -> ~/.ssh/id_ed25519` is `403` inside the roots too; `isDocServeAllowed`). "This machine" is `isThisMachineReader` (`packages/shared/this-machine-reader.ts`): not remote mode, not a GitHub Codespace (`CODESPACES=true`, whose port forwarder presents `Host: localhost`), `PLANNOTATOR_ALLOWED_HOSTS` unset, a loopback or `*.localhost` Host and `X-Forwarded-Host`, no `Forwarded` / `X-Real-IP` / `tailscale serve` header, and any `X-Forwarded-For` loopback only. Every other reader keeps the roots, symlink check included: `403` outside them. **A forwarder that adds none of those marks looks local:** a raw TCP forwarder (`socat`, an SSH `-L` into a session that is not in remote mode) or a bare nginx `proxy_pass` that sets Host to loopback gives whoever reaches it the documents anywhere on this machine. So does a VS Code dev tunnel, which is not detected. Run a session that others reach in remote mode (`PLANNOTATOR_REMOTE=1`), which keeps the roots. **HTML opened outside the roots** gets a narrow asset root (`isInsideRoots` on the annotate asset registries, `refusesOutsideRootHtmlAsset` in `packages/shared/html-assets-node.ts`). It serves only render types (images, media, CSS, fonts, scripts, nested HTML), never a hidden path, the dotenv family or a data file (`.json`, `.xml`, `.webmanifest`), and `Access-Control-Allow-Origin: *` goes only on fonts. So module scripts and the page's own `fetch()` do not work there, and a built page that puts `crossorigin` on its module scripts or stylesheets (Vite or Astro output) must sit inside the session's folders or be opened with `plannotator annotate`. That root answers only a tab on this machine (`404` for any other reader), and an HTML document served from it gets `connect-src 'none'` (`OUTSIDE_ROOT_HTML_DOCUMENT_CSP`). The same document opened in the viewer's srcdoc frame gets no response header, so `/api/doc` marks it (`rewriteHtml` adds `HTML_NO_NETWORK_MARKER`, `<meta name="plannotator-network" content="none">`, in both runtimes) and `HtmlViewer` puts `<meta http-equiv="Content-Security-Policy" content="connect-src 'none'">` right after its doctype, ahead of every page script (`injectNoNetworkCsp` in `packages/ui/components/html-viewer/srcdoc.ts`). `/api/share-html` reads with the `/api/doc` gate: the same-origin check, the reader rule above, a regular file by its real path and the 2MB cap. HTML inside the roots, such as the file or folder passed to `plannotator annotate`, keeps its folder's assets as before. Another site's page is refused first (`403 cross_origin`, the writes' `isSameOriginRequest`), here and on the annotate version routes. Per-document drafts (`/api/draft/document`) accept exactly the documents `/api/doc` serves the same reader; the draft index offered on reload, `/api/doc/exists` and Open in App stay on the roots. The 2MB cap applies to every reader |
| `/api/doc/exists` | POST | Batch-validate code-file paths (body: `{ paths: string[], base?: string }`) returns `{ results: { [path]: { status: "found"\|"ambiguous"\|"missing"\|"unavailable", … } } }` |
| `/api/draft` | GET/POST/DELETE | Auto-save annotation drafts to survive server crashes. POST and DELETE are unchanged (keyed by the plan's text). GET also carries `documents: [{ path, annotations, globalAttachments }]`, the plan's linked documents' saved comments, when the plan's document index lists any; with only those, it answers `200 { annotations: [], globalAttachments: [], documents, draftGeneration?, ts }` (see "Linked documents in plan review" in `plan-review.md`) |
| `/api/draft/document` | GET/POST | Per-document draft copies of the plan's linked documents, same contract as the annotate server's row below (`/api/plan` advertises `documentDrafts: true`, not in archive mode). Allowed paths: inside the project, or (Bun) a document the plan links beside its own plan file. Requests and the decision carry the page's id (`?client=`); a decision (`/api/approve`, `/api/deny`) clears every copy that page read, wrote or restored (without an id: every copy this server wrote, read or offered), then answers `409` |
Expand Down
7 changes: 3 additions & 4 deletions packages/editor/App.htmlLinkDraft.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
* (DOM-gated): the link waits. The draft stays where it is, a toast says why,
* and the linked document is not requested. With no typed comment the same
* link opens its document. The page's bridge is played by a `link-click`
* message from the page's own frame, as the bridge posts it.
* on the port the viewer hands the frame, as the bridge posts it.
*/
import { afterEach, describe, expect, test } from "bun:test";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { resetStorageBackend, setStorageBackend, type StorageBackend } from "@plannotator/ui/utils/storage";
import { LINK_WAITS_FOR_DRAFT_TITLE, typedCommentDraft } from "./htmlLinkDraftGuard";
import { followLinkInFrame } from "../ui/test-setup/bridgeLinkPort";

const hasDom = typeof document !== "undefined";
const appModule = hasDom ? await import("./App") : null;
Expand Down Expand Up @@ -91,9 +92,7 @@ async function mount(): Promise<HTMLIFrameElement> {
}

async function clickLink(frame: HTMLIFrameElement, href: string): Promise<void> {
await act(async () => {
window.dispatchEvent(new MessageEvent("message", { source: frame.contentWindow, data: { type: "plannotator-bridge-link-click", href } }));
});
await followLinkInFrame(frame, href);
await settle(3);
}

Expand Down
23 changes: 13 additions & 10 deletions packages/inbox/htmlLinks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* Links inside an attached HTML page: the whole window (InboxApp) over a REAL
* Inbox server in a temp data dir (its own process,
* tests/helpers/inbox-dom-server.ts in its `html-links` mode). The page's
* bridge is played by a `link-click` message from the page's own frame, as
* the bridge posts it in Interact. What is proved: a sibling page that is not
* bridge is played by a `link-click` on the port the viewer hands the frame,
* as the bridge posts it in Interact. What is proved: a sibling page that is not
* attached opens read-only over the page with Back, the note and Open in new
* tab, and Back returns; a link to another attachment of the thread opens it
* in the pane as a new history entry; an image in the folder that is not
Expand All @@ -23,12 +23,12 @@ import { request } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { NO_BROWSER } from '../../tests/helpers/no-browser';
import { followLinkInFrame } from '../ui/test-setup/bridgeLinkPort';

const hasDom = typeof document !== 'undefined';
const { InboxApp } = (hasDom ? await import('./App') : {}) as typeof import('./App');

const SERVER_SCRIPT = resolve(import.meta.dir, '../../tests/helpers/inbox-dom-server.ts');
const LINK_CLICK = 'plannotator-bridge-link-click';

type World = { project: string; htmlLinks: { thread: string; ids: Record<string, string> } };

Expand All @@ -44,9 +44,12 @@ let savedEventSource: unknown;
let savedOpen: typeof window.open;
let opened: string[] = [];

function loopback(path: string, method = 'GET', body?: string): Promise<{ status: number; text: string }> {
function loopback(path: string, method = 'GET', body?: string | Uint8Array, encoding?: string | null): Promise<{ status: number; text: string }> {
return new Promise((done, fail) => {
const req = request({ host: '127.0.0.1', port, path, method, headers: { 'Content-Type': 'application/json', Host: `127.0.0.1:${port}` } }, (res) => {
const headers: Record<string, string> = { 'Content-Type': 'application/json', Host: `127.0.0.1:${port}` };
// The window sends a page gzipped (api.ts `post`, `gzip: true`): its bytes and their encoding go through as they are.
if (encoding) headers['Content-Encoding'] = encoding;
const req = request({ host: '127.0.0.1', port, path, method, headers }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => done({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
Expand Down Expand Up @@ -101,7 +104,9 @@ beforeEach(() => {
world = worlds.shift()!;
savedFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const answer = await loopback(String(input), init?.method ?? 'GET', init?.body ? String(init.body) : undefined);
const raw = init?.body;
const body = raw === undefined || raw === null ? undefined : typeof raw === 'string' ? raw : new Uint8Array(await new Response(raw).arrayBuffer());
const answer = await loopback(String(input), init?.method ?? 'GET', body, new Headers(init?.headers).get('content-encoding'));
return new Response(answer.text, { status: answer.status, headers: { 'Content-Type': 'application/json' } });
}) as typeof fetch;
savedEventSource = (globalThis as Record<string, unknown>).EventSource;
Expand Down Expand Up @@ -154,11 +159,9 @@ async function renderSheet() {
return host;
}

/** The page's bridge relaying a link click (in Interact), from the frame it lives in. */
/** The page's bridge relaying a link click (in Interact), on the port the viewer handed it. */
async function clickLink(frame: HTMLIFrameElement, href: string) {
await act(async () => {
window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data: { type: LINK_CLICK, href } }));
});
await followLinkInFrame(frame, href);
}

const sheetFrame = (el: ParentNode) => el.querySelector<HTMLIFrameElement>('.ib-view .ib-htmlframe iframe')!;
Expand Down
7 changes: 7 additions & 0 deletions packages/server/doc-any-path.scenarios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,14 +311,20 @@ export function defineDocAnyPathScenarios(
symlinkSync(join(dir, ".hidden/pic.png"), join(dir, "link-hidden.png"));
}
const server = await open(kind);
/** The no-network marker the viewer turns into connect-src 'none' for its srcdoc frame. */
const noNetwork = /<meta name="plannotator-network" content="none">/;
const rawHtmlOf = new Map<string, string>();
const assetBase = async (dir: string) => {
const doc = await get(server, docUrl(join(dir, "page.html"), dir));
expect(doc.status).toBe(200);
rawHtmlOf.set(dir, String(doc.body?.rawHtml));
const base = /\/api\/html-assets\/[0-9a-f]+\//.exec(String(doc.body?.rawHtml))?.[0];
expect(base).toBeTruthy();
return base!;
};
const outside = await assetBase(added);
// The document the viewer frames as srcdoc is marked: no network there either.
expect(rawHtmlOf.get(added)).toMatch(noNetwork);
// What the page needs to render is served, but only fonts are readable by its scripts.
const pic = await get(server, `${outside}pic.png`);
expect(pic.status).toBe(200);
Expand All @@ -343,6 +349,7 @@ export function defineDocAnyPathScenarios(
expect(forwarded.text).not.toContain("PNG-BYTES");
// An HTML document inside the project keeps its folder's assets, as before.
const inside = await assetBase(project);
expect(rawHtmlOf.get(project)).not.toMatch(noNetwork);
const config = await get(server, `${inside}config.json`);
expect(config.status).toBe(200);
expect(config.headers["access-control-allow-origin"]).toBe("*");
Expand Down
Loading
Loading