Review of PR #780 (msch128/audit-train-3): Trusted Types, staticcheck/bench, resolver fallback

From mnema-talk v3.3.13, rendered on this site.

Reviewed at head 4d16f933e against origin/main, read-only, on 2026-11-11. Commits: 353bd9efe (Trusted Types), 6bfc3fc86 / 3b957e456 / 200187a06 (staticcheck, benchmarks), 54aa3160a / 4d16f933e (resolver fallback).

Verdict: not mergeable as is. Two blockers, both in the CI/tooling commits, both visible in the PR's own run 43053095684. The Trusted Types change itself has no missed sink that I could find; it has one should-fix gap and one hardening point.

Blockers

B1. Every e2e job dies with exit 127 before a browser starts

  • Where: e2e/ci-install-deps.sh:31 (introduced by 4d16f933e), together with the cd "$(dirname "$0")" at e2e/ci-install-deps.sh:13.
  • Scenario: the workflow runs e2e/ci-install-deps.sh chromium webkit from the repository root (.github/workflows/ci.yml:847, :1030). The script first changes into e2e/. ${BASH_SOURCE[0]} is still the relative e2e/ci-install-deps.sh, so cd "$(dirname ...)/.." tries e2e/e2e/.., fails, the substitution is empty and bash runs /scripts/ci-dns-fallback.sh: "No such file or directory", 127, and set -e ends the script.
  • Evidence: run 43053095684, step "Install browser system dependencies" fails with exit 127 in e2e-shard 1-4, e2e (firefox), e2e (webkit 1/2, 2/2). Reproduced locally with a two-file stub of the same layout.
  • Consequence: no CI run of this branch has executed the Playwright suite on a commit that contains the Trusted Types change (earlier runs of the branch are older commits, cancelled or failed). The Firefox and WebKit behaviour under the new policy is therefore unverified.
  • Fix: in ci-install-deps.sh the working directory is already e2e/, so call ../scripts/ci-dns-fallback.sh ... there, or compute the root before the cd. ci-audio-sink.sh:39 is correct as written (it never changes directory). At all three call sites append || true: the fallback is meant to be unable to fail a job, but under set -e a missing or non-executable script does exactly that.

B2. make staticcheck fails on a cold Go module cache, and takes the rest of backend-checks with it

  • Where: scripts/staticcheck.sh:23 (go run "$tool" ... 2>&1) and the "did not run cleanly" filter at scripts/staticcheck.sh:34.
  • Scenario: when the module cache does not hold staticcheck yet, go run honnef.co/go/tools/cmd/staticcheck@v0.8.2 prints go: downloading ... lines to stderr. They are merged into the output, match neither the finding pattern nor an indented detail line, and the script reports "staticcheck did not run cleanly" and exits 1.
  • Evidence: run 43053095684, job backend-checks, step "staticcheck": seven go: downloading lines, make: *** [Makefile:148: staticcheck] Error 1. Every later step (unit tests, allocation gate, fuzz smoke, build, docs checks) is skipped. Locally, with a warm cache, make staticcheck exits 0, which is why it was not seen.
  • This recurs on every cache miss (any go.sum change), so it is not a one-off.
  • Fix: warm the tool once before the three runs and fail clearly if that does not work, e.g. go run "$tool" -version >/dev/null 2>&1 || { echo "staticcheck could not be built"; exit 1; }, or build it into a temporary directory with GOBIN=... go install "$tool" and call the binary (also three times faster). Dropping ^go: downloading in the sed would work too but hides less cleanly.

Should-fix

S1. The name mnema-emoji-picker is unclaimed until the picker is opened for the first time

  • Where: web/scripts/emojiPickerCsp.ts:74 (the policy is created at module scope of the lazily loaded picker chunk, dist/assets/picker-*.js).
  • Scenario, verified in Chromium 157 against the built bundle served with the exact header: on the sign-in screen trustedTypes.createPolicy('vue' | 'mnema-markdown' | 'mnema-script-url', ...) is refused as a duplicate, default and any other name are refused, but trustedTypes.createPolicy('mnema-emoji-picker', { createHTML: s => s, createScriptURL: s => s }) is accepted. Whoever creates it first owns a full pass-through for HTML and script URLs. When the real picker loads afterwards, its own createPolicy throws, the patch falls back to the plain string and the picker's innerHTML is refused: the emoji picker is broken for that page.
  • Weight: it needs script that already runs on the page, so it is not an injection path by itself. It does make the documented claim ("only the four named policies can make a value a sink takes", SECURITY.md) untrue until the picker is opened, and trusted-types without 'allow-duplicates' only protects names that are taken.
  • Fix: create the policy at start-up in web/src/lib/trustedTypes.ts (same module that creates mnema-script-url) and let the patched parseTemplate import it (import { emojiTemplatePolicy } from '@/lib/trustedTypes' inside the patch text; the alias resolves in Vite). The policy object stays module-private. Add a unit test that the name is taken after the app module loads.

S2. mnema-script-url accepts any same-origin address, not only the worker scripts the build produced

  • Where: web/src/lib/trustedTypes.ts:42 (sameOriginScript).
  • What I tested (web/src/lib/trustedTypes.test.ts, run locally, plus reading the code): https://elsewhere.example/worker.js, //elsewhere.example/worker.js, data:text/javascript,1 and blob:null/... are refused; a blob:https://<own host>/... address is refused too, because its protocol is blob:. Any same-origin path, for example /api/..., is turned into a TrustedScriptURL.
  • Mitigations in place: ownScriptUrl is reachable only from module code, uploads and link-preview images answer with default-src 'none'; sandbox and nosniff, worker-src is 'self' blob:.
  • Fix: accept only /sw.js and paths under /assets/ (url.pathname === '/sw.js' || url.pathname.startsWith('/assets/')), in addition to the scheme and host check. The three call sites pass exactly those.

Notes

  • N1. vue is a pass-through, so mnema-markdown enforces nothing by itself. In the bundle Vue's patchProp runs every innerHTML value through its own policy (e[t] = t === 'innerHTML' ? vuePolicy.createHTML(n) : n), including the TrustedHTML from mnema-markdown, which is stringified and wrapped again. Any v-html, :innerHTML binding or h('div', { innerHTML }) therefore passes. The commit says so honestly (middleware.go:220-223, SECURITY.md). The lint rule vue/no-v-html covers the directive only; a bound innerHTML prop is not covered. Optional: add a restricted-syntax rule for innerHTML in templates and render functions. The policy mnema-markdown itself is tight: its only rule calls renderMarkdown(source, options), it has no createScriptURL, and the object is module-private.
  • N2. DOMParser.parseFromString is a Trusted Types sink, contrary to the brief: Chromium refuses it with "This document requires 'TrustedHTML'". It does not matter here: neither web/src nor the bundle outside the API docs chunk calls it.
  • N3. Dead sink in the bundle: highlight.js's highlightElement (e.innerHTML = i.value) is bundled in typingTarget-*.js but never called; the app only uses hljs.highlight(...) and sanitises its string (web/src/lib/markdown/highlight.ts:84). If someone calls highlightElement/highlightAll later it will throw under the policy.
  • N4. loadtest/viewer/main.go:252: err.Error() is now called without a nil check. Correct today (run and readLoop in session.go return only non-nil errors, I read both), but a later return nil becomes a nil dereference in the load-test tool instead of a quiet exit.
  • N5. The fallback script overwrites /etc/resolv.conf when resolvectl is missing or fails; on the hosted runners that file is a symlink into systemd-resolved's runtime directory, and tee writes through it. Fine for a throwaway runner.
  • N6. Local load test artefact: my own picker test fetched emoji data from jsdelivr and was blocked by connect-src; that is my bare <emoji-picker> without the app's dataSource (EmojiPicker.vue:68 passes a bundled file), not a finding.

Questions of the brief, point by point

QuestionResultHow checked
CSP the server sendsbasePolicy + require-trusted-types-for 'script'; trusted-types vue mnema-markdown mnema-script-url mnema-emoji-picker, enforced, no report-only headerread internal/httpx/middleware.go:189-275 and trustedtypes_test.go; go test ./internal/httpx/... passes
trusted-types lists exactly the names in use, no duplicatesYes: four names, four createPolicy calls in the bundle (Vue in platform-*.js, two through createTrustedTypePolicy, one in the picker chunk). No default, no 'allow-duplicates', no *bundle scan; in Chromium default, other and second policies of the three eager names are refused. Gap: S1
Pass-through policiesvue (inherent, N1) and mnema-emoji-picker (createHTML: html => html, module-private, fed only by the picker's static templates; gap S1). mnema-markdown and mnema-script-url are not pass-throughs (S2 for the latter's width)read source and minified bundle
Cross-origin, data:, blob: script URLall refusedunit tests run locally; code read
What the emoji-picker patch doesfour exact-match replacements while Vite bundles emoji-picker-element/picker.js: styles to adoptedStyleSheets, style attribute through CSSOM, parseTemplate through the policy, the Safari 13 fallback innerHTML = '' to textContent = ''read web/scripts/emojiPickerCsp.ts; the package has exactly two innerHTML assignments (picker.js:399, :415) and both are patched
Does it survive an updateYes, guarded twice: replaceOnce throws when a pattern matches zero or several times (fails vite build), and emojiPickerCsp.test.ts pins package.json and the installed version to 1.29.1, applies the patch to the installed file and asserts that no other innerHTML/outerHTML/insertAdjacentHTML/document.write/eval/new Function is leftran node --test scripts/emojiPickerCsp.test.ts scripts/serviceWorkerBuild.test.ts: 6 pass
/api/docs CSP unchangedYes, byte-identical: APIDocsContentSecurityPolicy is basePolicy, and basePolicy equals the old SPAContentSecurityPolicy of origin/main (diffed the two string literals)diff; TestAPIDocsPolicyIsTheAppPolicyWithoutTrustedTypes
Other routes weakenedNo. The only CSP changes are the two above. /api/* keeps default-src 'none'; frame-ancestors 'none'; media, emoji, link-preview and onboarding icons keep default-src 'none'; sandboxgit grep Content-Security-Policy over non-test Go files: 7 places, 2 touched
Browsers without Trusted TypesAs before: createTrustedTypePolicy returns null when globalThis.trustedTypes is missing and callers pass the plain string; the picker patch does the same; Vue does the sameunit tests "without Trusted Types in the browser"; code read

Sinks, source and built bundle

Searched web/src, web/index.html and every file of dist/ except the API docs chunk for: innerHTML, outerHTML, insertAdjacentHTML, document.write, srcdoc, createContextualFragment, parseFromString, setHTMLUnsafe, parseHTMLUnsafe, eval(, new Function, Function(, importScripts, new Worker/SharedWorker, serviceWorker.register, execCommand, createElement('script'|'iframe'), string setTimeout/setInterval, javascript:, addModule.

SinkWhereThrough a policy?
v-html (the only one)MarkdownContent.vue:146mnema-markdown, then Vue's vue
Vue static hoisting and innerHTML propplatform-*.jsvue
picker template.innerHTMLpicker-*.jsmnema-emoji-picker; rendered in Chromium under the header: 43 shadow elements, no Trusted Types violation
new Worker (media frame worker)media/guard.ts:109mnema-script-url
new Worker (noise filter worker)dfn/dfnNode.ts:133mnema-script-url
serviceWorker.register('/sw.js')pwa.ts:22mnema-script-url; in Chromium the worker became active under the header
highlight.js highlightElementtypingTarget-*.jsno, but unreachable (N3)
execCommand('copy'/'insertText'/'delete')copyText.ts, wikiEditorActions.tsnot a sink (only insertHTML is)
audioWorklet.addModulenoiseSuppressor.ts:109not a Trusted Types sink
<iframe :src> of the video cardLinkPreviewCard.vue:144src of an iframe is not a sink; no srcdoc anywhere
workers and sw.js themselvesdfnWorker-*.js, mediaFrameWorker-*.js, worklets, sw.jsself-contained IIFEs, no importScripts, no nested worker, no eval

No outerHTML, insertAdjacentHTML, document.write, srcdoc, createContextualFragment, parseFromString, eval, new Function, script element or string timer in the app bundle. For the paths not exercised locally (admin area, wiki, link previews, image lightbox, file uploads, setup assistant, offline page, service worker update flow) this static result is what I have: none of them has a sink of its own; they are plain Vue templates, and the wiki and link previews render through MarkdownContent. Firefox and WebKit were not exercised at all, by me or by CI (B1).

Chromium check, built bundle behind a local static server with the exact header: the sign-in shell renders with no violation; plain-string innerHTML, new Worker (same-origin and data:), script.src, iframe.srcdoc and DOMParser.parseFromString are refused.

staticcheck and benchmark commits

Every hunk of 6bfc3fc86 read. Behaviour-preserving:

  • Removed production helpers eraseAccount and Handler.deleteObjects: no caller left under any tag (git grep; go vet with and without -tags=integration). Their two test callers now call eraseWith(..., personalFallback) and core.DeleteObjects(...), which is what the helpers did. No reflection use.
  • Six struct conversions (PostPatch(req), ForumSettingsPatch(req), TagSpec(req), TagPatch(req), ServerNotify(req), ScheduledPatch(req)): each target type has exactly the fields the old literal copied (read all six definitions), so no extra field starts to flow.
  • Invisible characters written as escapes: compared the unquoted values of all string literals before and after in the 11 affected files with a small go/parser program: identical in every file.
  • Moved constants firefoxLinux/safariIPhone: used only in integration-tagged files of internal/auth/authn; internal/auth has its own copy. Removed authRequest and the two fixture fields: unused.
  • SA4006 fixes: viewer_track_fuzz_test.go (var at time.Time, every switch arm assigns), bot_status_integration_test.go (first two results were never read), webhooks_posting_integration_test.go (ct reassigned before use). No value that is used changed.
  • response_edges_test.go now panics with panic("deliberate") instead of a nil-map write; the test only looks for the frame name.
  • runtime.GOROOT() to go env GOROOT in the imgstrip tests: without go on the path the glob finds nothing and the test skips, as before without sources.
  • No error string changed. Build tags in the repository: integration, !integration, unix/!unix, windows/!windows; the Windows-only files were not vetted on this Mac.

3b957e456: the script logic is sound apart from B2 (allowlist can only shrink, //lint:ignore needs an entry, staticcheck.conf refused). 200187a06: clean. make bench-allocs passes locally (0 allocs/op on all four forward benchmarks), node --test scripts/bench-compare.test.mjs passes. seedCommunity was only moved to a testing.TB form.

CI commits

  • scripts/ci-dns-fallback.sh: does nothing while getent hosts answers (first statement of the loop), always ends with exit 0, has no set -e, all expansions quoted. sudo is used by the callers already (sudo tee, sudo apt-get on the neighbouring lines), all on hosted Ubuntu runners.
  • The way it is called is the problem: B1.

Commands run (scratch worktree, niced, -p 2)

CommandResult
make staticcheckexit 0 locally (warm cache); fails in CI, B2
go vet ./... and go vet -tags=integration ./...; go vet ./... in loadtest/viewerclean
go test -count=1 ./internal/httpx/...ok
make bench-allocsok, 0 allocs/op
web: npm ci, npm run lint0 errors (23 existing warnings), i18n 0 findings
web: npm run typecheckok
web: vitest on trustedTypes, markdownHtml, markdown/, dfn/, media/guard, mediaFrameWorker, noiseSuppressor, pwa, MarkdownContent*19 files, 440 tests, all pass
web: vite buildok
PR checks at 4d16f933ebackend-checks failed (B2), all e2e jobs failed (B1), others passing or pending

Left open

  • Fix B1 and B2, then let the Playwright suite run on Chromium, Firefox and WebKit: that run is the first real evidence for Trusted Types outside Chromium.
  • S1 and S2 are small and can go into the same train.

Something wrong on this page? Tell us.