Skip to content

fix(collab): store lone surrogates and NUL as U+FFFD (wiki-v2 issue 773) - #80

Merged
PMQ9 merged 2 commits into
wiki-v2from
fix/773-store-unicode
Nov 8, 2026
Merged

PMQ9 merged 2 commits into
wiki-v2from
fix/773-store-unicode

Conversation

@PMQ9

@PMQ9 PMQ9 commented Nov 8, 2026 •

Copy link
Copy Markdown

TL;DR

A crafted collab client could put a lone UTF-16 surrogate or a NUL into a page. Postgres then refused every store of that page while it was open. The collab store now writes the serialized JSON through storeSafeJson, which turns each of these into U+FFFD. The live Y.Doc and the ydoc bytes keep the raw value.

What

  • New fork-owned apps/server/src/authz/page-write/store-safe-json.ts with storeSafeString and storeSafeJson.
    • A lone surrogate becomes U+FFFD (native toWellFormed). U+0000 becomes U+FFFD too.
    • It covers values and object keys.
    • It is copy-on-write: a clean input comes back as the same reference, and the input is never mutated, because y-prosemirror can hand back Yjs-owned format objects.
    • Non-plain objects such as Uint8Array are left alone. An own __proto__ key is kept via defineProperty. If two keys normalize to the same name, the last one wins.
  • Seam, one line plus an import, in upstream collaboration/extensions/persistence.extension.ts (super-repo UPSTREAM_MODIFICATIONS.md §122):
    tiptapJson = storeSafeJson(TiptapTransformer.fromYdoc(document, 'default')); // CCC #773
    It runs before jsonToText, the deep-equal no-op check, the blank-clobber guard, updatePage, syncTransclusion and mentions. So pages.content, text_content and page_transclusions.content are all covered.
  • Specs: store-safe-json.spec.ts (13 unit tests) and persistence-store-unicode.pg.spec.ts (4 tests on real Postgres, plus the AUTHZ_REQUIRE_PG anti-vacuity check).
  • authz/route-guard/import-boundary.spec.ts: comment text only.

Why

Fixes https://github.com/cccvu/wiki-v2/issues/773.

  • Implementation plan (canonical, for both PRs): https://github.com/cccvu/wiki-v2/issues/773#issuecomment-6726122142. Review comments for this PR set go on the super PR, cccvu/wiki-v2 PR 782.
  • Yjs stores format values and keys, embeds and JSON content as escaped JSON, so a lone surrogate survives decoding. NUL survives everywhere.
  • Postgres refuses both. Checked on pg 18: jsonb gives 22P02 for "\ud83d" and {"\ud83d":1}, and 22P05 for "\^@". text gives 22021 for 0x00.
  • Before this change, every store failed: COLLAB_STORE_FAILED, a settle answered 503, a write returned write_outcome_unknown, and edits were lost on unload.
  • Fork PR 79 fixed only the API builder.

How

  • Only the stored projection is normalized. The audit found fromYdoc in exactly two places: the store and the ADR 0019 digest. History, restore, duplicate, export, /v1 and MCP all read the row, which is now clean.
  • The ydoc bytea keeps the raw state. That is safe because it is binary, and NUL is already stored there legitimately by the write-idem keys. Every later store normalizes the same state to the same JSON, so it reports unchanged and no rewrite loop starts.
  • The digest is unchanged. It is live-vs-live and never throws.
  • Browsers do not crash on these characters and never POST page bodies.
  • Rejected: filtering at ingress. Refusing a frame closes the document, and y-indexeddb re-sends the same struct on every reload. That locks out a legitimate user who pasted a NUL. It also cannot cover API writes or rows that are already poisoned.
  • Rejected: repairing the live doc. About 200–350 lines, it hits the format-negation trap, and it would still need this as a backstop.
  • Accepted trade-off. An edit that changes only malformed characters stores as unchanged, so the ydoc bytes are not rewritten. The difference is invisible after normalization. This is the same behaviour write-idem already has, and a test pins it.

Testing

  • Red before (seam line reverted): 4 failed and 14 passed of 18. expect(storeFailures).toEqual([]) got ["22P05"], and flushPageContent returned {flushed:false, reason:"error"}.

  • Mutations:

    Mutation Unit pg
    values skip toWellFormed 3 red 4 red (22P02)
    keys not normalized 3 red 4 red (22P02)
    NUL not replaced 7 red 4 red (22P05)
    mutate in place 3 red 1 red (live doc unchanged)
  • Suites:

    • new specs: 18/18;
    • src/authz non-pg: 146 suites, 2561 passed, 0 failed, 334 skipped;
    • CI-pattern pg specs (authz, service-bridge, editor-compat): 41 suites, 583 passed, 0 failed.
  • Checks: typecheck is clean in both orders; super scripts/check-upstream-boundary.sh exits 0; node --test scripts/ci/*.test.mjs passes 264/264; eslint is clean on the new files.

  • Perf (40k-node page, median of 20): storeSafeJson takes 5.9 ms clean (same reference) and 6.0 ms with one poisoned leaf. fromYdoc takes 9–12 ms on the same doc, so this adds a few ms per debounced store.

Risk

  • Low. It is pure, copy-on-write normalization of the stored projection only. There is no migration, no schema change and no infra change.
  • One-time 412 for pages that hold these characters. Since review round 1, the ADR 0019 digest hashes storeSafeJson(fromYdoc(doc)), the same projection the store writes. A clean page comes back as the same reference, so its digest does not change. A page that holds a lone surrogate, a NUL, a BigInt or a non-plain attribute object gets a new digest. A caller holding a version issued before the deploy gets one 412 and must re-read; an old and a new task disagree in the same way during the rolling overlap. Nothing is lost: a 412 changes nothing.
  • Rollback: revert this PR and re-pin the super-repo gitlink.
  • Merge order: this PR first, then re-pin the super-repo gitlink to its merge commit, then merge the super PR.
  • Out of scope: schema-invalid collab content, tracked in cccvu/wiki-v2 issue 781.

🤖 Generated with Claude Code

Yjs keeps a lone UTF-16 surrogate in format (mark attribute) values and
keys, embeds and JSON content, and U+0000 everywhere. Postgres jsonb
refuses both (22P02/22P05) and text refuses NUL (22021), so a crafted
collab client could make every store of a page fail while it was open.

The store now serializes through the fork-owned storeSafeJson
(authz/page-write/store-safe-json.ts): each such code point becomes
U+FFFD in values and keys, copy-on-write (a clean page is the same
reference; Yjs's own objects are never written to). It runs before
jsonToText, the deep-equal no-op check, updatePage and the post-store
effects. The live doc and the ydoc bytes keep the raw value; every later
store normalizes the same way, so the row converges as `unchanged`.

Seam: one line plus an import in persistence.extension.ts (UPSTREAM_
MODIFICATIONS.md section 122). Pinned by a unit spec and a real-Postgres
spec that applies a raw Yjs update through real Hocuspocus 3.4.4 and goes
red without the line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PMQ9

PMQ9 commented Nov 8, 2026

Copy link
Copy Markdown
Author

Paired super-repo PR: https://github.com/cccvu/wiki-v2/pull/782 (review comments go there). Merge this PR first, then re-pin the super gitlink to its merge commit, then merge the super PR.

🤖 Generated with Claude Code

@PMQ9 PMQ9 changed the title fix(collab): store lone surrogates and NUL as U+FFFD (#773) fix(collab): store lone surrogates and NUL as U+FFFD (wiki-v2 issue 773) Nov 8, 2026
…ection (wiki-v2 issue 773)

Review round 1 on wiki-v2 PR 782.

- storeSafeJson skipped any object whose prototype was not Object.prototype
  or null, and never called toJSON. A crafted collab client could still wedge
  every store with 22P05: an element attribute named __proto__ (Yjs builds
  attrs by assignment, so it re-prototypes them), an object value with an own
  __proto__ key (lib0 readAny does the same), or a Y.Map attribute value
  (serialized through toJSON). The walk now follows JSON.stringify: toJSON
  first, own enumerable keys whatever the prototype (copied into a plain
  object), undefined/function/symbol dropped or null, non-finite numbers null,
  -0 as 0, ArrayBuffer views left as is.
- A BigInt attribute made JSON.stringify throw on every store and every
  settle. It now stores as its decimal string.
- The ADR 0019 digest hashes storeSafeJson(fromYdoc(doc)), the projection the
  store writes: a clean page is the same reference, so its digest is
  unchanged; a BigInt no longer fails the settle; and a version survives an
  edit that changes nothing the store keeps.
- store-safe-json.fitness.spec.ts: every fromYdoc call is the direct argument
  of storeSafeJson, in the two allowlisted files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PMQ9
PMQ9 merged commit 42d71aa into wiki-v2 Nov 8, 2026
@PMQ9
PMQ9 deleted the fix/773-store-unicode branch November 8, 2026 20:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant