Injection sinks outside templates, as data; path-sink where outside input reaches; brands a project defines #129

Merged
sionzee merged 127 commits from sinks-and-brands into main 2026-11-22 17:32:54 +01:00
Owner

Based on tests-that-cannot-fail (#128), and contains it, #127 and #126: the diff shown is this piece alone.

SAFE-TS has brands: a value made safe for one use carries a type that says so, and the framework rules demand the brand where markup or a URL is rendered (vue-v-html, vue-unsafe-url, react-dangerous-html). The same sinks reached from plain code were open, and the set of brands was fixed in the checker. Each of these passed tsc strict, safe-ts check --deny-warnings and oxlint with the preset:

el.innerHTML = user;               el.insertAdjacentHTML("beforeend", user);
link.href = user;                  location.assign(user);
el.setAttribute("onclick", user);  setTimeout(user, 10);
exec(`ls ${user}`);                await readFile(join(ROOT, name));     // in a request handler

What this adds

Sinks are data. Which member takes markup, a URL the browser may run, code, a shell command, a file path, a regular expression's source or SQL is a sinks section in the language's map and in the browser and Node packs, with a list of members considered and rejected, each with its reason. Every browser sink was shown to run script in Chromium and Firefox, and all but one in WebKit. A pack for a library declares its own (a database client's query).

One rule per kind, so each has its own level: markup-sink, url-sink, code-sink, command-sink, pattern-sink, sql-sink, brand-sink (errors) and path-sink (idiomatic, a warning). A sink accepts a constant the source shows (also built up in a let, or read from a table written in the source), a number, the sink's brand, and the forms that make one (escapeHtml, a declared sanitizer, a URL with a safe written start, pathUnder, escapeRegExp). The framework rules now judge "safe" by the same code.

The operator's input is the operator's. A path, module or command from process.argv, the environment, import.meta, a listing of such a directory, or a config file read from one is accepted where the code shows it. Past that, fromOperator(text) makes the brand and is counted as an escape hatch.

Brands a project defines. Brand<"Sql">, brandConstructor (counted as an escape hatch) and brandSinks in @evobug_com/safe-ts-std/brand: only the declared constructors make the brand, and the declared sinks accept only it. Two worked examples in the docs: an SQL fragment that can only come from a tagged template, and an id that can only come from a parser.

New in std: SafePath with pathUnder(root, ...parts), and FromOperator.

path-sink asks who can reach the code

The first version reported every unbranded string that reaches the file system. On an adopter's project that was 61 findings, and reading them showed none was injectable: every path came from configuration, the environment, the command line, or a check of the project's own. What makes a path dangerous is that something outside the program chose it, and the checker knows something close to that: which code an outside party can cause to run.

So the rule reports only in functions that are, or are called from, a handler the runtime invokes with outside data: an HTTP, HTTPS or HTTP/2 request handler, a TCP or UDP socket's data, a WebSocket message, a worker's or child process's message. Those slots are data in the Node pack (and the ws pack), each shown on the running engine to receive ../secret.txt from a client. Reach follows the existing call graph once per run, including a handler returned by a factory and a call through a function-typed field or a typed route table.

On that project: 61 findings became 2, both in its static file server on a request's path, where the name from the URL is checked by a function of the project's own that returns string. The page has a section on turning such a function into the place where the SafePath is made.

Evidence

  • Held-out cases. Of 21 sinks in my file, the 17 the design covers are reported and every safe form is silent. Receivers are resolved through their written types: an element of a typed list, a target narrowed by instanceof, a field typed with a platform class, querySelector(...)!. ||=, &&=, ??= and Object.assign(el, { innerHTML }) are assignments. On a server of my own, a read reached from a createServer handler, one behind a hand-written check, and one in a handler registered by name are reported; the same read behind a SafePath parameter, or in a tool function no handler reaches, is silent.
  • An adopter's project, as installed: 2 new pattern-sink findings, nothing else (its packs predate the sinks section). With this branch's packs: path-sink 2, code-sink 2, pattern-sink 2, url-sink 1, markup-sink 1. All were read; one is injectable, by the server a smoke script talks to.
  • Soundness corpus: four classes added and closed (code from text, a path that escapes its root in a real HTTP request, a shell command, a pattern from text). 2 of 73 escape.
  • Cost: a file that names no sink member records nothing. Per-file analysis on that project's largest entry: about 195 ms before, 210 ms after; the whole-program pass is unchanged within noise.

What turns red on upgrade

  • A function merely named sanitizeHtml is no longer trusted by react-dangerous-html: it must be DOMPurify, sanitize-html or xss imported from its package, a function whose every return is one, or declared with defineSanitizer.
  • Code that writes unbranded text into a markup, URL or code sink is an error.

Decided along the way

  • DOMParser is not a sink: the document it makes is inert in all three browsers. fetch of a built URL is not one either; where a request may go is a different question.
  • new RegExp(text) stays with unhandled-failure where that rule already reports it; pattern-sink reports what it misses (str.match(text), a handled new RegExp).
  • A line read from stdin is the operator's, so readline handlers are not outside input. A program that takes hostile lines on stdin declares that slot in a pack.
  • setAttribute(name, value) with a name whose written type cannot be a sink attribute (`aria-${string}` | `data-${string}`) leaves the value alone.

What stays unseen

  • For reach: a framework whose handlers no pack describes; a port typed with the project's own interface; a handler passed through .bind; a route picked through a value with no written type; an event name that is not a constant.
  • Nodes moved from a parsed document into the page; Object.assign(el, props) with an object not written in the call; a shell option built elsewhere.
  • Where a value came from, in general: the brand at the sink is the design, not taint tracking.
  • Not built: header and log injection, prototype pollution, request forgery. The page says what each would take.

Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.

Based on `tests-that-cannot-fail` (#128), and contains it, #127 and #126: the diff shown is this piece alone. SAFE-TS has brands: a value made safe for one use carries a type that says so, and the framework rules demand the brand where markup or a URL is rendered (`vue-v-html`, `vue-unsafe-url`, `react-dangerous-html`). The same sinks reached from plain code were open, and the set of brands was fixed in the checker. Each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint with the preset: ```ts el.innerHTML = user; el.insertAdjacentHTML("beforeend", user); link.href = user; location.assign(user); el.setAttribute("onclick", user); setTimeout(user, 10); exec(`ls ${user}`); await readFile(join(ROOT, name)); // in a request handler ``` ## What this adds **Sinks are data.** Which member takes markup, a URL the browser may run, code, a shell command, a file path, a regular expression's source or SQL is a `sinks` section in the language's map and in the browser and Node packs, with a list of members considered and rejected, each with its reason. Every browser sink was shown to run script in Chromium and Firefox, and all but one in WebKit. A pack for a library declares its own (a database client's `query`). **One rule per kind**, so each has its own level: `markup-sink`, `url-sink`, `code-sink`, `command-sink`, `pattern-sink`, `sql-sink`, `brand-sink` (errors) and `path-sink` (idiomatic, a warning). A sink accepts a constant the source shows (also built up in a `let`, or read from a table written in the source), a number, the sink's brand, and the forms that make one (`escapeHtml`, a declared sanitizer, a URL with a safe written start, `pathUnder`, `escapeRegExp`). The framework rules now judge "safe" by the same code. **The operator's input is the operator's.** A path, module or command from `process.argv`, the environment, `import.meta`, a listing of such a directory, or a config file read from one is accepted where the code shows it. Past that, `fromOperator(text)` makes the brand and is counted as an escape hatch. **Brands a project defines.** `Brand<"Sql">`, `brandConstructor` (counted as an escape hatch) and `brandSinks` in `@evobug_com/safe-ts-std/brand`: only the declared constructors make the brand, and the declared sinks accept only it. Two worked examples in the docs: an SQL fragment that can only come from a tagged template, and an id that can only come from a parser. **New in std:** `SafePath` with `pathUnder(root, ...parts)`, and `FromOperator`. ## `path-sink` asks who can reach the code The first version reported every unbranded `string` that reaches the file system. On an adopter's project that was 61 findings, and reading them showed none was injectable: every path came from configuration, the environment, the command line, or a check of the project's own. What makes a path dangerous is that something outside the program chose it, and the checker knows something close to that: which code an outside party can cause to run. So the rule reports only in functions that are, or are called from, a handler the runtime invokes with outside data: an HTTP, HTTPS or HTTP/2 request handler, a TCP or UDP socket's data, a WebSocket message, a worker's or child process's message. Those slots are data in the Node pack (and the `ws` pack), each shown on the running engine to receive `../secret.txt` from a client. Reach follows the existing call graph once per run, including a handler returned by a factory and a call through a function-typed field or a typed route table. On that project: **61 findings became 2**, both in its static file server on a request's path, where the name from the URL is checked by a function of the project's own that returns `string`. The page has a section on turning such a function into the place where the `SafePath` is made. ## Evidence - **Held-out cases.** Of 21 sinks in my file, the 17 the design covers are reported and every safe form is silent. Receivers are resolved through their written types: an element of a typed list, a target narrowed by `instanceof`, a field typed with a platform class, `querySelector(...)!`. `||=`, `&&=`, `??=` and `Object.assign(el, { innerHTML })` are assignments. On a server of my own, a read reached from a `createServer` handler, one behind a hand-written check, and one in a handler registered by name are reported; the same read behind a `SafePath` parameter, or in a tool function no handler reaches, is silent. - **An adopter's project, as installed:** 2 new `pattern-sink` findings, nothing else (its packs predate the `sinks` section). **With this branch's packs:** `path-sink` 2, `code-sink` 2, `pattern-sink` 2, `url-sink` 1, `markup-sink` 1. All were read; one is injectable, by the server a smoke script talks to. - **Soundness corpus:** four classes added and closed (code from text, a path that escapes its root in a real HTTP request, a shell command, a pattern from text). 2 of 73 escape. - **Cost:** a file that names no sink member records nothing. Per-file analysis on that project's largest entry: about 195 ms before, 210 ms after; the whole-program pass is unchanged within noise. ## What turns red on upgrade - A function merely *named* `sanitizeHtml` is no longer trusted by `react-dangerous-html`: it must be DOMPurify, `sanitize-html` or `xss` imported from its package, a function whose every `return` is one, or declared with `defineSanitizer`. - Code that writes unbranded text into a markup, URL or code sink is an error. ## Decided along the way - `DOMParser` is not a sink: the document it makes is inert in all three browsers. `fetch` of a built URL is not one either; where a request may go is a different question. - `new RegExp(text)` stays with `unhandled-failure` where that rule already reports it; `pattern-sink` reports what it misses (`str.match(text)`, a handled `new RegExp`). - A line read from stdin is the operator's, so `readline` handlers are not outside input. A program that takes hostile lines on stdin declares that slot in a pack. - `setAttribute(name, value)` with a name whose written type cannot be a sink attribute (`` `aria-${string}` | `data-${string}` ``) leaves the value alone. ## What stays unseen - For reach: a framework whose handlers no pack describes; a port typed with the project's own interface; a handler passed through `.bind`; a route picked through a value with no written type; an event name that is not a constant. - Nodes moved from a parsed document into the page; `Object.assign(el, props)` with an object not written in the call; a `shell` option built elsewhere. - Where a value came from, in general: the brand at the sink is the design, not taint tracking. - Not built: header and log injection, prototype pollution, request forgery. The page says what each would take. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Open: which members take markup, a URL that may run script, code, a shell command, a file path,
a pattern or SQL was written nowhere; std had no brand for a path and no way for a project to
declare a brand of its own.

Closes:
- `sinks` in ecmascript-api.json (eval, Function, RegExp, String#match/matchAll/search, import()),
  browser-api.json (every member that parses markup into the live document, every IDL attribute
  that reflects a URL the browser navigates to, every one that runs script, setAttribute and
  setAttributeNS by the attribute's name, execCommand("insertHTML")) and node-api.json
  (child_process, vm, worker_threads, module.register, node:sqlite, and every node:fs and
  node:fs/promises function @types/node declares with a path parameter, at each one), each with
  an `inert` list of members considered and why they aren't sinks. The packs' generators copy the
  section into safe-ts.json, and the browser pack lists the classes and globals on the way to a
  sink (Location, Window, HTMLScriptElement, `location`, ...).
- Shown on the engines: ecmascript/sinks.test.ts and feature-node/test/sinks.test.ts give each
  kind text that does more than meant (code runs, `../` leaves the directory, the shell runs a
  second command, the statement deletes every row); feature-node checks the node:fs list against
  @types/node; feature-browser/test/sinks.test.ts holds every key to lib.dom.d.ts and the pack's
  copy to the map; test/browsers/sinks.test.ts (npm run test:browsers) makes every browser sink
  run script in Chromium and Firefox (WebKit all but execCommand) and no inert member run any.
- std/path: SafePath and pathUnder(root, ...parts), with a test that what it accepts stays under
  the root on the file system and what it refuses would leave it.
- std/brand: Brand<"Name">, brandConstructor("Name", make) (a Result or Option it returns keeps
  its Err and undefined), brandSinks("Name", members). Compile-time tests in brand.check.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: `el.innerHTML = user`, `link.href = user`, `setAttribute("onclick", user)`,
`setTimeout(user)`, `new Worker(user)`, `exec(`ls ${user}`)`, `readFile(`/var/data/${user}`)`,
`text.search(user)` passed every gate; the framework rules each had their own idea of safe HTML
(react-dangerous-html trusted a function for its name); a project couldn't hold its own brands'
constructors and sinks to them.

Closes:
- Rules markup-sink, url-sink, code-sink, command-sink, path-sink (idiomatic, a warning),
  pattern-sink, sql-sink and brand-sink (sinks.rs, analyze/sinks.rs, project/sinks.rs). The
  analysis records where a value reaches what may be a sink, through every spelling the failure
  rules follow (aliases, `.call`, `.bind`, destructured and dynamic imports), and splits it into
  the parts the sink reads; the whole program resolves the member through the packs' class
  chains (and `document.createElement("a")`, a binding typed with a package's class, a receiver
  of unknown class by name for innerHTML and kin) and judges each part by its type. Constants in
  disguise found on an adopter are accepted: path.join of import.meta.dirname, an imported const
  bound to a constant (LocalAnalysis::constant_tops), process.cwd(), os.tmpdir(), a mkdtemp
  directory, new URL(c, import.meta.url), a blob: URL, a URL made from the page's own address,
  String(n), numbers and literal types. Test files' platform sinks aren't checked. eval and new
  Function are left to the preset's oxlint no-eval and no-new-func (`lint` in the map).
- vue-v-html and react-dangerous-html are judged by the same code as markup-sink (vue.rs and
  react.rs no longer decide; react's name trust is gone); both now accept a template whose parts
  are each sanitized or Html. Shapes for sinks are kept apart (FileShapes::sinks) so the other
  rules' questions are unchanged.
- Brands of your own: Brand<"Name"> is a brand to the evaluator; a brandConstructor call is a
  function returning it; brandSinks are read from every file (safe-ts check) or from the file's
  import closure (the editor); brand-constructor reports a cast, trust<Name> and a type argument
  making one, also of a brand declared in another file (LocalAnalysis::brand_aliases,
  brand_casts). brandConstructor is counted with the escape hatches (summary, --json, baseline).
- Fixtures sinks/ and brands/; sinks::tests hold the three maps' sections and the packs' copies
  together. Soundness corpus: code-from-text, path-escapes-root, shell-command-injection,
  pattern-from-text, each escaping at the starting commit, all rejected now.
- Docs: a page per rule, Libraries "Sinks", Proof types SafePath and brands of your own (an SQL
  fragment from a tagged template or a placeholder; an id from a parser), Security scope, the
  React and Vue pages, README, CHANGELOG, the migration skill, census RULE_SEE, the oxlint
  preset. Doc examples that read a path given as a string now take a SafePath.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open (review of f342d8e3): on an adopter every path, code and command finding was the input of
whoever runs the program (argv, env, a listing of a fixed directory); `let html = "<ul>"; html +=
"<li>fixed</li>"` was reported; a sink was missed on a NodeListOf item, after `instanceof`, on
`querySelector(...)!`, on a field typed with a platform class; `||=`, `&&=`, `??=` and
`Object.assign(el, { innerHTML })` were silent; every file paid for sink shapes in Sites; the
editor saw only the brandSinks of a file's import closure.

Closes:
- Path, code and command sinks accept what the operator gives where the code shows it
  (`operator_value`): process.argv and parseArgs, process.env, import.meta, __dirname, cwd/tmpdir,
  readdir/glob names for such a path, a file read from one and JSON.parse/parseJson of it, joined
  with path.join, new URL, templates; through consts, lets, destructuring, for...of items, callback
  items, and functions of the file (and imported ones, `constant_tops` as `name()`) whose returns
  are. std/operator: FromOperator and fromOperator(text) for the rest, counted with the escape
  hatches (summary, --json, baseline).
- A let whose initializer and every =, +=, ||=, &&=, ??= in its own function are accepted is
  accepted (`let_values`); an entry of a table written out (`Object.entries(TABLE)`, members),
  also imported (`constant_tops` judges object and array literals).
- Receivers: the analysis records the receivers' chain Value of a member site; the whole program
  reads its written type (aliases, Mut, Option, `| undefined`, object types' and classes' fields,
  items of arrays, NodeListOf, tuples, Promise) to a global or package class; `instanceof` in an
  enclosing if, ?: or && names the class; an origin that leads to no described class falls back to
  the type, then to `anyReceiver`. tests/sink_receivers.rs: 18 receiver forms and a field, each
  with three sinks, against the plain form.
- ||=, &&=, ??= are sets; `Object.assign(target, { member: v })` sets each written member (an
  object not written in the call isn't followed).
- Cost: Sites no longer records anything for sinks; a site is recorded only where the member's
  name is one some map, pack or brandSinks lists (`sinks::SinkNames`, part of the analysis cache
  key), and the shapes its parts ask for are computed after the walk (`shape::shapes_at`). A
  string-typed receiver isn't followed; a function argument asks for nothing.
  sinks::cost tests a file without a sink name records nothing.
- brandSinks calls are found by listing the project (`Project::brand_sink_files`, refreshed every
  few seconds like global_type_files), in the editor as in safe-ts check; the brands fixture has a
  file using a declared sink without importing the brand's module, held by the editor-versus-CLI
  test.
- Docs: path-sink (the operator's input, FromOperator, migrating a resolver of your own to
  pathUnder), proof types (FromOperator), markup-sink (let, tables, the ways of writing a sink and
  its receiver), code-sink and command-sink, libraries, std helpers, README, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
path-sink now reports only in code a handler the runtime calls with outside data reaches: the
handler itself (written in place, named, or made by a function) and what it calls, across files,
computed once per `safe-ts check` from the files' summaries (HandlerSite, CallSite). Everywhere
else (a script's top level, a build tool, start-up code) it is silent. It is a program rule now:
the editor and the lint plugin don't report it.

The slots are data: `sinks.handlers` in node-api.json (http, https, http2, net, tls, dgram,
readline, the `message` of workers, ports, child processes and process) and in the ws pack, with
tests on the running Node and ws that each slot exists, at an event @types/node declares, and
receives what a client, a peer, a line or a message sent. A framework's pack declares its own.
node:readline createInterface and worker_threads parentPort have their classes in the pack.

setAttribute(name, value) with a name the source doesn't show takes the kind its written type
allows: a union of literals, or template literal types whose start no sink name can follow.

On an adopter, 61 path findings became 5. The soundness class path-escapes-root now serves a
name from an HTTP request; both variants escape on the reference and are rejected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts, all kept from both sides: the packs' `sinks` and `acquires` sections (the generators
and safe-ts.json, regenerated with them), the pass's fields and its set-up (reach is computed
after `sentinel_askers` is set), `test:browsers`, the sidebar, the CHANGELOG, the libraries
guide's Sinks and "What must be released" sections, and the migration skill's sections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A call the analysis can't tie to a body is followed through the declared type it goes through
(resolve_slot) to every function the program puts into that type: declared with it, given where
it is expected (object members, array items, arguments), and the methods of classes given as, or
implementing, an interface. The index is built once, the first time reach needs it. A call's
result is followed by the callee's declared function type (`deps.api()` with `api: () =>
Handler`). Fixture rows for each; a route picked through an untyped value and a port typed with
the project's own type stay documented blind spots.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts, all kept from both sides: the rule list, the CLI's escape-hatch line (skipped tests,
brandConstructor and fromOperator calls), the soundness classes (sinks and tests), the README's
known gaps and the CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
path-sink page: a neutral name for the example's resolver
Some checks failed
Benchmarks / bench (pull_request) Has been cancelled
Tests / test (pull_request) Has been cancelled
8cbe83193f
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Merge the base: main now has the pass's speed work and the control-flow analyses
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m7s
Tests / test (pull_request) Successful in 8m48s
acee8bf341
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from tests-that-cannot-fail to main 2026-11-22 17:32:22 +01:00
Merge main: the piece below has landed
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
72a7c9b034
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch sinks-and-brands 2026-11-22 17:32:54 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!129
No description provided.