Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test: make the provider mirror readers fail closed on a shape they can't account for (#5673)
Adam Eivy94d117d055e4
diff --git a/server/lib/README.md b/server/lib/README.mdindex ba8957befc..ce2c53d948 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -491,7 +491,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. || `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. |-| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), `compareDeclaration(serverSrc, clientSrc, name)`, and `compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName?)` (for a regex spelled as a `new RegExp([…].join('|'), 'i')` array on one side and an inline `/…/i` literal on the other — compares what it matches, not how it is typeset). Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |+| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), `compareDeclaration(serverSrc, clientSrc, name)`, and `compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName?)` / `regexAlternationSource(declText)` (for a regex spelled as a `new RegExp([…].join('|'), 'i')` array on one side and an inline `/…/i` literal on the other — compares what it matches, not how it is typeset, and returns `null` rather than a partial read on any shape it can't decode). Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. || `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. || `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). |diff --git a/server/lib/mirrorParity.js b/server/lib/mirrorParity.jsindex b3b97a7c80..12688d5313 100644--- a/server/lib/mirrorParity.js+++ b/server/lib/mirrorParity.js@@ -118,37 +118,99 @@ export function compareDeclaration(serverSrc, clientSrc, name) {};}-// A single-quoted JS string literal, escapes included, as written in source.-const STRING_LITERAL_RE = /'((?:[^'\\]|\\.)*)'/g;-// `new RegExp([ 'a', 'b' ].join('|'), 'i')` — the multi-line, per-alternative-// array form the server files use so each alternative can carry its own comment.-const ARRAY_FORM_RE = /new RegExp\(\s*\[(.*)\]\.join\('\|'\)\s*,\s*'i'\s*\)/;-// A `/…/i` regex literal, terminated by the statement's `;` or a `.test(` call.-// Greedy on purpose: `[-_/:]` puts an unescaped `/` mid-pattern, so a lazy walk-// would stop inside a character class.-const REGEX_LITERAL_RE = /\/(.*)\/i(?=\.test\(|;)/;+// One single-quoted JS string literal at the head of the remaining array body,+// plus its trailing separator.+const NEXT_STRING_LITERAL_RE = /^'((?:[^'\\]|\\.)*)'\s*(?:,\s*)?/;+// Each accepted spelling of a mirrored capability regex, anchored to the WHOLE+// normalized declaration. Anchoring is what makes an unrecognized shape fail+// closed: a search-anywhere pattern would happily read a decoy array out of a+// declaration that assigns something else entirely, and report the mirror as+// intact. Group 1 is the alternation body in every one of them.+//+// 1. `const NAME = new RegExp([ 'a', 'b' ].join('|'), 'i');` — the server's+// array form, so each alternative can carry its own comment;+// 2. `const NAME = /…/i;` — a plain literal;+// 3. `export const isX = (id) => <guards> && /…/i.test(id);` — the browser's+// predicate form, where the literal is inlined at the end of a guard chain.+const DECLARATION_FORMS = [+ /^(?:export\s+)?const\s+\w+\s*=\s*new RegExp\(\s*\[(.*)\]\s*\.join\('\|'\)\s*,\s*'i'\s*\)\s*;$/,+ // Greedy on purpose: `[-_/:]` puts an unescaped `/` mid-pattern, so a lazy+ // walk would end the literal inside a character class.+ /^(?:export\s+)?const\s+\w+\s*=\s*\/(.*)\/i\s*;$/,+ /^(?:export\s+)?const\s+\w+\s*=\s*\(\w+\)\s*=>\s*(?:[^/]*&&\s*)?\/(.*)\/i\.test\(\w+\)\s*;$/,+];+// Only the first form's body is a list of alternatives; the other two capture+// the finished pattern.+const [ARRAY_FORM_RE] = DECLARATION_FORMS;/**- * The alternation source of a capability regex, whichever of the two forms the- * declaration is typeset in — the array form above, or a plain `/…/i` literal.+ * The regex fragment a single-quoted source literal denotes, or null when it+ * uses an escape this reader cannot decode by inspection.+ *+ * Only `\\` (a backslash the regex engine will actually see, which is how every+ * alternative spells `\d` / `\.`) and `\'` are decodable here. `\x2e`, `\u002e`+ * and `\n` all denote something OTHER than their own text — `'\x2e'` is `.`,+ * which matches ANY character — so copying them through verbatim would let a+ * client literal that means something different compare equal. These guards+ * exist to catch drift, so an unreadable literal fails CLOSED rather than+ * being guessed at.+ */+function decodeRegexFragmentLiteral(body) {+ let out = '';+ for (let i = 0; i < body.length; i++) {+ const ch = body[i];+ if (ch !== '\\') {+ out += ch;+ continue;+ }+ const escaped = body[i + 1];+ if (escaped !== '\\' && escaped !== "'") return null;+ out += escaped;+ i++;+ }+ return out;+}++/**+ * Every alternative in an array body, or null when the body holds anything+ * other than a comma-separated run of decodable string literals.+ *+ * Failing closed on the leftovers is the point: a `[...SHARED, 'extra']` or a+ * `[NAMED_FRAGMENT]` element read by a scan-for-literals pass would silently+ * vanish from the comparison, and the mirror it is supposed to pin would drift+ * green.+ */+function parseAlternativeList(body) {+ const alternatives = [];+ let rest = body.trim();+ while (rest.length > 0) {+ const match = NEXT_STRING_LITERAL_RE.exec(rest);+ if (!match) return null;+ const decoded = decodeRegexFragmentLiteral(match[1]);+ if (decoded === null) return null;+ alternatives.push(decoded);+ rest = rest.slice(match[0].length);+ }+ return alternatives;+}++/**+ * The alternation source of a capability regex, whichever of the accepted+ * spellings above the declaration is typeset in.** `/` is normalized (an escaped `\/` and a bare `/` mean the same thing to the* engine, and only one of them is legal inside a literal outside a character* class), so the two sides may differ in slash escaping but not in what they- * accept. Returns null when the declaration is neither form.+ * accept. Returns null for any shape not in `DECLARATION_FORMS` — a mirror the+ * reader cannot fully account for must fail its guard, not skip past it.*/export function regexAlternationSource(declText) {if (declText == null) return null;const norm = stripCommentsAndNormalize(declText);- const array = ARRAY_FORM_RE.exec(norm);- const source = array- ? [...array[1].matchAll(STRING_LITERAL_RE)]- // Source text → string VALUE: `'llama-?3\\.[1-9]'` is the regex fragment- // `llama-?3\.[1-9]`. Comparing the raw literals instead would report a- // divergence on every escaped metacharacter.- .map(([, body]) => body.replace(/\\(.)/g, '$1'))- .join('|')- : REGEX_LITERAL_RE.exec(norm)?.[1] ?? null;+ const form = DECLARATION_FORMS.find((re) => re.test(norm));+ if (!form) return null;+ const [, body] = form.exec(norm);+ const source = form === ARRAY_FORM_RE ? parseAlternativeList(body)?.join('|') ?? null : body;return source == null ? null : source.replace(/\\\//g, '/');}diff --git a/server/lib/mirrorParity.test.js b/server/lib/mirrorParity.test.jsindex d890ee0f37..8a8199c32a 100644--- a/server/lib/mirrorParity.test.js+++ b/server/lib/mirrorParity.test.js@@ -4,6 +4,7 @@ import {extractDeclaration,compareDeclaration,compareRegexDeclaration,+ regexAlternationSource,} from './mirrorParity.js';describe('stripCommentsAndNormalize', () => {@@ -130,3 +131,37 @@ describe('compareRegexDeclaration', () => {expect(compareRegexDeclaration(server, 'const TOOL_USE_RE = 42;', 'TOOL_USE_RE').match).toBe(false);});});++describe('regexAlternationSource fails closed', () => {+ // A scan-for-literals pass would silently DROP the non-literal element and+ // report the surviving alternatives as the whole pattern — a mirror that has+ // genuinely diverged then compares equal. Refuse the array instead.+ it('refuses an array holding anything but string literals', () => {+ expect(regexAlternationSource("const RE = new RegExp(['a', 'b'].join('|'), 'i');")).toBe('a|b');+ expect(regexAlternationSource("const RE = new RegExp(['a', SHARED].join('|'), 'i');")).toBeNull();+ expect(regexAlternationSource("const RE = new RegExp([...SHARED, 'b'].join('|'), 'i');")).toBeNull();+ });++ // `'\\x2e'` is the single character `.`, which matches ANYTHING — copying the+ // escape through as the text `x2e` would compare equal to a client `/x2e/i`+ // that means something entirely different.+ it('refuses an escape it cannot decode by inspection', () => {+ expect(regexAlternationSource("const RE = new RegExp(['a\\\\.b'].join('|'), 'i');")).toBe('a\\.b');+ expect(regexAlternationSource("const RE = new RegExp(['\\x2e'].join('|'), 'i');")).toBeNull();+ expect(regexAlternationSource("const RE = new RegExp(['\\n'].join('|'), 'i');")).toBeNull();+ });++ // A search-anywhere read would find the array and report the mirror intact+ // while the declaration assigns something else entirely.+ it('refuses a declaration that merely CONTAINS a recognizable form', () => {+ const array = "new RegExp(['a', 'b'].join('|'), 'i')";+ expect(regexAlternationSource(`const RE = ${array};`)).toBe('a|b');+ expect(regexAlternationSource(`const RE = FLAG ? ${array} : OTHER_RE;`)).toBeNull();+ expect(regexAlternationSource(`const RE = widen(${array});`)).toBeNull();+ });++ it('returns null for a declaration that is neither supported form', () => {+ expect(regexAlternationSource(null)).toBeNull();+ expect(regexAlternationSource('const RE = buildPattern();')).toBeNull();+ });+});diff --git a/server/lib/providerGateways.parity.test.js b/server/lib/providerGateways.parity.test.jsindex 0ce9bd0974..82f8c0aa44 100644--- a/server/lib/providerGateways.parity.test.js+++ b/server/lib/providerGateways.parity.test.js@@ -39,19 +39,64 @@ const pickClientFields = (row) => Object.fromEntries(CLIENT_FIELDS.filter((field) => row[field] !== undefined).map((field) => [field, row[field]]),);+// The whole normalized declaration, anchored: `export const PROVIDER_GATEWAYS =+// Object.freeze([ … ]);`. Anchoring is what makes an unrecognized shape fail+// closed — a scan for `{…}` anywhere in the declaration would keep reading the+// old row literals out of a table that had been wrapped in a transform, and+// report a registry that no longer exists as intact.+const TABLE_RE = /^(?:export\s+)?const\s+PROVIDER_GATEWAYS\s*=\s*Object\.freeze\(\s*\[(.*)\]\s*\)\s*;$/;+// One `Object.freeze({ … })` row at the head of the remaining array body, plus+// its trailing separator.+const NEXT_ROW_RE = /^Object\.freeze\(\s*\{([^{}]*)\}\s*\)\s*(?:,\s*)?/;+// One `key: 'value'` property at the head of the remaining row body, plus its+// trailing separator. Escapes are rejected outright — no gateway field has one,+// and decoding them by inspection is how a parser starts guessing.+const NEXT_ROW_FIELD_RE = /^(\w+)\s*:\s*'([^'\\]*)'\s*(?:,\s*)?/;++/**+ * Consume `text` with `nextRe` until nothing is left, collecting what each+ * match yields — or null the moment a leftover doesn't match.+ *+ * Failing closed on the leftover is the whole point: a `{ id: 'x', ...overrides }`+ * row, or a table wrapped in a helper, read by a scan-for-what-I-recognize pass+ * would compare equal to the static shape it stopped being, and the drift this+ * guard exists to catch would pass green.+ */+function consumeAll(text, nextRe, valueOf) {+ const collected = [];+ let rest = text.trim();+ while (rest.length > 0) {+ const match = nextRe.exec(rest);+ if (!match) return null;+ const value = valueOf(match, collected);+ if (value === null) return null;+ collected.push(value);+ rest = rest.slice(match[0].length);+ }+ return collected;+}++/** One registry row as a plain object, or null when it is not a static table. */+function parseGatewayRow(body) {+ const fields = consumeAll(body, NEXT_ROW_FIELD_RE, ([, key, value], seen) =>+ (seen.some(([existing]) => existing === key) ? null : [key, value]));+ return fields && Object.fromEntries(fields);+}+/**- * The client registry's rows, parsed from source. Each row is a flat- * `Object.freeze({ key: 'value', … })` with no nested braces, so a- * brace-delimited split over the comment-stripped declaration is enough — and- * anything more structural would mean importing the module, which is the thing- * this file exists to avoid.+ * A registry declaration's rows, or null when it — or any row in it — is no+ * longer a flat run of static literals. Anything more structural would mean+ * importing the module, which is the thing this file exists to avoid.*/+function parseGatewayTable(declaration) {+ const table = TABLE_RE.exec(stripCommentsAndNormalize(declaration));+ return table && consumeAll(table[1], NEXT_ROW_RE, ([, body]) => parseGatewayRow(body));+}++/** `parseGatewayTable` over the browser copy's `PROVIDER_GATEWAYS`. */function parseClientGatewayRows() {const declaration = extractDeclaration(readFileSync(CLIENT_PATH, 'utf8'), 'PROVIDER_GATEWAYS');- if (declaration == null) return null;- return [...stripCommentsAndNormalize(declaration).matchAll(/\{([^{}]*)\}/g)].map(([, body]) =>- Object.fromEntries([...body.matchAll(/(\w+):\s*'([^']*)'/g)].map(([, key, value]) => [key, value])),- );+ return declaration == null ? null : parseGatewayTable(declaration);}describe('providerGateways ↔ aiToolkit/internal/gateways parity', () => {@@ -78,10 +123,33 @@ describe('providerGateways ↔ client/src/utils/providers.js parity', () => {const clientRows = parseClientGatewayRows();it('the client declares a parseable PROVIDER_GATEWAYS table', () => {- expect(clientRows, 'client/src/utils/providers.js is missing: PROVIDER_GATEWAYS').not.toBeNull();+ expect(+ clientRows,+ 'client/src/utils/providers.js#PROVIDER_GATEWAYS is missing, or a row is no longer a flat table of static `key: \'value\'` properties — this guard cannot read it, so re-shape the row or teach the parser',+ ).not.toBeNull();expect(clientRows.length).toBeGreaterThan(0);});+ // The parser must refuse what it cannot see through, not skip it: a row that+ // pulls fields in at runtime would otherwise compare equal to the static row+ // it stopped being.+ it('refuses a row carrying anything but static single-quoted properties', () => {+ expect(parseGatewayRow("id: 'openrouter', label: 'OpenRouter'")).toEqual({ id: 'openrouter', label: 'OpenRouter' });+ expect(parseGatewayRow("id: 'openrouter', ...overrides")).toBeNull();+ expect(parseGatewayRow("id: 'openrouter', label: LABELS.openrouter")).toBeNull();+ expect(parseGatewayRow("id: 'openrouter', id: 'orcarouter'")).toBeNull();+ });++ // …and the table reader must refuse a declaration whose rows it can still+ // see but whose exported value they no longer are.+ it('refuses a table that is not a plain frozen array of frozen rows', () => {+ const rows = "Object.freeze({ id: 'openrouter', label: 'OpenRouter' })";+ expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}]);`))+ .toEqual([{ id: 'openrouter', label: 'OpenRouter' }]);+ expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}].map(withBaseURL));`)).toBeNull();+ expect(parseGatewayTable(`export const PROVIDER_GATEWAYS = Object.freeze([${rows}, ...EXTRA]);`)).toBeNull();+ });+it('declares the same rows, in the same order (browser-visible fields)', () => {expect(clientRows,