8000 feat(deck): Markdown draft editor over workspace drafts folder (#66) by simon-inkie · Pull Request #68 · simon-inkie/inkie-deck · GitHub
[go: up one dir, main page]

Skip to content

feat(deck): Markdown draft editor over workspace drafts folder (#66) - #68

Merged
simon-inkie merged 21 commits into
mainfrom
claude/dazzling-davinci-h66qwp-issue-66
Oct 16, 2026
Merged

simon-inkie merged 21 commits into
mainfrom
claude/dazzling-davinci-h66qwp-issue-66

Conversation

@simon-inkie
@simon-inkie simon-inkie commented Oct 14, 2026 •
Copy link
Copy Markdown
Owner

Closes #66 (first slice only; see Follow-ups).

Known limitations (read first)

  • "Agent" means "changed outside this editor". A person editing the file in another tool also reads as "agent". It is inferred from a content hash, not identity.
  • The conflict check is atomic against other saves through the Deck (shared advisory lock) but not against an external writer landing between the check and the rename. The editor polls every 5 s to narrow this.
  • request.formData() reads the whole request body before the 1 MB content cap is applied, so the cap bounds what is stored, not what is received.
  • Browser writes are accepted only from allowlisted origins: the voice proxy's VOICE_ALLOWED_ORIGINS (default http://localhost:$PORT plus the dev port), checked against the Origin header, not Host, so DNS rebinding is refused. Reaching Deck by another name, or through a proxy that rewrites Host, needs that origin listed (setting it replaces the default). Requests with no Origin or Sec-Fetch-Site (an agent using curl) pass. Draft reads over GET are not origin-protected, like the rest of Deck.
  • If the sidecar .deck-drafts.json is a symlink, is hard-linked, or resolves outside drafts/, it is ignored: every draft reads as "agent" and attribution is not recorded until the file is fixed (drafts still save).
  • A draft file with more than one hard link is treated as not a draft (not listed, 404 on open, 400 on save).
  • Leaving the page with unsaved edits asks for confirmation (in-app navigation and tab close/reload); there is no local recovery draft.
  • In a folder-swap race the waiting save's .lock file (a token only) can be created outside the workspace before the re-check refuses the write; no draft content is written there.
  • Case-insensitive filesystem collisions (Draft.md vs draft.md) were not examined. Reads are synchronous, bounded to 1 MB each.
  • Pre-existing, not changed, separate follow-up: the shared atomicWrite in safe-fs.server.ts (used by the inbox and other stores) has a predictable temp name and follows a planted symlink; the drafts module no longer uses it. withInboxLock also does a blocking synchronous read of its lock file on release.
  • The Drafts link is in the desktop top bar only, not the mobile agent strip.
  • Three early commits carry a commit-message trailer that links a private assistant session, which the repo's leak rule flags; removing it needs a history rewrite, so a maintainer can strip it on squash merge. Later commits omit it.
  • Not exercised in a real browser or running dev server; covered by jsdom and temp-workspace tests only.

TL;DR

A draft is an ordinary <WORKSPACE_ROOT>/drafts/<name>.md file, so an agent reads and writes it with its normal file tools. The Deck gets a Drafts page (plain textarea) to open, create and save drafts. It shows last-saved time (file mtime) and whether the current version was written by the person (via this editor) or the agent (anything else). If the file changes outside the editor while open, a visible alert offers "Load the newer copy" or "Keep mine and overwrite"; a draft removed outside gets its own alert with "Keep mine and recreate". No rich text, multi-cursor, external integrations or new service. Large-paste and attachment behaviour (#65) is untouched.

Design

  • app/lib/drafts.server.ts: list/read/save. Flat *.md names only, confined to the realpath of drafts/ and re-checked inside the lock right before the write; the file a name resolves to must itself be a draft name; symlinked drafts, hard-linked drafts and a drafts/ symlink out of the workspace are refused. Writes go through an O_EXCL temp file with a random suffix, then rename. 1 MB cap (files over it are never read: open answers 413 with a message, the list shows them unread, save refuses). Reads stat first, open non-blocking (a FIFO cannot freeze the server), refuse non-regular files after fstat, and go through one file descriptor capped at the limit plus one byte. CRLF/CR normalised to LF on save.
  • Version = sha256 of content. Save sends the loaded version; mismatch returns 409 with the current copy unless force. The save result is the version that save wrote. Check and write run under the advisory lock; the shared sidecar update takes its own lock. Errors inside the lock return JSON.
  • Authorship: hidden sidecar drafts/.deck-drafts.json holds the hash the Deck last saved; match = person, else agent. The sidecar is read only if it resolves to itself inside drafts/, is not a symlink (O_NOFOLLOW) and has one hard link. A corrupt sidecar is backed up to .deck-drafts.json.bad (written from the confined read, never through a link) and logged before being replaced.
  • Editor: confirms before switching or creating over unsaved edits; a route blocker and a beforeunload guard (only while dirty) cover in-app navigation and tab close; read-only while an open or create is pending; stale save and poll responses are dropped; force-save buttons are disabled during a save.
  • GET/POST /api/drafts (POST refuses non-allowlisted browser origins with 403), /drafts page, DraftEditor, optional WORKSPACE_ROOT (unset hides the feature; a relative value logs a warning and disables it). The dev script defaults it to packages/deck/.workspace/ (gitignored), outside the .runtime/ directory that is wiped on every start (the reseed is in scripts/dev-paths.mjs and a test runs it), and passes VOICE_ALLOWED_ORIGINS to the app so --port N works.
  • Conflict policy: last write wins with a warning, not a lock.

SPEC: .specs/claude-dazzling-davinci-h66qwp-issue-66/SPEC.md. Every review finding and its outcome: .specs/claude-dazzling-davinci-h66qwp-issue-66/REVIEW.md.

Test plan (clean tree, head a050c6d)

  • pnpm typecheck: exit 0
  • pnpm test: base 48 passed; deck 112 files, 2309 passed, 11 skipped (new suites: test/drafts.test.ts, test/draft-editor.test.tsx; the FIFO cases run in a child process with a 20 s timeout and report as skipped where mkfifo is missing)
  • pnpm check:boundaries: no dependency violations
  • pnpm check:leaks: clean (444 files, 33 rules)
  • pnpm check:licence: ok
  • pnpm check:lib-version: no collision
  • pnpm -C packages/deck check:dashes: exit 0

Follow-ups

  • Mobile nav entry; diff against the last person-saved version; async reads; harden the shared atomicWrite.

🤖 Generated with Claude Code

Drafts are plain files under <WORKSPACE_ROOT>/drafts. The Deck page edits and saves them, shows last-saved time and person/agent writer, and warns visibly when the file changes outside the editor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GNgHnmc7XDCrYeFW1SMTDd
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie simon-inkie left a comment
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 40f5943. Scope is right: the first slice from #66 is all here (open/create, edit, save, last-saved time, person/agent writer, visible conflict alert). There is no rich text, no integration and no new service, and #65 is untouched. Confinement, symlink refusal, the 409/force path and the temp-workspace tests are solid. One real bug and a few smaller points.

1. Every browser save writes CRLF line endings, and the editor then shows "unsaved changes" for good (must fix)
DraftEditor.tsx:49-53 sends the body as multipart FormData. The multipart encoding algorithm in the HTML spec rewrites every bare LF in a string value as CRLF. Browsers do this, and so does Node's undici. I checked it against this branch: POSTing content: "a\nb\n" through the real action in api.drafts.tsx leaves "a\r\nb\r\n" on disk and in the returned draft. Two things follow:

  • Agents and git see CRLF files in drafts/, which goes against the repo's LF policy.
  • After a save, setLoaded(body.draft) holds CRLF content but text is still LF, so dirty (DraftEditor.tsx:69) stays true. The status line keeps saying "unsaved changes" and Save stays enabled.

Suggested fix: normalise on the server in saveDraft (drafts.server.ts:224, before the s 8000 ize check and the hash) with content.replace(/\r\n?/g, "\n"), so a CR-only file is converted too. Add a route test that posts multi-line content and asserts LF on disk. The current route test only uses single-line content, and the jsdom test stubs fetch, so neither can see this.

2. Unhandled throw inside the lock (low)
drafts.server.ts:245 calls view() inside withInboxLock. If drafts/x.md is a directory, or the file vanishes between existsSync and statSync, the action throws and you get a framework 500 rather than the JSON error the client expects. Wrapping it in try/catch and returning { ok: false, status: 500 } would fix it.

3. Sidecar read-modify-write is locked per draft, not per sidecar (low)
drafts.server.ts:242/266: the lock is on <draft>.lock, but .deck-drafts.json is shared. Within one process this is safe, because readMeta..writeMeta runs with no await (I ran 80 concurrent cross-draft saves and lost no attributions). Two Deck processes on the same workspace could still drop each other's "person" record. Either note it next to the code or lock the sidecar path.

4. Small things

  • A relative WORKSPACE_ROOT silently disables the feature, because draftsEnabled swallows the error at drafts.server.ts:86. A startup warning would save some head-scratching.
  • request.formData() (api.drafts.tsx:51) buffers the whole body before the 1 MB check. That is acceptable on loopback, but the cap only limits what gets written, not what the server accepts.
  • The SPEC Log says "Commits: see branch". DEVELOPMENT.md asks for the short sha.

On authorship: "agent" meaning anything else is acceptable for this slice, because the UI says "the agent (changed outside this editor)" and the limitation is stated up front in the PR.


Generated by Claude Code

…ck sidecar (#66)

Multipart posts turned LF into CRLF, leaving the editor permanently dirty. Saves now store LF. Failures inside the save lock return JSON errors, the shared sidecar update takes its own lock, and a relative WORKSPACE_ROOT logs a warning. Adds route and editor tests for save, load-newer and keep-mine.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GNgHnmc7XDCrYeFW1SMTDd
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GNgHnmc7XDCrYeFW1SMTDd
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Re-review at b2edbbb. The earlier findings are fixed. LF normalisation runs before the size check and the hash, and on Node 22 undici really does post a\r\nb, so the route test covers the CRLF path. The lock's try/catch passes the 409 through and still releases the lock. The sidecar lock is only ever taken inside a per-draft lock, so the two can't deadlock. A relative WORKSPACE_ROOT now logs a warning. The editor tests cover save, 409, Load newer and Keep mine. CI is green (4/4).

What's left:

  1. Medium: if the draft is deleted outside the editor, saving fails with no message. In saveDraft (drafts.server.ts:270-281), a missing file gives 409 conflict: true with no current. That case has its own test ("flags a conflict when the file was deleted under the editor"). But DraftEditor.save (DraftEditor.tsx:153-155) only calls setRemote when body.current is present, and then clears the error. The person clicks Save and sees no alert and no error. The text stays marked unsaved, and Keep mine can't be reached because the alert never appears. The poll (DraftEditor.tsx:108) ignores the 404, so it doesn't catch this either. Fix: show an alert when conflict && !current (for example "This draft was deleted outside the editor") with a Keep mine button that posts force=1, and add a test for it.
  2. Low: a false conflict alert can appear right after your own save. The poll copies loadedRef.current before it awaits the fetch (DraftEditor.tsx:102). Say a poll starts while a save is in flight and its GET reads the new file after the save's setLoaded has run. It still compares against the old version and calls setRemote with your own save, which the alert labels as written by "you". Re-reading loadedRef.current after the await would fix it.
  3. Low: a save can report 500 even though the file was written. In drafts.server.ts:284-295, a failure after atomicWrite (sidecar lock timeout, or the final view) is caught as "Could not save the draft." (500), but the new content is already on disk. If the person retries with the same baseVersion, they get a 409 against their own text.

Generated by Claude Code

…ve result after write (#66)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Review findings for head a706a99

Two independent reviews of this PR. Please address the Critical and Major items and reply to each Minor with a fix or a one-line reason to defer, then push. Keep the spec in sync with what changes.

Review A

Verdict: MERGE AFTER FIXES. No Critical finding identified; several Major data-loss and confinement defects remain.

Major

  • DraftEditor.tsx:95: Switching or creating drafts silently discards unsaved edits. Both paths call adopt, replacing the textarea without checking dirty. Edit A, then select B or create C: A's changes disappear.

  • DraftEditor.tsx:157: A delayed save can attach the wrong filename to the displayed text. Save A, open B while the POST is pending, then receive A's response. setLoaded(A) leaves B's text untouched; the next Save writes B's content into A. Guard responses against changes of selection.

  • drafts.server.ts:302: The save response can silently authorise overwriting an agent revision. After Deck writes A, it awaits the sidecar lock. An agent writes B during that wait; the response returns B's version, while the textarea retains A. The next ordinary Save overwrites B without a conflict. Return the content/version actually saved and detect subsequent changes separately.

  • drafts.server.ts:284: Confinement expires before writing. Validation precedes an asynchronous lock wait. Replace the validated drafts directory with a symlink to an outside directory during that wait. For a new filename, the failed confined read plus absent lstat permits atomicWrite through the replacement directory, creating the draft outside the workspace. Static symlink tests miss this race.

  • dev.mjs:40: Restarting development deletes default drafts. The new default workspace lives under .runtime, which the launcher recursively removes on every start. Create and save a draft using default development settings, restart: the draft is gone. Persist drafts outside the reseeded directory.

  • api.drafts.tsx:47: Cross-origin writes have no protection. The unauthenticated action accepts form posts and force=1 without checking Origin. A hostile page whose browser can reach Deck can submit a known filename and overwrite it without reading its version. Loopback binding alone is insufficient; browser reachability restrictions vary.

Minor

  • Private provenance in commit text: 40f5943, fb5663b and b2edbbb contain Claude-Session links to a private assistant session. leak-gate.mjs:371 explicitly prohibits this shape. Publishing retains those identifiers even though file content passes the gate.

  • draft-editor.test.tsx:192: The polling regression test covers only a favourable ordering. Its delayed GET returns the post-save version. A GET that captured the old version before saving, but arrives afterwards, still raises a false conflict. Add that ordering; current tests also omit switching during save.

  • drafts.server.ts:173: Reads are unbounded and synchronous. Listing reads every draft fully. An agent-created oversized Markdown file can stall Deck or exhaust memory despite the save cap.

Checked/limits: Read the SPEC, editor/server/API/tests, supporting code and commit bodies. The content gate passed for 441 tracked regular files excluding environment/credential files; no commercial plans found in inspected material. Local main...HEAD spans 339 files with unrelated earlier work, which I did not fully audit. No browser, tests, real run, network, database or cross-platform execution. No files changed.

Review B

Verdict: MERGE

Summary

PR 68 introduces a workspace draft editor and JSON API (/api/drafts) for editing Markdown files in <workspace>/drafts. Confinement, advisory locking, content-hash conflict detection, and path validation are properly implemented.

Findings

Critical

None.

Major

None.

Minor

  1. packages/deck/app/lib/drafts.server.ts:109-114 — Silent reset of sidecar metadata on parse error

    • Failure scenario: If .deck-drafts.json is corrupted or partially written, readMeta() catches the JSON parse error and returns an empty object {}. The next call to saveDraft() will write { version: 1, files: { [name]: version } }, discarding writer attribution for all other drafts. All existing drafts will subsequently report writer: "agent".
    • Recommendation: If the sidecar file exists but fails to parse, preserve a backup or log an error before overwriting.
  2. packages/deck/app/components/DraftEditor.tsx:117-118 — Polling does not reset gone if recreated with identical content

    • Failure scenario: If an open draft file is deleted, polling detects 404 and sets gone = true. If the file is immediately restored with identical content, polling receives 200 with body.draft.version === now.version, which skips setRemote and leaves gone = true displayed until the user reloads or saves.

Confinement & Safety Checks

  • Path traversal: normaliseDraftName enforces ^[A-Za-z0-9][A-Za-z0-9._-]*\.md$ and rejects ... confineToRootReal checks resolved paths against the drafts directory realpath. Live silo roots are blocked.
  • Symlinks: Symlinked draft files are explicitly rejected on write via lstatSync(...).isSymbolicLink().
  • Races & Data Loss: Advisory locking (withInboxLock) is taken per draft file and sidecar. Conflict detection compares sha256 hashes (baseVersion !== currentVersion) and returns HTTP 409 with the current copy on disk.
  • Leakage: No private keys, customer data, or internal URLs found.
  • Test Honesty: Vitest suites (drafts.test.ts, draft-editor.test.tsx) test concurrent saves, stale saves, traversal attempts, symlink rejections, and CRLF normalization.

What Was Not Checked

  • Playwright end-to-end browser execution.
  • Non-standard Windows/macOS case-insensitive filesystem collision behaviour (e.g. Draft.md vs draft.md).

Related Brain Files

  • [[../../brain/projects/oss-pr-reviews-2026-10-14/pr-68-comment]] (1.00) — pr-68-comment
  • [[../../brain/projects/oss-pr-reviews-2026-10-14/pr-68-sol]] (0.95) — pr-68-sol
  • [[../../brain/projects/oss-pr-reviews-2026-10-14/pr-68-aggy]] (0.93) — PR 68 Review: Markdown Draft Editor (Basic text editor inside the Deck for drafting with agents #66)
  • [[../../brain/projects/deck-brain-plan-2026-10-12/10-phase1-reviews-opus]] (0.78) — Task 1 round 2 (Opus, 12 Oct 19:32 BST), reviewed Deck ab340d9..f4a9f09
  • [[../../brain/projects/deck-brain-plan-2026-10-12/opus-cloud-review-packets-2026-10-14/deck-README]] (0.76) — Deck review packet

@simon-inkie
Copy link
Copy Markdown
Owner Author

Automated review (CodeRabbit CLI, run against this branch) found one issue, which agrees with the data-loss concern above:

Major, packages/deck/app/components/DraftEditor.tsx:186: switching drafts discards unsaved edits. The select's onChange calls open() without checking dirty; open() then calls adopt(), which replaces the text. Picking another draft while edits are unsaved loses them silently. create() has the same problem. Suggested fix: confirm before switching when dirty is true.

-             => e.target.value && void open(e.target.value)}
+             => {
+              const next = e.target.value;
+              if (!next) return;
+              if (dirty && !window.confirm("Discard unsaved changes?")) return;
+              void open(next);
+            }}

…oss-origin writes (#66)

Confirm before switching or creating over unsaved edits; drop save and poll responses that no longer match the editor; return the version a save wrote; re-check confinement inside the lock; refuse cross-origin browser writes; never read files over the cap; keep a copy of a corrupt sidecar; move the dev workspace out of .runtime.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
…ate (#66)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Addressed in ddd1b7b (pushed to this branch; no history rewrite). Replies per finding, with the review items and the CodeRabbit comment together.

Major (Review A and CodeRabbit)

  • Switching or creating discards unsaved edits (also the CodeRabbit major): fixed. Both paths confirm via window.confirm when dirty; declining keeps the text, and creating asks before the POST so nothing is created on decline. Tests cover decline, accept, no prompt when clean, and create.
  • Delayed save attaches to the wrong filename: fixed. A save response is dropped if the editor text was replaced meanwhile (switch, create, load newer copy); the list is refreshed instead. An older open/create response is also dropped. Test: save A held open, switch to B, release; B keeps its text and base version, and the next save posts B against B's version. Reverting the guard makes that test fail.
  • Save response authorising an overwrite of an agent revision: fixed. The server returns the version this save wrote (content, hash, mtime taken right after the write), never a re-read. Test: an agent writes during the sidecar wait; the next save from the returned version conflicts and the agent's file is untouched.
  • Confinement expiring before the write: fixed. Confinement and the symlink check are re-run inside the lock immediately before the write and again before the sidecar write. Test: the drafts/ folder is swapped for an outside symlink while the save is queued; nothing is created outside. Disabling the re-check makes the test fail.
  • Dev restart deletes drafts: fixed. The default dev workspace is now packages/deck/.workspace/ (gitignored), outside the reseeded .runtime/.
  • Cross-origin writes: fixed. POSTs are refused with 403 when Sec-Fetch-Site is not same-origin/none or the Origin host differs from Host. Header-less requests (an agent using curl) pass. Limitation: behind a proxy that rewrites Host, same-origin saves would be refused. Route tests cover it.

Minor

  • Claude-Session trailers in earlier commits: deferred. Removing them needs a history rewrite, which I was told not to do. The new commits omit the trailer. A maintainer can drop them on squash merge. pnpm check:leaks:messages already reports findings in other older commits on main as well.
  • Polling test only covered one ordering: fixed. Added the case where the GET read the old file but arrives after the save. The poll now discards any answer whose request overlapped an adopt or a save (generation counter).
  • Unbounded synchronous reads: partly fixed. Existing files over 1 MB are never read (read answers 413, listing shows them without reading, save refuses). Reads stay synchronous but are bounded to 1 MB each; an async rewrite is deferred.
  • (Review B) Corrupt sidecar silently reset: fixed. It is copied to .deck-drafts.json.bad and logged before being replaced; test added. Other read errors abort the sidecar write.
  • (Review B) gone alert persists if the file reappears with the same content: fixed. A 200 poll clears it, and a matching version clears a stale conflict alert. Test added.
  • (Review B, not checked) case-insensitive filesystem collisions (Draft.md vs draft.md): deferred, not examined in this slice.

SPEC log updated. Checks on the clean tree at ddd1b7b: pnpm typecheck exit 0; pnpm test base 48 passed, deck 112 files 2281 passed 11 skipped; pnpm check:boundaries no violations; pnpm check:leaks clean (442 files, 33 rules); pnpm check:licence ok; pnpm check:lib-version no collision; pnpm -C packages/deck check:dashes exit 0.


Generated by Claude Code

@simon-inkie
Copy link
Copy Markdown
Owner Author

Review at head ddd1b7b

Verdict: approve, with minor follow-ups. I found no Critical or Major issues. Every fix listed in the reply comment is in the code, and the tests exercise the races they claim to cover.

What I checked and found correct:

  • Editor races. In DraftEditor.tsx, the adoptRef check (193) runs before every branch of the save handler, including the 409 branches. That means a save response is dropped whenever open, create or Load newer has replaced the text in the meantime. Text typed during a save is safe because loaded.content becomes the text that was posted, so the editor stays dirty. The poll captures genRef before its GET and re-reads loadedRef after it. Adopt, save start and save finish each bump genRef, so a GET that overlaps any of them is discarded. I found no practical window left.
  • Save result. drafts.server.ts:343-369 returns the hash of the content this save wrote, not a re-read. Nothing after atomicWrite can turn the result into a 500.
  • Confinement after the lock wait. Lines 335-341 re-run the realpath and symlink checks inside the lock, synchronously, right before atomicWrite. The sidecar path is re-checked at 361. What remains is the kernel-level gap between lstat and rename, which would need O_NOFOLLOW/openat to close. That is acceptable.
  • Lock and errors. The lock is released in finally, and errors thrown inside it come back as JSON 500. Line endings: CRLF/CR become LF before the size check and the hash, so this is not a regression.
  • The "neither header" exemption. It is acceptable. Current browsers always send Origin on a cross-origin POST. When a referrer policy strips it, the browser sends null, and new URL("null") throws, so the request is refused. Only very old browsers (Firefox before 70) send neither header.
  • Scope. The diff is 13 files, all for Basic text editor inside the Deck for drafting with agents #66. The Composer: turn a large paste into an attached markdown document #65 large-paste and attachment code is untouched.
  • Commits. The new commits (e55184b through ddd1b7b) carry no Claude-Session trailer, and all are signed off. The trailer on 40f5943, fb5663b and b2edbbb is still pending the maintainer's decision.

Findings

  1. [Minor] packages/deck/app/routes/api.drafts.tsx:56-70 - DNS rebinding bypasses the cross-origin check.
    • Problem: The check compares Origin with Host, and both come from the request. A hostile domain that rebinds to 127.0.0.1 makes Origin host equal Host, and Sec-Fetch-Site reads same-origin, so the POST, including force=1, passes. Vite's allowedHosts protects only dev. The production server (react-router-serve via start-production.mjs) does not validate Host. The same comparison also refuses every save behind a proxy that rewrites Host (nginx's default proxy_set_header Host $proxy_host).
    • Fix: Compare Origin, or Host, against an allowlist of expected origins: localhost:$PORT, 127.0.0.1:$PORT, plus a configured front hostname. voice-relay.mjs already does this with ALLOWED_ORIGINS. That one change closes rebinding and fixes the proxy case. If it is deferred, record it as a known limitation in the SPEC and the PR body. (Draft reads over GET are exposed to rebinding too, as are the rest of Deck's routes; that predates this PR.)
  2. [Minor] packages/deck/app/components/DraftEditor.tsx:110-118 (and create, 153-168) - edits typed while an open or create request is in flight are lost without a prompt.
    • Problem: confirmDiscard() runs when the person clicks, before the await. Text typed while the GET or POST is pending is then replaced by adopt() without asking.
    • Fix: After the await, compare text with what was on screen when the person confirmed, and ask again if it changed. Alternatively, make the textarea read-only while an open is pending.
  3. [Minor] packages/deck/app/components/DraftEditor.tsx:119 - opening a draft over 1 MB shows no reason.
    • Problem: The list shows drafts over the cap. Opening one returns 413 with "larger than 1 MB; edit it outside the Deck", but the editor always shows "Could not open that draft.".
    • Fix: setError(body.error ?? "Could not open that draft."). Type body with error?: string and add a test.
  4. [Nit] packages/deck/app/lib/drafts.server.ts:204-207 - the size cap can be bypassed between stat and read.
    • Problem: The cap is checked with statSync, then the file is read in full with readFileSync. A file that grows between the two calls is read whole. The sidecar read in readMeta (line 145) has no bound at all.
    • Fix: Open a file descriptor, fstat it, and read at most MAX_DRAFT_BYTES + 1 bytes. Bound the sidecar read the same way.
  5. [Nit] packages/deck/app/lib/drafts.server.ts:177 - the backup copy follows a symlink at its destination.
    • Problem: copyFileSync(file, file + ".bad") follows a symlink at the destination. A planted .deck-drafts.json.bad symlink sends the copy outside the workspace.
    • Fix: Unlink the .bad path first, or lstat it and refuse a symlink, and copy with COPYFILE_EXCL. This has low impact because an agent can already write to the workspace.
  6. [Nit] drafts.server.ts:299 with safe-fs.server.ts withInboxLock - in the folder-swap race, the waiter's lock file is created in the outside directory.
    • Problem: The confinement re-check runs only after the lock is taken, so the .lock file lands outside. The test at packages/deck/test/drafts.test.ts:388 filters out .lock files to tolerate this. The file holds only a token and is removed on release.
    • Fix: Add a comment, or check draftsDirReal(false) === dirReal before taking the lock.
  7. [Nit] packages/deck/app/components/DraftEditor.tsx:280,302 - the force-save buttons stay enabled during a save.
    • Problem: "Keep mine and overwrite" and "Keep mine and recreate" are not disabled while a save is in flight, so a double click sends two force saves. The second is harmless.
    • Fix: Add disabled={saving}.
  8. [Nit] packages/deck/test/drafts.test.ts:337 - two refusal cases have no test.
    • Problem: Nothing tests Origin: null (refused only because new URL("null") throws) or a matching Origin combined with Sec-Fetch-Site: cross-site.
    • Fix: Add both cases so a later refactor cannot loosen the check without a test failing.
  9. [Nit] PR description - it is out of date.
    • Problem: It still says the dev script sets .runtime/workspace and that the test plan ran at head b2edbbb. It does not mention the 403 cross-origin rule, the Host or proxy limitation, or the 413 handling of oversized files.
    • Fix: Regenerate it from the SPEC's TL;DR and Test plan.

CI status on ddd1b7b

4 of 4 check runs completed, all success: guards, licence, test (22.x), test (24.x).

Unverified

  • I did not run the tests locally because no node_modules was installed. I am relying on CI and on reading the tests.
  • Nothing was run in a real browser. The DNS-rebinding bypass and the proxy behaviour come from reading the code and were not reproduced.
  • Case-insensitive filename collisions and async reads were deferred by the builder and are not examined here.

Generated by Claude Code

…ng, capped fd reads (#66)

Check Origin against the shared VOICE_ALLOWED_ORIGINS allowlist instead of Host, so DNS rebinding is refused and allowlisted proxies work. Make the editor read-only while an open or create is pendi
8BD0
ng, show the server's message when opening fails, disable force-save buttons during a save, read drafts and the sidecar through a capped file descriptor, and never follow a symlink at the sidecar backup path.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Review at head 44b8686

Verdict: approve, with minor follow-ups. I found no Critical or Major issues. All nine round-4 items are in the code as claimed. Two new Minor items are worth fixing before merge: a regression in readCapped where a FIFO blocks the server, and drafts returning 403 under pnpm dev --port N. Both are small changes.

What I verified against the code:

  1. Origin allowlist (api.drafts.tsx:66-72). The route imports resolveAllowedOrigins from server/voice-relay.mjs, which is the same function and the same VOICE_ALLOWED_ORIGINS variable the voice proxy uses. That module has no imports, so it is safe to pull into the app bundle. Host is no longer read. A Sec-Fetch-Site other than same-origin/none gets a 403. An Origin that is not listed, including "null", gets a 403 through includes(), so the check no longer depends on new URL throwing. A request with neither header passes.
    • DNS rebinding. The check is sound against it. A rebinding page sends its own Origin (http://evil:4242), and Sec-Fetch-Site: same-origin does not save it, because the Origin check runs regardless.
    • Requests with no Origin. Current browsers always send Origin on a POST.
    • Env-var reuse. Setting VOICE_ALLOWED_ORIGINS replaces the default, and a test covers this. A blank value falls back to the default.
    • Misconfiguration. It fails closed: a 403 with a message that names the variable. Matching is exact strings with no wildcards, and trailing slashes are stripped.
    • Production. start-production.mjs passes PORT and the loaded .env to the app, so the app and the proxy agree.
  2. Read-only during open/create. The textarea is read-only while an open or create is pending (readOnly={switching}). switching is set before the await and cleared in finally, only by the latest request (seq guard). Test added.
  3. 413 message. setError(body.error ?? ...) shows the server's message. Test added.
  4. Capped reads (readCapped, drafts.server.ts:149-167).
    • Partial reads. The loop handles them: readSync runs until it returns 0 or the count passes max, and the buffer is max+1 bytes, so the remaining length is never 0 before the throw.
    • fd leaks. The fd is closed in finally on every path. openSync throwing leaves nothing open.
    • Draft and sidecar paths. Both the draft read and the sidecar read go through this function.
  5. .bad backup. rmSync(force) unlinks a link at the backup path, not its target. The copy then uses COPYFILE_EXCL. I checked locally that COPYFILE_EXCL onto a dangling symlink gives EEXIST on Linux, so a link planted between the two calls still cannot be followed. If a directory sits at .bad, rmSync throws, the outer catch logs it, and the save still succeeds. The test plants a symlink to an outside file and checks that the file is unchanged.
  6. Force-save buttons. Both have disabled={saving}. The test checks that exactly one force=1 POST is sent.
  7. Refusal tests. They call the real action with real Request headers (undici does not strip origin or sec-fetch-site). Each assertion would fail if the check were removed. The tests cover null, an allowlisted Origin with cross-site, rebinding (Origin matching Host, same-origin), and the proxy allowlist replacing the default.
  8. REVIEW.md. It matches the PR thread for rounds 2 to 4, including the severities, outcomes and shas. The round-3 to round-4 superseding of the Host check is recorded.
  9. PR description. It is current: the head, the 2288-test count (2281 + 7 new, consistent), .workspace/, the allowlist and replace-default behaviour, the 413 handling and the .lock limitation are all there.

Regressions. I diffed ddd1b7b..44b8686. Confirm-before-switch, the adoptRef drop of late save responses, the openSeqRef drop of older open/create responses, and the poll's genRef/savingRef guard are unchanged.

Scope. The diff is 14 files, all for #66: SPEC/REVIEW, drafts server/route/page/editor, nav link, routes, dev script, .env.example, .gitignore, and tests. No #65 paste or attachment code is touched.

Findings

  1. [Minor] packages/deck/app/lib/drafts.server.ts:150 - a FIFO at a draft path hangs the whole Deck. This is a regression from d30e9d4.
    • Problem: fs.openSync(file, "r") blocks on a named pipe until a writer appears, and it does so synchronously on the server's event loop. The old view() called statSync and refused anything that was not a regular file before reading. Now open comes before fstat. A x.md FIFO, or a symlink to one inside drafts/, therefore freezes the server on the next list, open or poll; listDrafts admits symlinks. A FIFO at .deck-drafts.json does the same through readMeta. That second case was already true before this PR's last commit. I reproduced the block locally: openSync on a FIFO hangs until killed.
    • Fix: Open with fs.constants.O_RDONLY | fs.constants.O_NONBLOCK. On a FIFO that open returns at once, and the existing !st.isFile() check then refuses it. On regular files it behaves as before (checked locally). Add a test that does mkfifo (skip it on Windows).
  2. [Minor] packages/deck/scripts/dev.mjs:158 - drafts are refused with 403 when dev runs on a non-default port.
    • Problem: dev.mjs gives VOICE_ALLOWED_ORIGINS=http://localhost:${appPort} only to the proxy (proxyEnv, line 132). The app gets env, which has neither that variable nor PORT. In the app process, resolveAllowedOrigins therefore returns localhost:4242 and localhost:5174. With pnpm dev --port 5180, voice works but every draft create and save gets a 403. The failure is fail-closed and the message names the variable, but it contradicts "default http://localhost:$PORT" in the SPEC and PR.
    • Fix: Build appEnv from { ...env, VOICE_ALLOWED_ORIGINS: proxyEnv.VOICE_ALLOWED_ORIGINS } (or set PORT: appPort), so the two processes share one allowlist.
  3. [Nit] packages/deck/.env.example:186-190 - the WORKSPACE_ROOT block does not say that saves need the origin listed.
    • Problem: Someone who reaches Deck over a tailnet but has no voice set up would not think to set a VOICE_* variable for drafts. They will meet the 403 first.
    • Fix: Add one line, for example "Browser saves are accepted only from origins in VOICE_ALLOWED_ORIGINS (default http://localhost:$PORT)", with a matching sentence in INSTALL.md if drafts get a section there.
  4. [Nit] packages/deck/test/drafts.test.ts:347,352,390 - the tests assume PORT is unset.
    • Problem: The default-allowlist assertions hard-code localhost:4242. They clear VOICE_ALLOWED_ORIGINS but not PORT, so a developer with PORT exported gets a spurious failure.
    • Fix: Save, delete and restore PORT in the same try/finally.
  5. [Nit] packages/deck/app/lib/drafts.server.ts:155 - every read zero-fills a fresh 1 MB buffer.
    • Problem: Buffer.alloc(max + 1) runs on every read. listDrafts reads every draft, so each list after a save, and each 5 s poll, allocates and zero-fills about 1 MB per draft.
    • Fix: Use Buffer.allocUnsafe(max + 1) (only subarray(0, n) is ever exposed), or size the buffer to Math.min(st.size, max) + 1 and grow it only if the read fills it.
  6. [Nit] PR body footer - it carries the same claude.ai/code/session_... link that the leak rule flags in commit trailers.
    • Problem: Harmless while it stays in the PR body. But if the squash-merge commit message is taken from the PR description, the link lands on main.
    • Fix: Strip it, together with the three known trailers, when composing the squash message.

Commits

There are no new Claude-Session trailers. Only 40f5943, fb5663b and b2edbbb carry one, as already known. All 11 commits are signed off.

CI status on 44b8686

4 of 4 check runs completed, all success: guards, licence, test (22.x), test (24.x). The two test jobs were still in progress when I first checked and finished at 10:14 UTC. Mergeable state: clean.

Unverified

  • I did not run the suite locally because there is no node_modules. I am relying on CI and on reading the tests. The FIFO hang, O_NONBLOCK and COPYFILE_EXCL behaviour were checked with plain Node 22 on Linux only. COPYFILE_EXCL symlink handling on macOS (libuv copyfile) was not checked.
  • Nothing was run in a real browser or dev server. The DNS-rebinding refusal, the proxy case and the dev-port 403 come from reading the code.
  • I could not see a round-1 review comment on the PR, so the round-1 rows of REVIEW.md were checked only against the round-2 comment, which confirms those fixes.
  • Case-insensitive name collisions and async reads remain deferred.

Generated by Claude Code

…nv isolation (#66)

Open drafts and the sidecar with O_NONBLOCK so a FIFO cannot freeze the server, refuse non-regular files, stop zero-filling a 1 MB buffer per read, pass VOICE_ALLOWED_ORIGINS to the dev app so --port works, document the requirement, and pin PORT and VOICE_ALLOWED_ORIGINS in the draft tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Review at head fd9bb56

Verdict: approve. I found no Critical or Major issues. All six round-5 items are in the code and do what they claim. I checked them by running the code, not only by reading it: the draft suites, extra probes against special files, and the real dev launcher on a non-default port. What remains is one Minor item about test quality and a few Nits. None of them blocks merge.

What I verified:

  1. Non-blocking reads (drafts.server.ts:149-174). readCapped opens the file with O_RDONLY | O_NONBLOCK, calls fstat, and refuses anything that is not a regular file before reading. Both the draft path and the sidecar path go through it.
    • Closing the fd. The fd is closed in finally on every path. If openSync itself throws, nothing was opened.
    • Regular files. O_NONBLOCK has no effect on regular files, so the read loop cannot get EAGAIN.
    • Race between check and open. There is no separate check left. The type check is fstat on the fd that was opened, so a draft swapped for a FIFO between the two steps is still refused.
    • Probe results. I ran throwaway probe tests on Linux, Node 22, and deleted them afterwards. None of these cases hung, and all were refused:
      • a FIFO draft
      • a symlink to a FIFO inside drafts/
      • a force-save over a FIFO (400, and the FIFO is left in place)
      • a directory named x.md
      • a Unix socket named x.md, and a symlink to that socket (open gives ENXIO)
      • a FIFO at .deck-drafts.json, where list, read and force-save still succeed and the sidecar failure is only logged
    • No fd leak. The open fd count was unchanged after 200 rounds of list, read, 413, FIFO, directory and missing-file reads, plus a save.
    • Running server. Against a running dev server, a FIFO draft and a symlink to it return 404, the list still returns, and a force-save returns 400.
    • Without the fix. With the flag reverted, the new tests hang. See finding 1.
  2. dev.mjs. appEnv now gets VOICE_ALLOWED_ORIGINS: proxyEnv.VOICE_ALLOWED_ORIGINS (lines 161-164). I ran node scripts/dev.mjs --port 5180 with PORT and VOICE_ALLOWED_ORIGINS unset. The launcher logged VOICE_ALLOWED_ORIGINS=http://localhost:5180. I then sent POST /api/drafts with three different Origins:
    • http://localhost:5180: the draft was created, returning 200 with writer person.
    • http://localhost:4242: 403.
    • http://evil.example: 403.
      The fix works on the real launcher, not only in the source-level test. Without --port, the dev allowlist is now just http://localhost:4242. That matches the port the app serves on.
  3. .env.example. The note is present and accurate.
  4. Test env isolation. beforeEach saves and deletes PORT and VOICE_ALLOWED_ORIGINS, and afterEach restores or deletes them. The older per-test saves inside the file are now redundant but harmless. I ran both suites with PORT=9999 VOICE_ALLOWED_ORIGINS=http://x.example exported, and all 64 passed.
  5. Buffer.allocUnsafe. Only buf.subarray(0, n) is ever decoded, where n is the sum of the readSync return values. Any uninitialised tail is never read, so it cannot reach a response, a hash or a file. A 1 MB multibyte file at exactly the cap, a 3-byte file and an empty file all read back exactly.
  6. PR body and REVIEW.md. The session link is gone from the PR body; the body only mentions the old trailers in prose. REVIEW.md round 5 matches the round-5 comment in content, severities and sha, with two wording issues covered in finding 4.

Regressions. git diff 44b8686..fd9bb56 touches only drafts.server.ts (readCapped), dev.mjs, .env.example, drafts.test.ts and the SPEC and REVIEW files. DraftEditor.tsx and api.drafts.tsx are unchanged, so these remain exactly as verified in round 5: confirm-before-switch, the adoptRef drop of late save responses, the openSeqRef drop of older opens, the poll genRef/savingRef guard, and the origin allowlist.

Scope. 14 files, all for #66. The nav and route changes add only the Drafts link and routes. No #65 paste or attachment code is touched.

Commits. There are no new Claude-Session trailers; only the known 40f5943, fb5663b and b2edbbb carry one. All 13 commits are signed off. No em-dashes or en-dashes were added.

Findings

  1. [Minor] packages/deck/test/drafts.test.ts:507-537 - the FIFO tests hang instead of failing, and pass instead of skipping.
    • Problem, without the fix: I put back "r" and ran vitest -t FIFO. The run sat silent until my 45 s timeout killed it, with no failure and no output. Vitest's testTimeout cannot interrupt a synchronous openSync that blocks the event loop. The workflows set no timeout-minutes, so in CI a regression would hang the job until GitHub's 6-hour cap rather than fail.
    • Problem, where mkfifo is missing: the test runs return, so it is reported as passed, not skipped.
    • Fix: Run the read in a child process with a deadline, for example spawnSync(process.execPath, [...], { timeout: 5000 }), and assert that it exited cleanly. Alternatively, add timeout-minutes to the CI test jobs. Detect mkfifo once and use it.skipIf(!hasMkfifo), so the test shows as skipped.
  2. [Nit] packages/deck/test/drafts.test.ts:517 - the symlink case never reaches the non-blocking open.
    • Problem: linked.md points to a FIFO outside the workspace. Confinement (confineToRootReal) refuses it before readCapped runs, so a symlink to a FIFO is not tested through O_NONBLOCK. listDrafts admits symlinks, and a link to a FIFO inside drafts/ does reach the open. I checked that case locally and it is handled; it just has no test.
    • Fix: Point the link at a FIFO inside the folder, for example drafts/target.fifo.
  3. [Nit] packages/deck/app/lib/drafts.server.ts:155 - the file is opened before its type is known.
    • Problem: A device node whose open has side effects (a tape rewind, or taking a tty) would still be opened before fstat refuses it. This is reachable only if someone with root runs mknod inside drafts/, so the impact is very low.
    • Fix (optional): Run statSync first and refuse anything that is not a regular file. Keep the fstat check as the authoritative one.
  4. [Nit] .specs/claude-dazzling-davinci-h66qwp-issue-66/REVIEW.md:80 - round 5 row 1 overstates the tests.
    • Problem: It says the mkfifo tests are "skipped where unavailable" and cover "symlink-to-FIFO". In fact they pass silently where mkfifo is missing (finding 1), and the symlink case is refused by confinement (finding 2).
    • Fix: Reword the row, or update it together with the fixes for findings 1 and 2.

Out of scope, not a finding for this PR: safe-fs.server.ts:583 (withInboxLock release) still calls readFileSync(lockPath) with a blocking open. If the .lock file were swapped for a FIFO while the lock is held, the release would block. This is a pre-existing shared helper. A planted FIFO lock that exists before the lock is taken is already handled, because the stale-steal path only calls stat and rename on it.

CI status on fd9bb56

4 of 4 check runs completed, all success:

  • guards (10:23:12 UTC)
  • licence (10:23:04 UTC)
  • test (22.x) (10:25:30 UTC)
  • test (24.x) (10:25:28 UTC)

Unverified

  • All local runs used Node 22 on Linux. Locally, the two draft suites pass at 64 of 64. I did not run the full deck suite or typecheck locally; I am relying on CI for those. macOS behaviour of O_NONBLOCK and COPYFILE_EXCL was not checked.
  • I did not test in a real browser. The dev-port check used curl with explicit Origin and Sec-Fetch-Site headers. The voice proxy could not bind its port in my sandbox, which does not affect the app's allowlist.
  • I did not physically create a device node, because that needs root. Finding 3 comes from reading the code.
  • Case-insensitive name collisions and async reads remain deferred, as recorded in the SPEC.

Generated by Claude Code

A blocked synchronous open cannot be interrupted by the test timeout, so the FIFO cases now spawn the real module in a child with a 20 s limit and fail cleanly on regression. Skipped, not passed, where mkfifo is missing. The symlink case targets a FIFO inside drafts/. Stat the path before opening as a mitigation; fstat stays authoritative.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Review at head 86ae24b

Verdict: approve. I found no Critical, Major or Minor issues. The round-5 Minor is fixed: the FIFO tests now fail, rather than hang, when the fix is removed. I confirmed that by reverting the fix and running them. What remains is four Nits, and none of them blocks merge.

What I verified, by running the code on Linux with Node 22 in a throwaway worktree:

  1. FIFO tests in a child process (drafts.test.ts:505-557).
    • How they run. The tests start the real drafts.server.ts with node --import tsx under spawnSync with a 20 s timeout, and both use it.skipIf(!hasMkfifo).
    • At head. Both pass in about 330 ms each, and the two draft suites pass 64 of 64.
    • Mutation A: O_NONBLOCK removed, stat pre-check kept. Both tests still pass, because the pre-check now stops a FIFO first. The author already says so (see finding 1).
    • Mutation C: both the pre-check and O_NONBLOCK removed. Both tests fail at about 20.05 s with expected true to be false, and the run ends in 41 s instead of hanging.
    • Cleanup on timeout. spawnSync kills the blocked child with SIGTERM. That child is the only process: tsx loads in-process, so there are no grandchildren. Afterwards there was no leftover child.mjs/tsx process, the /tmp entry count was unchanged, and no new FIFO was left behind. The runInChild temp dir is removed in finally, and ws (with its FIFOs) is removed by the existing teardown.
    • tsx in CI. tsx is a devDependency of packages/deck, and the child's cwd is packages/deck, so --import tsx resolves after pnpm install --frozen-lockfile. CI confirms it ran on both lines: test (22.x) and test (24.x) each report 2291 passed and 11 skipped. 11 skipped is the same count as before the FIFO tests existed, so the FIFO tests were run there, not skipped.
    • Cost. About 0.7 s added locally. The CI test step takes about 60 to 70 s, as before.
    • hasMkfifo. It treats only ENOENT as missing, so a BSD mkfifo that rejects --help (non-zero exit, but no spawn error) still counts as present. That is correct.
  2. Symlink case. linked.md points to drafts/target.fifo, which is inside the confined folder, so the case now reaches readCapped rather than being refused by confinement. The expected names: [] also shows that the list skips both the FIFO and the link to it.
  3. statSync pre-check (drafts.server.ts:158).
    • No new race. If the path is a FIFO or device when stat runs, the file is never opened. If it is swapped after the stat, the O_NONBLOCK open plus the fstat check still refuse it, so the stat only adds a layer.
    • Symlinks. statSync follows them exactly as openSync did, and confinement and the save-side lstat checks are unchanged.
    • Error mapping. ENOENT is still ENOENT, so a missing sidecar still reads as {}. A non-regular file still throws Not a regular file., which maps to 404 on read and to a refusal on save. A socket used to fail with ENXIO and now fails at the stat, but it maps to the same 404. An unreadable file passes the stat, and the open still fails with EACCES.
    • The untested O_NONBLOCK-only path. I find this acceptable: the fstat check is the authoritative one, and the stat is defence in depth. I also checked that path directly. In a child process I patched fs.statSync to report pipe.md as a regular file, then called readDraft and saveDraft on it. Both returned ok: false at once and nothing hung. It is cheap to turn this into a test (finding 1).
  4. Docs. Round 5 row 1 in REVIEW.md is reworded accurately. The round 6 table matches the round-5 comment's findings, severities and outcomes. The SPEC has the sixth-round log entry and records the pre-existing withInboxLock limitation. The PR body states the same limitation, has the head 86ae24b, and gives the same 2291/11 counts.
  5. Checks run locally. typecheck exit 0, check:dashes exit 0, and leak-gate clean (443 files, 33 rules). No em-dashes or en-dashes were added.
  6. Scope and commits. The PR still has 14 files, all for Basic text editor inside the Deck for drafting with agents #66, and the Composer: turn a large paste into an attached markdown document #65 paste and attachment code is untouched. Round 6 changed only drafts.server.ts (+4 lines), drafts.test.ts, SPEC.md and REVIEW.md. The new commits a5f6659, 151be2e and 86ae24b carry no Claude-Session trailer, and all are signed off. Only the known 40f5943, fb5663b and b2edbbb carry the trailer.

Findings

  1. [Nit] packages/deck/test/drafts.test.ts:547 - the O_NONBLOCK open has no test of its own. Since the stat pre-check went in, removing the flag passes every test, which I confirmed. This is recorded in REVIEW.md round 6 row 3 - add one child-process case that patches the default fs export's statSync to report the FIFO as a regular file before importing the module, for example fs.statSync = (p, ...a) => String(p).endsWith("pipe.md") ? { isFile: () => true } : real(p, ...a), then assert that readDraft("pipe").ok and saveDraft(...).ok are both false. I ran exactly that, and it passes at head in well under a second.
  2. [Nit] packages/deck/test/drafts.test.ts:525,543,555 - the result is parsed from the last line of stdout + stderr. Any stderr output, such as a Node warning or a console.error from the module, becomes the last line, and the test then fails with an opaque SyntaxError. A child that crashes, for example because tsx does not resolve, also fails that way rather than with a clear message. A timeout reports only expected true to be false. - parse r.stdout only, assert r.status === 0, and pass out as the assertion message, for example expect(timedOut, out).toBe(false).
  3. [Nit] packages/deck/app/lib/drafts.server.ts:150-158 - the comment order is now confusing. The O_NONBLOCK comment sits above the stat pre-check rather than above the open it explains. The doc comment at line 147 still says the function throws EISDIR, but a directory now throws Not a regular file. (the docstring part predates this round). - move the O_NONBLOCK comment down to the openSync line, and fix the docstring to say "ENOENT, or Not a regular file".
  4. [Nit] .specs/claude-dazzling-davinci-h66qwp-issue-66/REVIEW.md:22,95 and SPEC.md:173 - the commit lists stop at a5f6659. 86ae24b, the errno typing fix that the round-6 test needs in order to typecheck, and 151be2e are missing. Row 4 points to "this docs commit" instead of a sha. - add both shas to the REVIEW commit table and the SPEC Commits line, and replace "this docs commit" with 151be2e.

CI status on 86ae24b

4 of 4 check runs completed, all success:

  • guards (10:34:52 UTC)
  • licence (10:34:46 UTC)
  • test (22.x) (10:37:11 UTC): 112 files, 2291 passed, 11 skipped
  • test (24.x) (10:37:11 UTC): 112 files, 2291 passed, 11 skipped

The two test jobs were still in progress when I first checked. Mergeable state: unstable at that first check, while the jobs ran.

Unverified

  • I ran nothing locally on Node 24. That --import tsx resolves on 24.x rests on the CI logs: the skipped count is unchanged and the job is green.
  • I did not check macOS: BSD mkfifo, O_NONBLOCK, and how spawnSync kills a child there.
  • I did not run the full deck suite locally, only the two draft suites, typecheck and the leak and dash gates. For the full count I am relying on CI.
  • Nothing was run in a real browser in this round. Case-insensitive name collisions and async reads remain deferred, as recorded in the SPEC.

Generated by Claude Code

…t keeps drafts (#66)

Read the sidecar only if it resolves to itself inside the drafts folder, is not a symlink (O_NOFOLLOW) and has one hard link, and write the .bad backup from the confined read instead of copying through the path. Extract the dev reseed into scripts/dev-paths.mjs so a test runs the real reset and shows drafts survive it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
…lose (#66)

useBlocker asks before an in-app navigation while the draft is dirty, and a beforeunload listener is registered only while dirty and removed after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Review of c73eadf (Opus)

Verdict: changes requested. The sidecar fix holds: every sidecar exploit variant I tried is refused. Two problems from the same class remain in other paths, and I reproduced both against this head. The unsaved-edits guard and the dev reseed are correct.

Findings

  • [Major] packages/deck/app/lib/drafts.server.ts:290 - a draft file hard-linked to an outside file is served by the draft API.
    • Problem: view() calls readCapped without the hard-link check. Confinement only resolves symlinks, so ln <outside private file> drafts/x.md passes it, and GET /api/drafts?name=x.md returns the outside bytes (reproduced).
    • The same route also exposes a hard-linked sidecar. The sidecar reader now refuses it, but an in-folder symlink leak.md -> .deck-drafts.json is read as an ordinary draft and returns the linked bytes (reproduced).
    • This is the outcome the sidecar fix was meant to prevent, by a simpler route. It needs the same filesystem, and with protected_hardlinks=1 the creator must own the target or be able to read and write it.
    • Saving through the Deck does not write through the link, because the rename replaces it.
    • Suggested fix: on the draft read path, refuse st.nlink > 1 on the open descriptor, as the sidecar read already does (noLinks, without needing O_NOFOLLOW there). Do this in view(), so list, open and the in-lock conflict read all refuse it.
  • [Major] packages/deck/app/lib/drafts.server.ts:426 and :271 (via atomicWrite, safe-fs.server.ts:456-459) - a planted temp-file symlink makes a draft save overwrite a file outside the workspace.
    • Problem: the temp name <file>.tmp-<pid>-<Date.now()> is predictable, and writeFileSync(tmp, ...) follows symlinks. Anyone who can write to drafts/ (the agent, by design) can pre-plant symlinks for the next few thousand milliseconds and trigger a save (POST without an Origin header is accepted). The save then writes the draft content into the outside target. rename also leaves a.md (or .deck-drafts.json) as a symlink to that target.
    • Reproduced: an outside victim.conf was overwritten with the saved draft text, and a second outside file was overwritten with the sidecar JSON.
    • The helper predates this PR (the inbox uses it too), but this PR is what places it in an agent-writable folder that it claims to confine.
    • Suggested fix: in drafts, create the temp file with flag: "wx" (O_EXCL never follows a final symlink) and a random suffix from crypto.randomBytes, then rename. Fixing atomicWrite/atomicWriteBuffer themselves is a separate follow-up.

Verified, no finding

  • Sidecar confinement, no outside bytes returned or copied for any of these:
    • a symlinked sidecar, both non-JSON and valid JSON
    • a relative symlink
    • a symlink to an in-folder symlink that points outside
    • drafts/ itself symlinked outside (saves 500), or to an in-workspace directory whose sidecar is an outside link
    • a symlinked .bad with a corrupt sidecar (the link is removed, and the wx copy holds only the confined bytes)
    • an in-folder symlink to .bad
    • the sidecar swapped to a symlink between saves
    • a FIFO at the sidecar path (no hang)
    • a directory at the sidecar path
    • .lock symlinks for the sidecar and for drafts (wx refuses them; no bytes read)
    • a symlinked draft
    • A swap of drafts/ between the realpath check and the open would need an outside file literally named .deck-drafts.json that has one link and is not a symlink, so it is not practically exploitable.
  • Unsaved edits:
    • Decline stays and confirm leaves. No prompt when clean or after a save.
    • Browser back (POP) is blocked, and leaves on confirm.
    • Not a trap: a second attempt after a decline asks again, and a failed save or a draft removed outside both leave on confirm. Declining and then saving leaves with no prompt.
    • Polling and conflict detection keep working after a decline.
    • beforeunload is added only while dirty and removed on unmount.
    • The existing switch/create confirm, the late-response guards and the poll generation guards are unchanged, and their tests pass.
  • Dev restart: dev.mjs behaviour is otherwise unchanged (same seed steps and order). .workspace/ is a sibling of .runtime/ and is never removed. An explicit WORKSPACE_ROOT is respected.
  • Scope: the diff touches only Basic text editor inside the Deck for drafting with agents #66 files; Composer: turn a large 10BC8 paste into an attached markdown document #65 is untouched. There are no new Claude-Session trailers (only 40f5943, fb5663b and b2edbbb carry one).

CI on c73eadf

All 4 check runs completed with success: test (22.x), test (24.x), guards, licence. The combined commit status has no statuses. Locally: pnpm typecheck passed, and the draft suites passed (75/75).

Unverified

  • Not run in a real browser or a running dev server. The editor was checked with jsdom probes inside createRoutesStub, and the server with a throwaway temp workspace driving drafts.server.ts directly, not over HTTP.
  • Case-insensitive filesystems were not checked.

Generated by Claude Code

…sive random temp files (#66)

Refuse a draft with more than one hard link on the open descriptor, require the file a draft name resolves to to be a draft name, and write drafts, the sidecar and backups through an O_EXCL temp file with an unpredictable suffix instead of the shared predictable-name helper.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Claude <noreply@anthropic.com>
@simon-inkie
Copy link
Copy Markdown
Owner Author

Re-review at a050c6d. Verdict: approve. Both Majors from round 9 are closed, and I found no new real bugs.

Re-exploits, run against the real module in a throwaway workspace

  • Major 1, hard link: ln <outside file> drafts/hl.md now gets 404 on open, is not listed, and saving it (even with force) gets 400. The outside file is unchanged. With a hard-linked sidecar plus leak.md -> .deck-drafts.json: 404, not listed. The sidecar is refused and logged, the draft still saves, and the outside file is unchanged. A symlink onto .deck-drafts.json.bad, a.md.lock or .deck-drafts.json.lock gets 404 on read and is refused on save. The nlink check and the read use the same descriptor (readCapped, drafts.server.ts:198-219), so a hard link added after the open cannot change which file is read.
  • Major 2, predictable temp name: I planted symlinks at every old-style a.md.tmp-<pid>-<ms> name across a 2 s window and then saved. The outside victim was unchanged, a.md is a regular file, and no temp files were left behind. The temp file is created with wx, so a planted name fails instead of being followed. rename replaces a symlink at the target name instead of following it, and a symlinked or dangling-symlink target is refused before the write. Written files are mode 0644 under umask 022.
  • Names: .deck-drafts.json.md, A.MD, é.md, a..md, x.md. and a name containing NUL all get 400. x.md.lock.md is a valid draft and collides with no bookkeeping name.
  • Still working: a normal draft (one link) reads, lists and saves. CRLF is stored as LF. A stale base gets 409, and force overwrites. The 1 MB cap gives 413 at 1 MB + 1 byte and accepts exactly 1 MB. Sidecar attribution reads as person. The .bad backup is created exclusively. Every write in the module goes through safeWriteFile or the exclusive .bad create, and atomicWrite is no longer used. The sidecar lock is still taken only inside the per-draft lock.
  • Editor: not changed since c73eadf. All 82 draft and editor tests pass (confirm-before-switch, route blocker and beforeunload, dropping stale save and poll responses).

Findings: none at Major or Minor.

CI on a050c6d: guards passed, licence passed, test (22.x) passed, test (24.x) passed (4/4). Locally: pnpm typecheck exits 0; pnpm test gives base 48 passed and deck 2309 passed, 11 skipped.

Scope: the diff touches only #66 files; #65 is untouched. Commits after b2edbbb have no Claude-Session trailer.

Unverified

  • Concurrent-save atomicity: checked by the existing tests only. I did not stress it separately.
  • Read timing window: the draft read opens the already-resolved path without O_NOFOLLOW (drafts.server.ts:198-201). In principle a path swapped between the realpath check and the open would be followed. I did not test this, so it is not reported as a finding. A cheap hardening is to pass O_NOFOLLOW for drafts too, since draftPath has already resolved the final component.
  • Not tested in a real browser.

Generated by Claude Code

@simon-inkie
simon-inkie merged commit fee194e into main Oct 16, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Basic text editor inside the Deck for drafting with agents

2 participants

0