Files
AutistMask/tests/buildForbiddenInputs.test.js
sneak c8d758f4eb
All checks were successful
check / check (push) Successful in 54s
e2e / e2e-chrome (push) Successful in 2m1s
e2e / e2e-firefox (push) Successful in 52s
harden: make the background physically unable to read the shared state singleton (closes #324)
Five defects traced to one fact: src/background/index.js read and wrote the
module-level `state` singleton in src/shared/state.js, which the MV3 service
worker never populates and which answered an unpopulated read out of
DEFAULT_STATE in silence. Every previous fix added a loadState() before the
access, and that is what produced the fifth: a load detaches the objects an
in-flight handler is holding.

So the reachability goes rather than a sixth call site.

The background now has its own storage layer, src/background/state.js:
getState() is a detached, normalized per-call read, and updateState() is a
queued read-modify-write whose read is one storage round trip ahead of its
write. Nothing in the background holds an in-memory copy of the profile. The
write is the whole record, and updateState()'s header now names what that costs:
a popup write landing inside that one-round-trip window is reverted.

- Every handler takes one snapshot and answers from it, including the address
  it names: activeAddressOf(s) replaced a second, later storage read that
  could disagree with the first.
- wallet_switchEthereumChain applies applyChainSwitchFields() (split out of
  chainSwitch.js, which keeps the singleton path for the popup) inside
  updateState() instead of calling onChainSwitch() on the singleton.
- The remembered site decision is a read-modify-write, not a load-mutate-save
  around a prompt the user takes seconds to answer.
- backgroundRefresh() refreshes a private copy of the wallets and applies the
  balances that came back by address, so it never publishes an object other
  in-flight work holds, and a wallet added or deleted during the round trip
  survives its write.
- The transaction attempt takes its chain id and its endpoint from the same
  snapshot. They used to come from different moments, so a chain switch
  committed in between moved the endpoint under an artifact already verified
  against the old chain.

getProvider(rpcUrl, networkId) now REQUIRES the network id and validates it
against networks.js. That closes the cold-worker wrong-chain send at its shape
rather than at one call site: the hint used to default to currentNetwork() off
the unpopulated singleton, so the endpoint was the user's chain and ethers
fixed chainId at 0x1, and the wallet's own verifySignedTx then refused every
non-mainnet dApp send. refreshBalances(), lookupTokenInfo(), scanForAddresses()
and resolveEnsName() carry the id through; balances.js no longer requires
state.js at all.

The prohibition is enforced mechanically, not by review, and it is enforced by
the bundler rather than by a guess at what the bundler does. The table of
modules an entry point's bundle may not contain lives in
script/lib/forbiddenBundleInputs.js — one copy, read by both layers that act on
it — and build.js's assertNoForbiddenInputs() fails the build when esbuild's
metafile reports src/shared/state.js as an input of a background bundle, naming
the import chain from the metafile's own graph. That is the resolution the
shipped bundle was built from, so no specifier syntax, no hop and no resolution
rule can slip past it; Dockerfile:42 runs make build, so it holds in CI.

A background entry point the table does not name fails the build as well. The
five defects were accidents, and so is adding a second worker entry point
without knowing that a table elsewhere needs a line for it: entry points under
src/background/ are prohibited by default and must be listed, rather than
protected only when someone remembers. That prefix is the build's only notion of
"the background", and eslint.config.js scopes the lint rule from the same
constant so the two layers cannot disagree about it.

Every way the table can rot is a failure rather than a quiet pass: a key no
bundled entry point matched, a listed module this build bundled nowhere, and an
entry that lists no modules. The second is what makes a rename of
src/shared/state.js loud instead of silently disarming the check, and it is
stronger than an existsSync() because it also fails when the module is still
there but has dropped out of every bundle. The third is refused at require time,
where the table is defined, because an empty list also empties the lint rule's
forbidden set — one character, and a plain require of the singleton in the
worker was green in make test, make lint and make build alike.

An entry is recorded as checked only once its bundle's inputs are in hand. It
used to be recorded before the output lookup that produces them, so an early
return past that point left both halves of the guarantee satisfied by a bundle
nothing had examined.

What the assertion does NOT cover is a COPY of the singleton at another path: it
is keyed by path, so a copy builds and lints clean. That is stated where the
table lives, with what the residual actually is — a copy carries the singleton's
own guard, so an unloaded read is a loud StateNotLoadedError and defects 1-3
cannot recur silently, but a copy carries loadState() too, so defects 4 and 5
(a stale read several awaits after a load, a load detaching objects an in-flight
handler is mutating) would recur over it in silence.

make check does not run make build, so the assertion is unit tested against
synthetic metafiles in tests/buildForbiddenInputs.test.js: build.js runs its
build() only as a program now and exports the checks. Executing a check in CI
is not testing it — without that file, inverting the condition leaves every
check in this repo green with the singleton back in the worker. Each vacuous
pass above has a case, including the output lookup that finds nothing, the empty
list, the unlisted second entry point, and recordBundledInputs() itself, which
every other case used to hand-seed.

A custom ESLint rule walks the CommonJS require graph from every src/background/
file and reports the same thing in the editor, before a full bundle. It reads
the same table, and it matches specifiers textually, so it is best-effort fast
feedback and not the guarantee — two earlier revisions of it shipped holes (a
template literal, a dynamic import(), a comment inside the call, a directory
resolved through package.json main). Those are covered now and pinned by
tests/backgroundStateLintRule.test.js. Two shapes it does not report are pinned
there as asserted non-reports, so the header's list of its bounds is measured
rather than claimed: a computed specifier (require("../shared/" + "state"),
which esbuild constant-folds into the bundle) and a symlink to the module
(esbuild reports the real path). Each is make lint exit 0 and make build exit 2.

Reading a persisted field of the singleton before any load now throws
StateNotLoadedError instead of serving DEFAULT_STATE.

Test stubs: chrome.storage.local is a serialization boundary, and eight files
stubbed it with an aliasing get, so the object a module held and the object
"storage" held were one object — an assertion could pass on a build that never
wrote anything. Every test that drives real persistence now goes through
tests/support/storageStub.js, which structured-clones in both directions.

closes #320
2026-08-23 15:38:48 +00:00

367 lines
14 KiB
JavaScript

// build.js's FORBIDDEN_INPUTS assertion — the mechanical guarantee that the
// MV3 background bundle cannot contain src/shared/state.js
// (https://git.eeqj.de/sneak/AutistMask/issues/324).
//
// Why this file exists: `make check` does not run `make build`. CI executes
// the assertion (Dockerfile runs `make build`), but executing is not testing —
// invert its condition, or make the table lookup always come back undefined,
// and every check in this repo stays green while the singleton walks back into
// the worker. Five defects, one destroyed wallet, and the whole argument for
// the scoped loud-read guard rest on this assertion, so it is pinned here.
//
// The subject is build.js's exported helpers plus the table's own
// well-formedness check, driven against SYNTHETIC metafiles in esbuild's
// shape. Nothing here shells out to a build or writes dist/: the assertion's
// job is to read a metafile correctly, and a metafile is data. That the real
// shapes reach it is the build's own business and is measured in the PR that
// introduced it.
//
// Every vacuous pass this guarantee has been found to have is pinned below,
// because each one was a way for `make check`, `make lint` and `make build` to
// be green over a background bundle containing the singleton: a stale key, a
// stale module, an entry that lists no modules, an entry recorded as checked
// before its bundle was in hand, and a background entry point nobody added to
// the table.
//
// Paths are absolute on the way in, because the helpers normalize whatever
// esbuild gave them to repo-relative and this file should not depend on the
// working directory jest was started from.
const path = require("path");
const {
importChain,
newForbiddenRecord,
recordBundledInputs,
assertNoForbiddenInputs,
assertForbiddenTableCovered,
} = require("../build");
const {
BACKGROUND_ENTRY_PREFIX,
FORBIDDEN_INPUTS,
assertTableWellFormed,
} = require("../script/lib/forbiddenBundleInputs");
const ROOT = path.resolve(__dirname, "..");
const abs = (p) => path.join(ROOT, p);
const ENTRY = "src/background/index.js";
const OUT = "dist/chrome/src/background/index.js";
const STATE = "src/shared/state.js";
const HOP = "src/shared/chainSwitchFields.js";
const SECOND = "src/background/worker2.js";
const SECOND_OUT = "dist/chrome/src/background/worker2.js";
const POPUP = "src/popup/index.js";
const POPUP_OUT = "dist/chrome/src/popup/index.js";
// The real table's shape: entry point -> modules its bundle may not contain.
const TABLE = { [ENTRY]: [STATE] };
// A metafile as esbuild emits one: `outputs[out].inputs` is the flat list of
// every input that contributed to that output, and `inputs[file].imports` is
// the edge list, which is what the chain walk follows.
function metafile({ outputs = {}, imports = {} } = {}) {
return {
outputs: Object.fromEntries(
Object.entries(outputs).map(([out, inputs]) => [
abs(out),
{
inputs: Object.fromEntries(
inputs.map((input) => [
abs(input),
{ bytesInOutput: 1 },
]),
),
},
]),
),
inputs: Object.fromEntries(
Object.entries(imports).map(([file, targets]) => [
abs(file),
{ imports: targets.map((target) => ({ path: abs(target) })) },
]),
),
};
}
function check(mf, table = TABLE, record = newForbiddenRecord()) {
recordBundledInputs(mf, record);
assertNoForbiddenInputs(abs(ENTRY), abs(OUT), mf, record, table);
return record;
}
describe("assertNoForbiddenInputs()", () => {
test("a forbidden module in the bundle fails, naming the import chain", () => {
const mf = metafile({
outputs: { [OUT]: [ENTRY, HOP, STATE] },
imports: {
[ENTRY]: [HOP],
[HOP]: [STATE],
},
});
expect(() => check(mf)).toThrow(
`${OUT} bundles ${STATE}, which ${ENTRY} must not reach: ` +
`${ENTRY} -> ${HOP} -> ${STATE}.`,
);
});
test("a bundle without the forbidden module passes, and is recorded as checked", () => {
const mf = metafile({
outputs: { [OUT]: [ENTRY, HOP, "src/background/state.js"] },
imports: { [ENTRY]: [HOP, "src/background/state.js"] },
});
const record = check(mf);
expect([...record.entriesChecked]).toEqual([ENTRY]);
expect(record.bundledInputs.has(STATE)).toBe(false);
});
test("the failure still names the bundle when no import chain can be shown", () => {
// esbuild resolves `import("../shared/" + variable)` as a glob: the
// module is an input of the output, but no single edge leads to it.
// The message must degrade to no chain rather than crash.
const mf = metafile({
outputs: { [OUT]: [ENTRY, STATE] },
imports: { [ENTRY]: [] },
});
expect(() => check(mf)).toThrow(
`${OUT} bundles ${STATE}, which ${ENTRY} must not reach.`,
);
});
// The lookup this covers is the fragile step in the whole assertion:
// repoRelative() resolves against process.cwd() and esbuild's output keys
// are cwd-relative, so a change to where the build runs from, or to
// outfile vs outdir, makes it miss. It must be loud, and the entry must
// NOT already be marked checked when it does — otherwise a later edit
// turning this throw into an early return leaves both halves of the
// guarantee satisfied by a bundle nothing looked at.
test("an output esbuild did not report fails, and records nothing as checked", () => {
const mf = metafile({
outputs: { "dist/chrome/src/background/renamed.js": [ENTRY] },
imports: { [ENTRY]: [] },
});
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
expect(() =>
assertNoForbiddenInputs(abs(ENTRY), abs(OUT), mf, record, TABLE),
).toThrow(`esbuild reported no metafile output for ${OUT}`);
expect([...record.entriesChecked]).toEqual([]);
// So even if that throw became `return`, the coverage half catches it.
record.bundledInputs.add(STATE);
expect(() => assertForbiddenTableCovered(record, TABLE)).toThrow(
`${ENTRY} is listed in FORBIDDEN_INPUTS but was not bundled`,
);
});
});
// Finding from the fifth review of this change: adding a second worker entry
// point is exactly the accident this guarantee exists for, and the person
// adding one has no reason to know a table elsewhere needs a line. So the
// default for the background directory is protected, not unprotected.
describe("background entry points are protected by default", () => {
test("a bundled background entry point with no line in the table fails", () => {
const mf = metafile({
outputs: { [SECOND_OUT]: [SECOND, STATE] },
imports: { [SECOND]: [STATE] },
});
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
expect(() =>
assertNoForbiddenInputs(
abs(SECOND),
abs(SECOND_OUT),
mf,
record,
TABLE,
),
).toThrow(
`${SECOND} is a background entry point with no line in ` +
`FORBIDDEN_INPUTS`,
);
});
test("an entry point outside the background directory needs no line", () => {
// The popup legitimately bundles the singleton; that is its model.
const mf = metafile({
outputs: { [POPUP_OUT]: [POPUP, STATE] },
imports: { [POPUP]: [STATE] },
});
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
expect(() =>
assertNoForbiddenInputs(
abs(POPUP),
abs(POPUP_OUT),
mf,
record,
TABLE,
),
).not.toThrow();
expect([...record.entriesChecked]).toEqual([]);
});
test("the prefix is the one the lint rule is scoped to", () => {
expect(BACKGROUND_ENTRY_PREFIX).toBe("src/background/");
expect(SECOND.startsWith(BACKGROUND_ENTRY_PREFIX)).toBe(true);
expect(POPUP.startsWith(BACKGROUND_ENTRY_PREFIX)).toBe(false);
});
});
describe("recordBundledInputs()", () => {
// The sole data source for the module half of the anti-rot check, and
// every other case here hand-seeds what it produces. Driven for real,
// across two outputs, and then handed straight to the check that reads it.
test("records every input of every output, satisfying the module half", () => {
const mf = metafile({
outputs: {
[OUT]: [ENTRY, HOP],
[POPUP_OUT]: [POPUP, STATE],
},
imports: { [ENTRY]: [HOP], [POPUP]: [STATE] },
});
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
expect([...record.bundledInputs].sort()).toEqual(
[ENTRY, HOP, POPUP, STATE].sort(),
);
// Nothing hand-seeded: the covered check passes on what the recorder
// actually collected, so a recorder that collects nothing fails here.
assertNoForbiddenInputs(abs(ENTRY), abs(OUT), mf, record, TABLE);
expect(() => assertForbiddenTableCovered(record, TABLE)).not.toThrow();
});
});
describe("importChain()", () => {
test("terminates on a cyclic input graph, and still finds the module", () => {
const mf = metafile({
imports: {
[ENTRY]: [HOP],
[HOP]: ["src/shared/log.js"],
// The cycle: log <-> hop, with the target one hop past it.
"src/shared/log.js": [HOP, STATE],
},
});
expect(importChain(mf, abs(ENTRY), STATE)).toEqual([
ENTRY,
HOP,
"src/shared/log.js",
STATE,
]);
});
test("terminates and returns null when a cycle cannot reach the module", () => {
const mf = metafile({
imports: {
[ENTRY]: [HOP],
[HOP]: ["src/shared/log.js"],
"src/shared/log.js": [HOP, ENTRY],
},
});
expect(importChain(mf, abs(ENTRY), STATE)).toBeNull();
});
});
describe("assertForbiddenTableCovered()", () => {
test("the shipped table is satisfied by a build that checked it", () => {
const record = newForbiddenRecord();
record.entriesChecked.add(ENTRY);
// The popup bundle is what legitimately contains the singleton.
record.bundledInputs.add(STATE);
expect(() => assertForbiddenTableCovered(record, TABLE)).not.toThrow();
});
// The build this drives bundles the popup and no background entry point,
// because a stale key AND a bundled background entry point is now the
// stronger failure above — the entry point that is there but unlisted is
// reported by name, before the end of the build. This case is the rot that
// is left after that one: a key naming something this build never bundled.
test("a key no bundled entry point matched fails", () => {
const mf = metafile({
outputs: { [POPUP_OUT]: [POPUP] },
imports: { [POPUP]: [] },
});
const stale = { "src/background/renamed.js": [STATE] };
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
assertNoForbiddenInputs(abs(POPUP), abs(POPUP_OUT), mf, record, stale);
record.bundledInputs.add(STATE);
expect(() => assertForbiddenTableCovered(record, stale)).toThrow(
"src/background/renamed.js is listed in FORBIDDEN_INPUTS but was" +
" not bundled, so nothing checked it",
);
});
test("a forbidden module this build bundled nowhere fails", () => {
// The other half of the same rot: renaming or moving the singleton
// leaves a table that names a path nothing resolves to any more, and
// every bundle then passes it vacuously.
const mf = metafile({
outputs: { [OUT]: [ENTRY] },
imports: { [ENTRY]: [] },
});
const stale = { [ENTRY]: ["src/shared/stateRenamed.js"] };
const record = check(mf, stale);
record.bundledInputs.add(STATE);
expect(() => assertForbiddenTableCovered(record, stale)).toThrow(
"src/shared/stateRenamed.js is listed in FORBIDDEN_INPUTS for" +
` ${ENTRY}, but this build bundled it nowhere`,
);
});
// The third rot, and the worst of the three: an entry with an empty list
// is checked, is bundled, names no module that could be missing, and
// prohibits nothing — in BOTH layers at once, since the rule's forbidden
// set is Object.values(table).flat().
test("an entry that lists no modules fails", () => {
const mf = metafile({
outputs: { [OUT]: [ENTRY, STATE] },
imports: { [ENTRY]: [STATE] },
});
const empty = { [ENTRY]: [] };
const record = newForbiddenRecord();
recordBundledInputs(mf, record);
assertNoForbiddenInputs(abs(ENTRY), abs(OUT), mf, record, empty);
expect(() => assertForbiddenTableCovered(record, empty)).toThrow(
`FORBIDDEN_INPUTS["${ENTRY}"] lists no modules`,
);
});
});
describe("assertTableWellFormed()", () => {
// Runs at require time on the shipped table, in script/lib/
// forbiddenBundleInputs.js, so an empty list fails the lint run as well as
// the build — the build's own re-check cannot help a layer that never
// reaches the build.
test("the shipped table is well formed", () => {
expect(() => assertTableWellFormed(FORBIDDEN_INPUTS)).not.toThrow();
expect(Object.entries(FORBIDDEN_INPUTS).length).toBeGreaterThan(0);
});
test("an entry that lists no modules fails, naming the entry", () => {
expect(() => assertTableWellFormed({ [ENTRY]: [] })).toThrow(
`FORBIDDEN_INPUTS["${ENTRY}"] lists no modules`,
);
});
test("a table with no entries at all fails", () => {
expect(() => assertTableWellFormed({})).toThrow(
"FORBIDDEN_INPUTS is empty",
);
});
});