Skip to content

feat(serving): run tier one patches in a sandbox - #221

Merged
allisonmahmood merged 6 commits into
mainfrom
sdk/205-tier1-shell
Sep 12, 2026
Merged

allisonmahmood merged 6 commits into
mainfrom
sdk/205-tier1-shell

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner

Tier 1 patches need to run browser code without inheriting the reader's login or gaining direct access to company resources.

This adds the sandboxed frame and document-bound broker, admits raw tier 1 bundles, and handles routes, files, session changes and stale versions. It includes a1c3b77's reader-facing polish for the notices and needs-rebuild door.

Stacked on #220 (sdk/204-sdk-commands), which remains this PR's base branch.

Review corrections in 741b990 expose the real client route/download APIs, transfer upload buffers, preserve Auth door policies, force inert shell downloads, retain public routing, serve UTF-8 content, share runtime limits, and correct the README/SDK guidance.

Approved framing policy, applied in 7d8ba8f: Static and scripted /~content responses use frame-ancestors 'self', including content error responses. Outer shells and first-party pages retain frame-ancestors 'none'. Both Chromium and Firefox verify that normal shell framing works, foreign parents cannot embed content, and shells cannot themselves be embedded. The earlier policy decision is resolved.

Verification

  • pnpm lint and pnpm typecheck passed.
  • pnpm test --maxWorkers=1: 661 tests passed across 70 files; no tests skipped or timeouts changed.
  • Chromium and Firefox: all 8 serial acceptance scenarios passed, including real-client route/history/download calls, actual upload detachment, ignored-download-hint containment, public routing for both identities, Auth sign-out submission, Unicode rendering, outer-shell anti-framing, and native 2,000-row printing.
  • Auth uses isolated fake development sessions. Browser sign-out submission is intercepted before contacting Clerk; offline Auth socket tests cover the logout response.

Closes #205.

Implementation and PR prepared with GPT-6 Astra in Oh My Pi. Notice polish by Claude Fable 5.1.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 11, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed a1c3b77 against origin/sdk/204-sdk-commands (4576918), using #205 and its referenced §10 contract. One pass, no subagents; merge blockers only.

Standards

No independent merge-blocking method or YAGNI findings. The standalone shell export, bounds and wire-retirement handling are explicitly requested, not speculative scope.

Spec

1. Intent / method — expose the route bridge and download through the shipped client

#205 requires “Deep link and back/forward through the route bridge” and “a shell-owned download.” The broker implements these, but the actual client cannot consume them. Client exposes no route or download surface; its transport discards the bootstrap route and ignores port events without an id. The acceptance fixture instead captures the port alongside the real client and implements a second request/event client (fixture-client.ts:65–85, 99–105). Thus the tests pass for capabilities unavailable through the generated patchy client; the frame's own URL is only /~content/..., not the deep link.

Block until: wire these browser operations/events through the existing client transport and exercise that client in the route/download acceptance scenario, rather than requiring each patch to recreate the fixture's second transport.

2. Intent — production uploads clone bytes instead of transferring them

#205 requires “bytes transferred as ArrayBuffer”; the referenced serving decision explicitly says ownership transfers. The now-enabled production upload path calls port.postMessage(message) without a transfer list. Only the fixture's raw upload probes supply [bytes]. Replies transfer correctly, but real uploads still structured-clone the entire buffer, including allowed 20 MiB files.

Block until: transfer the prepared upload buffer through the real transport and verify that path, not just harness.raw(..., [bytes]).

Verification: disposable server/Postgres with fake Clerk credentials, actual source-built patchy/client, and a Chromium browser. Identity and file put/get succeeded; client/file method inspection confirmed the missing browser operations, and a four-byte upload retained its sender buffer. No tracked files changed; the disposable instance was stopped. Firefox and the full suite were not rerun.

Summary: Standards 0 blockers; Spec 2 blockers, foremost the route/download functionality missing from the shipped client.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of PR 221 against issue #205 (plus method, YAGNI, tests, surfaces, and containment). Diff is the three-dot range 4576918...a1c3b77 (stacked on #220). Ten parallel reviewers; Standards and Spec are kept separate on purpose.

Intent vs #205

#205’s product intent is the viewer promise: a colleague opens one company address and gets a trusted shell that never puts uploaded script on the session. Tier ≥ 1 binds a patch/version, frames /~content/<patchId>/<versionId>?n=<nonce> in an opaque-origin sandbox, and talks to Patchy only through a document-bound MessageChannel broker that acts as the reader. Merge admits raw tier 1 bundles and serves them in that sandbox; tier 0 stays srcdoc.

This PR implements that intent, not a subset and not a different product. It copied the prototype’s shape (one-shot port, second load revokes, own-property dispatch, shell-owned route/download/print) and did not import proto/frame-broker files.

Small drift, same intent: not_available_on_public is a stopping first-party notice (matches #205 “Done when: tables.list shows the notice”, not spec §10’s “three notice codes only”). Files use the bytes routes, which the same #205 bullet also asked for.


Standards

Hard violations

packages/serving/src/Pages.ts ~45–50, 94–102 — patchUrlHeaders now always sets SCRIPTED_SHELL_SECURITY_POLICY, and setHeaders(admission, …) copies that onto Auth doors.

That policy is form-action 'none' plus script-src/connect-src 'self' with no Clerk host, and it drops Auth’s frame-ancestors 'none'. The deactivated page (pageResponse(..., session) with signOutForm) therefore cannot POST /logout and cannot load Clerk / /auth/session.js. The signed-out door loses clickjacking protection.

  • ui-consistency (Served patches / Change discipline): first-party doors compose Auth’s template; preserve form and session-script behavior; only company patch shells add Clerk hosts — not by stripping them from Auth pages.
  • ADR-0006: a doored Auth page keeps Clerk’s Frontend API script/connect sources.
  • CLAUDE.md Reverse states: deactivation still needs a working sign-out.

Smallest fix: drop CSP from patchUrlHeaders. Middleware already applies the scripted-shell fallback when a response has no CSP; leave Auth pageResponse CSP intact.

Hit every surface (soft)

README.md ~51–52 still lists “browser broker” with unimplemented local patchy dev. Product/ADR/skills were updated; this line was not. packages/patchy/README.md still says “The API also admits tier 0 … higher tiers remain refused,” which this PR makes false.

Effect

No Effect service findings. Broker is a browser IIFE (globalTimers/globalFetch off with reason); Schema compilers sit at module scope; Pages/PatchesApi still yield* env services and catchTags.

UI otherwise

Notices / needs_rebuild compose htmlPage + shared .auth-card / .auth-kicker / .auth-action. Patch frame keeps height: 100%, overflow: hidden, title, referrerpolicy, escaped attributes; broker is external /~shell/broker.js. Device kicker extraction matches “named shared class in the shell.”

Baseline smells (judgement only)

  • Duplicated Code — renderShellNotice re-emits Auth pageResponse brand/card wrap. Suppressed: ADR-0010 (@patchy/serving/shell must not import Auth).
  • Speculative Generality — ./shell subpath for a local runtime that product.md still calls unbuilt. Suppressed: ADR-0010 / ticket 14.
  • Duplicated Code — chromium-print.ts / firefox-print.ts share goto/print/EOF polling. Engine prefs differ; leave unless a third printer appears.

Spec

(a) Missing or partial

Playwright is Chromium+Firefox, fullyParallel: false, workers: 1, four tests. Against the Done when list it covers navigation/204/redirect egress, pending read/write replacement, malformed/oversized/duplicate envelopes, 32/64 MiB bounds, door login/logout/expiry/switch, CSRF POST, CSP on content 401/404/redirect/attachment, stale public refresh-once, 2000-row print, deep link/back-forward, url(name) blob, shell download, localStorage/fetch/window.open, signed-out public tables.list notice.

Gaps vs originating copy, not the Playwright bullets: spec §10 “Public tier 1: every op answers not_available_on_public, member or not; me answers null” is only exercised signed-out. Issue 205 “session_expired and principal_changed reload the whole page after sign-in” is checked as a Sign in return href, never a completed sign-in.

(b) Scope creep

Device-login markup was restyled onto .auth-kicker (DevicePages.ts) — not a frame/broker requirement. The broker also adds a 20 MiB file cap, per-op JSON limits, and a hostile-clone jsonBytes walker; issue 205 only asked “outstanding requests and held bytes bounded (32, 64 MiB).”

(c) Implemented but wrong

Spec §10: browser-owned ops “route.set (refuses a ~ first segment), route on popstate, download are answered in the shell.” Public restriction is “every other op” after bootstrap me is null — company-data runtime, not history. broker.ts does if (me === null) throw not_available_on_public for route.set, then location.replaces the notice, so a public patch cannot drive the route bridge.

Otherwise the asked surface is present: exact content CSP; Permissions-Policy camera=(), microphone=(), geolocation=(); iframe sandbox="allow-scripts allow-modals"; shell frame-src 'self'; @patchy/serving/shell exports renderPatchWrapper, brokerScript, CSP constants with no auth; raw tier 1 store; tier 0 script → tier_mismatch; ADR-0010, glossary, product.md, skill + matching lock hash.


Method

The architecture is the small model ADR-0010 asked for: one version-keyed renderer, opaque-origin iframe, document-bound port, first-party notices. Admission is the right size (tier ≥2 refused; tier 0 through validateHtml; else raw + maxBundleBytes).

Ownership is readable:

  • render.ts — marketing home/404
  • shell.ts — wrapper, notices, brokerScript, re-export of shell-headers.ts
  • shell-headers.ts — pure CSP/cache strings
  • serving-headers.ts — Effect middleware + fallbacks
  • Pages.ts — door, which HTML, which policy
  • broker: one browser file → esbuild IIFE → generated/broker-script.ts, fail-closed if a node: import survives

Overbuilt is almost all in broker.ts: a custom jsonBytes walker plus Schema decode plus 32/64 MiB accounting, and that 536-line mount() has no unit tests (only Playwright). Hardcoded /api/runtime/call, /~shell/broker.js, /~content/…?n= bake the host URL grammar into the blob — ticket 14 (patchy dev) will have to be a same-origin host with that grammar; there is no base-URL hook. That is acceptable for this ticket if local serving copies the production paths, and it will hurt if it does not.

Tests are proportional to “serial and few,” not a second serving stack. Weak method: waitForTimeout on hostile nav; print helpers launch a second headed browser, which is earned for native window.print().


YAGNI

The core is the small model. Spec reserved chunk* / cancel; this code does not implement them. Four serial Playwright tests against a real server; the fixture drives createClient and only adds raw() for hostile envelopes. jsonBytes is earned (hostile structured clones cannot hit JSON.stringify first), not speculative. Print, clipboard, 32/64, three stale states are spec — not YAGNI.

Real dings:

  • Duplicated bodyLimit. Broker hardcodes what Runtime already computes from config. A limits change silently desyncs the frame from the server.
  • not_available_on_public as a terminal shell notice. Spec §10: notices for access_denied / session_expired / principal_changed only; public ops surface to the patch. This navigates the whole page away.
  • Over-accounting. reserve(id.length * 2 + 64) for Set-entry overhead is not the 32/64 MiB bound.
  • CSP by string replace in shellContentSecurityPolicy. Compose the directive list; a reordered constant would silently stop injecting Clerk.
  • Test timing slop. Four waitForTimeout(200|250|300) in tier1.spec.ts. Poll the thing you mean.
  • Comments on nonce, referrerPolicy: "same-origin", and “do not abort a mutation” record constraints. “This is always the first runtime call…” narrates.

Acceptance tests vs “Done when”

Harness matches the ticket: Chromium and Firefox, workers: 1, four tests, fake Clerk keys, seeded session.

Item Status
frame-src blocks script nav, redirects, 204 covered (asserts no foreign request, shell URL unchanged)
Nav during pending read/write covered (replacement received === []; insert once)
Malformed / oversized / duplicate-id covered
Login, logout, expiry, account switch covered (cookie swap, not live Clerk UI — as specified)
Simple cross-site POST refused covered (400 + zero runtime_calls)
CSP on redirects, errors, uploaded active partial (proxy /~tier1/redirect, not a production 302)
Stale public shell refreshes once covered (exact two navigations)
2,000-row print, first + last covered (DOM + pdftotext)
Deep link + back/forward covered
Own file via url(name) covered (blob: + naturalWidth === 1)
Shell-owned download covered (filename + bytes)
localStorage / fetch / window.open fail covered (origin: "null")
Public T1 signed out + tables.list notice covered

Hit every surface

  • Wire — hit. packages/api admits tiers 0–1; handler matches; docs/API.md mirrors caps.
  • CLI — partial. No new command (ok). Skill + lock hash updated. packages/patchy/README.md still says higher tiers remain refused.
  • Dev loop — partial. docs/DEVELOPMENT.md and test/postgres.ts build the broker. patchy-dev-loop skill never mentions it.
  • Vocabulary / product — hit. ADR-0010 written; ADR-0006 scoped; glossaries and docs/product.md carry the promise.
  • Migrations / company resources / repo layout — n/a.
  • Served pages — hit. ui-consistency updated; no new packages/core/fixtures accept case for tier ≥ 1.
  • Reverse states — hit, except the Auth-door CSP overlay above breaks the deactivated way out.

Containment

Bug — shell download mints a same-origin executable blob. broker.ts ~460–487 does createObjectURL(new Blob([bytes], { type: content.contentType })) in the shell and clicks <a download>. Type is patch-chosen (text/html, image/svg+xml). HTTP files.get is Content-Disposition: attachment plus sandbox; default-src 'none' (ADR-0010). The broker path is neither. The click is async off a MessagePort (no parent user gesture). If the UA ignores download, the shell navigates to uploaded HTML/SVG with the Clerk session. Force application/octet-stream (or a sandboxed download context).

Concern — no frame-ancestors on shell/content. First-party pages set frame-ancestors 'none'. Scripted shell/content CSPs do not. A same-site sibling iframe GET does send Lax cookies, so a live company shell+broker can be clickjacked into acting as the viewer.

Note — listed threats otherwise hold. Content URL carries CSP sandbox + connect-src 'none'; isolation tests origin null; clipboard-write only; simple cross-site POST is invalid_request with no mutation; public versions refuse every op except me; shell script is external /~shell/broker.js only; server admits Origin / Sec-Fetch-Site / principal independently of broker schemas.


UI consistency / Effect

No UI consistency findings. Notice polish (a1c3b77) matches the skill: first-party htmlPage cards, shared .auth-kicker, access-denied has no reload, running pages are the sandboxed frame only.

No Effect service findings.


Standards: 2 findings (1 hard, 1 soft). Worst: Auth-door CSP overlay blocking deactivated sign-out and Clerk session scripts.

Spec: 4 findings (2 partial, 1 scope, 1 wrong). Worst: public route.set stopped as not_available_on_public instead of remaining a shell-owned route bridge.

@allisonmahmood

allisonmahmood commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner Author

Resolution of both Astra and Grok. Review fixes: 741b990; CI integration fixes: 51dd045; approved content-framing policy: 7d8ba8f. The framing decision is resolved; there is no pending product decision.

Fixed

  1. Shipped client route/download surface. patchy/client exposes route.get/set/subscribe and file-store download; bootstrap route and popstate events reach consumers. Normal acceptance operations use that client. The fixture's second request/event client was removed; raw port access remains only for hostile envelopes and reply observation.
  2. Production upload ownership. The real MessagePort uses a transfer list. Full upload buffers detach; subviews copy only their selected bytes, avoiding adjacent-byte exposure or detachment. Real Node MessageChannels and both browsers verify the transport and stored bytes.
  3. Auth doors and sign-out. Removed the CSP overlay from patchUrlHeaders. Auth retains Clerk script/connect sources, form permission, frame-ancestors 'none', and its same-origin referrer policy. Both browsers submit the deactivated door's actual sign-out form with the correct Origin.
  4. Executable shell download blobs. Shell-created blobs always use application/octet-stream; frame-local file URLs retain their stored MIME. Both browsers still download uploaded HTML when the anchor's download hint is removed, rather than navigating the authenticated shell into it.
  5. Framing containment — approved policy applied. Both static and scripted /~content policies use frame-ancestors 'self'; content errors retain that boundary. Shells and first-party pages use 'none'. Browser acceptance verifies normal shell framing, rejected foreign-parent content embedding, and rejected same-origin/foreign embedding of shells. ADR-0010 records why content must admit its shell.
  6. Public route and error behavior. Public route changes and back/forward work. not_available_on_public rejects to patch code without replacing the page. Only access_denied, session_expired, and principal_changed are access-class stopping notices. Public me remains null for both signed-out and signed-in readers.
  7. Content encoding. HTML explicitly declares UTF-8 without rewriting stored bytes/BOM. Both browsers render non-ASCII HTML without a meta charset.
  8. Duplicated body limits. Broker and Runtime share API byte-limit defaults and operation classification; server configuration overrides remain supported.
  9. Documentation mirrors. Corrected both stale READMEs; updated client guidance, ADR/product/glossary text, and the public skill hash. The approved ancestor policy is now documented rather than left as an unresolved exception.
  10. Acceptance gaps. Added signed-in public coverage and completed real /join return hops after expiry/account changes using fake development sessions. Firefox anti-framing checks observe rejected navigation/no committed shell document, not an inaccessible blocked frame's DOM.
  11. CI integration. The broker generator formats its TypeScript output with the repository's Prettier configuration. Packed-CLI smoke now expects the hardened viewer CSP. Fresh generation/format checking and the complete packed-CLI smoke passed after those corrections.

Retained, with reasons

  • Clone walker plus schemas and bounds: hostile structured clones must be bounded before JSON serialization/schema decoding; these checks defend different stages. Existing per-file/per-operation caps remain security limits, now shared instead of duplicated.
  • Conservative retained-ID accounting: completed IDs remain retained to reject replay. Budgeting their overhead prevents unbounded growth; it is a conservative budget, not byte-exact engine heap measurement.
  • Document-local broker state and browser coverage: kept the existing mount/lifecycle structure rather than splitting the port, principal and pending-operation state during these fixes. Real browser tests exercise document replacement, containment and revocation instead of substituting a mocked broker unit suite.
  • Standalone shell export and notice wrapper duplication: ADR-0010/ticket 14 require a shell usable without Auth/platform infrastructure. Sharing Auth's page renderer would violate that dependency boundary; notices still use the shared first-party styling.
  • Fixed same-origin URL grammar: the local host contract uses the same runtime/content/broker paths. No speculative base-URL configuration was introduced for an unbuilt alternative host layout.
  • Separate native print helpers: Chromium and Firefox require different printer controls/preferences. Both prove first and last rows in the native 2,000-row PDF; a generic printer abstraction is not earned here.
  • Bounded negative-observation waits: an immediate zero-request/reload assertion can pass before queued browser work executes. The existing windows observe prohibited effects; they are not positive readiness waits.
  • Controlled redirect/204 probes: these provide deterministic hostile navigation inputs without adding production attack routes. Real sign-in return navigation is now covered, but the proxy probes are not claimed as proof of CSP on every production redirect path.
  • CSP string composition: it matches fixed directive text, so directive reordering alone does not break Clerk injection. Direct header/Auth/browser coverage protects the boundary; a directive-builder refactor was unnecessary.
  • Bootstrap-first-call comment: retained because it states the required identity-bootstrap ordering, including anonymous shells, rather than adding a new behavior.
  • a1c3b77 notice/device-kicker polish: preserved the requested polish and named shared-class convention instead of introducing another style variant.
  • Dev-loop skill and core tier-0 fixtures: no new manual dev step exists—documented commands generate the broker automatically. Tier-0 sanitization fixtures stay unchanged because tier-1 raw admission has separate coverage; weakening the static policy fixtures would be wrong.
  • Spec-mandated bounds and wire retirement: retained refresh-once/needs-rebuild/no-replay behavior. Reserved chunk/cancel operations remain unimplemented because this ticket did not request them.

Verification on the approved-policy commit

  • pnpm format:check, pnpm lint, and pnpm typecheck: passed.
  • Focused serving/page suites: 22 tests passed.
  • Fresh source build, Chromium and Firefox: all 8 serial acceptance scenarios passed, including real-client operations, transfer detachment, containment, approved ancestor policies, and native 2,000-row printing.
  • Browser sign-out submission is intercepted before contacting live Clerk; offline Auth socket coverage verifies the logout response. This is not presented as a live-provider browser logout test.
  • Latest commit 7d8ba8f: all seven reported checks passed — lint, test (22), test (24), cli-smoke, clerk-live, dependency-review, and label (CI run). The stacked base has no required-status-check rule; all reported checks were verified regardless.
  • GitHub reports the PR mergeable. All review blockers are resolved under the approved framing policy; no merge was performed.

allisonmahmood and others added 6 commits September 12, 2026 14:17
The shell notices and the needs-rebuild door used the login door's card
but jumped straight to a headline and spoke in runtime terms ("unanswered
operations", "retired runtime wire", "the shell and this bundle disagree").

Give every notice a muted kicker above the title so the card reads as
Patchy stopping the patch, rewrite the copy in the reader's words (what
happened, what to do), and drop the trailing paragraph margin so notices
without an action are not bottom-heavy. The kicker is the device-login
page's existing treatment promoted to a shared `.auth-kicker` in the shell.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 8eb3b94 into main Sep 12, 2026
7 of 14 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/205-tier1-shell branch September 12, 2026 12:22
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patch repos can be initialized and refreshed, but cannot yet be
published without switching to a standalone HTML file.

Add repo publishing for tiers 0 and 1, with release and declaration
checks, typechecking, single-file bundling, and recoverable publication.
Creates save the returned patch ID; share and delete use that repo
identity. Update the CLI contracts and skills, and cover interrupted
publication and bundle refusal paths.

Stacked on `sdk/205-tier1-shell` (#221). This PR targets that branch and
contains the #206 changes, not the preceding stack.

Closes #206.

## Verification
- `pnpm test`: 672 tests passed across 70 files.
- `pnpm format:check`, `pnpm lint`, and `pnpm typecheck` passed.
- `pnpm test:packed-cli-e2e` passed against a real disposable server.
- Real-server/browser smoke verified provisioning, additive updates,
refusal paths, and starter saves through the broker.
- Standards and spec reviews completed; all findings fixed and confirmed
resolved.

Implemented with GPT-6 Astra in the Oh My Pi harness.

Merge preparation: three multi-process CLI scenarios exceeded Vitest's
five-second default on Node 22. Backported #223's existing 30-second
budgets for the credential-precedence sequence and two repo-build
scenarios. Assertions and product code are unchanged. All 113 CLI tests
passed locally on Node 22 with two CPUs; all four focused cases passed
with one CPU. Formatting and lint passed.

CI correction and merge preparation: GPT-6 in Codex.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:core Touches the core area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(serving): tier 1: the shell, the sandboxed frame and the broker

1 participant