@bongos/core 1.19.415 → 1.19.416

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.bongos-core.json CHANGED
@@ -2,22 +2,22 @@
2
2
  "artifact": "bongos-core",
3
3
  "manifest_schema": 1,
4
4
  "generator": "scripts/gds/package-core.js",
5
- "core_version": "1.19.415",
6
- "core_contract": "1.19.415",
7
- "source_commit": "6e1130920b6477c117c5b10a7f2754db87ef558a",
5
+ "core_version": "1.19.416",
6
+ "core_contract": "1.19.416",
7
+ "source_commit": "1380d5372fffa712f955b0b7375a8b3a99089c8c",
8
8
  "source_ref": "HEAD",
9
- "built_at": "2026-08-29T16:12:53.136Z",
9
+ "built_at": "2026-08-29T16:18:39.698Z",
10
10
  "redaction": {
11
11
  "model": "docs-redacted+functional-verbatim",
12
12
  "docs_redacted": 355,
13
13
  "agent_docs_stubbed": 23,
14
- "functional_verbatim": 1698,
14
+ "functional_verbatim": 1699,
15
15
  "rules": 3,
16
16
  "gate_literals": 3,
17
17
  "gate": "passed"
18
18
  },
19
- "file_count": 2076,
20
- "tree_sha256": "992018f989d8c0b69b801d98f5bae82fb871101fb97f42f1dd43c3b4a63548cf",
19
+ "file_count": 2077,
20
+ "tree_sha256": "7e57eaed4b7d4afd8c45bd44503ead5fd9477a96aef101d6f04be3c23ff3bacc",
21
21
  "files": [
22
22
  {
23
23
  "path": ".claude/skills/blocker-review/SKILL.md",
@@ -1902,7 +1902,7 @@
1902
1902
  {
1903
1903
  "path": "docs/file-map.md",
1904
1904
  "mode": "0000644",
1905
- "sha256": "0eda387feba9769e7bd939ec6072f2e562f54d896b56816272f351d8798cf125"
1905
+ "sha256": "76febc87dd3d8b6641673093df2efa7c699a33428e6a53bc1cf595e0f3daf558"
1906
1906
  },
1907
1907
  {
1908
1908
  "path": "docs/handoff-template.md",
@@ -1912,7 +1912,7 @@
1912
1912
  {
1913
1913
  "path": "docs/module-api-changelog.md",
1914
1914
  "mode": "0000644",
1915
- "sha256": "728e49741b202322cb1e86147fd1a063e9421d094e6fa39ebbf11afa216ab23e"
1915
+ "sha256": "d8522f28a0009d2a15f4f4ae69488855022aff8a7d6e17bc33ec2f5d2c95b9d1"
1916
1916
  },
1917
1917
  {
1918
1918
  "path": "docs/modules-contract.md",
@@ -5422,12 +5422,12 @@
5422
5422
  {
5423
5423
  "path": "package-lock.json",
5424
5424
  "mode": "0000644",
5425
- "sha256": "5d5bd36ca85d6db8f0d37e036f6660c525eb07e49335f76d3fc23f33a4b56fe5"
5425
+ "sha256": "56b89bb9c7f6bea14a6a8f9a5c2e90443950df52ae44aeb73a553ce0db9590ad"
5426
5426
  },
5427
5427
  {
5428
5428
  "path": "package.json",
5429
5429
  "mode": "0000644",
5430
- "sha256": "b1bf9ff0d5e9155030c651fa5eea3e1ce81a683394b7090c5d48b1a87fc79ada"
5430
+ "sha256": "cd9fe4e19f8f3642c0953f045fff13a8392ddd844da6e131d4a9b1a237fa372d"
5431
5431
  },
5432
5432
  {
5433
5433
  "path": "public-docs/index.html",
@@ -7542,7 +7542,7 @@
7542
7542
  {
7543
7543
  "path": "src/module-api.js",
7544
7544
  "mode": "0000644",
7545
- "sha256": "85ade7dd85598993897af78be6cee56b8476a8bb1762866b3e6fc9586bad3694"
7545
+ "sha256": "30e53d05c81c6182e0e58d7c14a5c5c7a053cd0fe818c1dfbba2bb9f77d9c860"
7546
7546
  },
7547
7547
  {
7548
7548
  "path": "src/module-loader/catalog.js",
@@ -9227,7 +9227,7 @@
9227
9227
  {
9228
9228
  "path": "tests/memory_isolation.mjs",
9229
9229
  "mode": "0000644",
9230
- "sha256": "2982e61db8b1b3862dffa75d4cc3a9ce1a422b9070a9b84cc080247f4af1fa62"
9230
+ "sha256": "92d1c3d8343b0e2742c4fbbcfa3276a0cc99767229c4eb628a4dfc10a4181d67"
9231
9231
  },
9232
9232
  {
9233
9233
  "path": "tests/memory_map.mjs",
@@ -9449,6 +9449,11 @@
9449
9449
  "mode": "0000644",
9450
9450
  "sha256": "dac9d9891eac706432aff97ce35e27692064a2791dc1e546215c74e68b81e8a8"
9451
9451
  },
9452
+ {
9453
+ "path": "tests/own_scope_guard.mjs",
9454
+ "mode": "0000644",
9455
+ "sha256": "694002ebe39755fd01bdba57bf70e7077201b81a6938df92fff09b44027a29cc"
9456
+ },
9452
9457
  {
9453
9458
  "path": "tests/package_core.mjs",
9454
9459
  "mode": "0000644",
package/docs/file-map.md CHANGED
@@ -347,6 +347,7 @@ tests/
347
347
  ├── linkify_refs.mjs ← (#604): the doc-linkifier classifier — pins which `#NNN` rewrite (tasks) vs stay bare (heading anchors, link targets, idea/blocker/session/PR ids, code spans), incl. comma-list entity inheritance + idempotency.
348
348
  ├── sandbox_stage.mjs ← (#927, ADR 0046): sandbox-first review gate — box detection, BOX_PREVIEW_HOSTNAME parsing, previewable-surface matching, decideShipGate table, tree-stamp freshness (temp git repo), runShipGate composition with injected fs/exec/prompt.
349
349
  ├── session_start_freshness.mjs ← (#1277, ADR 0067): the SessionStart freshness decision (decideFreshness) — pull ONLY on a clean `main` full clone strictly behind origin/main; warn in every other behind case; skip when up to date.
350
+ ├── own_scope_guard.mjs ← (task 1003343, goal 1000045 criterion own-scope-held-by-a-test): the OWN-SCOPE structural guard, generalised out of memory_isolation.mjs. An explicit inventory of own-scoped route files; inside them the route's declared PATH decides — a path naming no builder must never read a subject from the request (direct, optional-chained, destructured, aliased, computed-key or header), a path that DOES name one needs a per-route exemption whose gate the guard verifies is present. Repo-wide backstop: any file mounting a `/me` route must be in the inventory. Source-grepping, so it runs in the DB-free `unit` lane.
350
351
  └── public_task_resolver.mjs ← (#604): the public `/public/tasks/:id` projection — title/value_summary exposed only for shipped|confirmed; withheld for in-flight so unshipped/security task names can't leak.
351
352
  ```
352
353
 
@@ -1267,5 +1267,7 @@ is load-bearing: the script throws rather than guess if it is missing, and
1267
1267
  landed since 1.19.413 with no explicit bump. run 33260596712. (task 1002620)
1268
1268
  1.19.415 — CI auto-patch (publish-on-merge, ADR 0161): carrier for merges
1269
1269
  landed since 1.19.414 with no explicit bump. run 33262322596. (task 1002620)
1270
+ 1.19.416 — CI auto-patch (publish-on-merge, ADR 0161): carrier for merges
1271
+ landed since 1.19.415 with no explicit bump. run 33262582879. (task 1002620)
1270
1272
  ---------------------------------------------------------------------------
1271
1273
  ```
package/package-lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@bongos/core",
3
- "version": "1.19.415",
3
+ "version": "1.19.416",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@bongos/core",
9
- "version": "1.19.415",
9
+ "version": "1.19.416",
10
10
  "license": "AGPL-3.0-or-later",
11
11
  "dependencies": {
12
12
  "express": "^4.21.2",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bongos/core",
3
- "version": "1.19.415",
3
+ "version": "1.19.416",
4
4
  "description": "Cloud Bongos — the AI-first build platform core (GDS + platform surfaces + module system), installed as a versioned dependency (ADR 0108).",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "main": "src/platform-server.js",
package/src/module-api.js CHANGED
@@ -33,7 +33,7 @@ const { validateOrRespond, LIMITS, parseId, asyncHandler, corsPublicGet, parsePa
33
33
  // there. scripts/gds/bump-version.js still rewrites the literal below; it appends
34
34
  // the entry to that file. Look for a version's history there, not here.
35
35
  // ---------------------------------------------------------------------------
36
- const CORE_VERSION = '1.19.415'; // CI auto-patch carrier (ADR 0161); changelog: docs/module-api-changelog.md
36
+ const CORE_VERSION = '1.19.416'; // CI auto-patch carrier (ADR 0161); changelog: docs/module-api-changelog.md
37
37
 
38
38
  // A namespaced logger so a module's log lines are attributable + consistent.
39
39
  // Usage: const log = api.logger('dev-box'); log.info('mounted');
@@ -212,6 +212,10 @@ await t('production code contains no grader-system references', () => {
212
212
  assert.ok(!/hacker worker/i.test(rawSrc), 'memory.js route source must not mention grader workers');
213
213
  });
214
214
 
215
+ // GENERALISED (task 1003343): this check now also exists — for memory.js AND for
216
+ // every other own-scoped surface (/me, builder-settings, platform-identity) — in
217
+ // tests/own_scope_guard.mjs, which runs in the DB-free unit lane. This file is in
218
+ // the INTEGRATION set, so the copy below gates nothing in CI; keep them agreeing.
215
219
  await t('the SELF read endpoints never derive the owner from request input', () => {
216
220
  assert.ok(!/req\.query\.builder/i.test(codeOnly), 'no owner should come from req.query.builder*');
217
221
  assert.ok(!/req\.body\.builder/i.test(codeOnly), 'no owner should come from req.body.builder*');
@@ -0,0 +1,472 @@
1
+ // tests/own_scope_guard.mjs
2
+ //
3
+ // THE OWN-SCOPE STRUCTURAL GUARD — "an own-scoped route takes its subject from
4
+ // the authenticated session, never from the request" (goal 1000045, criterion
5
+ // own-scope-held-by-a-test; task 1003343).
6
+ //
7
+ // WHY THIS EXISTS. The 2026-08-28 account-security audit found the hole CLOSED:
8
+ // no route on main derives acting identity from a URL, query, body or header
9
+ // parameter. But it was closed BY CONSTRUCTION — held by convention and code
10
+ // review, with nothing in CI to stop a future edit reopening it. One module
11
+ // already held the line structurally (modules/memory, tests/memory_isolation.mjs)
12
+ // and that guard covered exactly one file — and sits in the INTEGRATION set, so
13
+ // it never runs in the DB-free PR lane. This file generalises it to every
14
+ // own-scoped surface and lives in the lane that actually executes (task 1002282:
15
+ // a proof that never runs is not a gate).
16
+ //
17
+ // THE MECHANISM — how an own-scoped route is told apart from a legitimate
18
+ // cross-owner one, which takes an identifier DELIBERATELY and is rank-gated
19
+ // instead (PATCH /builders/:id/rank, the /boxes/:builderId fleet routes,
20
+ // POST /government/assignments, the goals membership routes, release-on-behalf):
21
+ //
22
+ // 1. An explicit INVENTORY of own-scoped surface FILES, one stated reason
23
+ // each. A blanket grep across all routes would break the cross-owner ones;
24
+ // the inventory is what keeps the guard off them entirely.
25
+ // 2. Inside an inventoried file, THE ROUTE'S OWN DECLARED PATH decides. A
26
+ // route that means to act on somebody else NAMES them in its path
27
+ // (`:builderId`). A route whose path names no builder is own-scoped, full
28
+ // stop — that is the route's own public promise to its callers, it cannot
29
+ // be forgotten (you cannot declare a route without a path), and it is
30
+ // exactly the promise this guard enforces.
31
+ // 3. A path that DOES name a builder is a cross-owner route, and is allowed
32
+ // only via a per-route exemption carrying a stated reason AND a required
33
+ // GATE PATTERN THE GUARD VERIFIES IS PRESENT. The exemption does not
34
+ // exempt — it substitutes a different, checked obligation. Drop the gate
35
+ // and the route fails here even though it is on the exemption list.
36
+ // 4. A DISCOVERY BACKSTOP over every route file in the repo: any file that
37
+ // declares a `/me`-mounted route must be in the inventory. `/me` is
38
+ // unambiguous — nothing cross-owner is ever mounted there — so a future
39
+ // own-scoped surface cannot appear without either joining the inventory or
40
+ // failing this test.
41
+ //
42
+ // Rejected alternatives, and why: a marker/annotation convention (`@own-scoped`)
43
+ // is invisible to the guard exactly when the author forgets it, which is the
44
+ // failure mode we exist to catch. An allowlist of exempt ROUTES with no gate
45
+ // check is a free pass — the greenest fix for a red build becomes "add a line to
46
+ // the allowlist". Detecting the adjacent rank gate ALONE cannot work either:
47
+ // rank is a PRIVILEGE dimension, not an OWNERSHIP one (a cross-owner route can
48
+ // be metic-gated and a self route archon-gated), which is precisely why
49
+ // src/bongos/route-rank-check.js cannot catch an own-scoped route growing an
50
+ // override parameter. Here the gate check is used only where ownership has
51
+ // already been established from the path.
52
+ //
53
+ // DB-free by construction: this reads source text. No Postgres, no server.
54
+ //
55
+ // Run: node tests/own_scope_guard.mjs
56
+
57
+ import { strict as assert } from 'node:assert';
58
+ import fs from 'node:fs';
59
+ import path from 'node:path';
60
+ import url from 'node:url';
61
+
62
+ const here = path.dirname(url.fileURLToPath(import.meta.url));
63
+ const repo = path.join(here, '..');
64
+
65
+ let passed = 0;
66
+ let failed = 0;
67
+ function t(name, fn) {
68
+ try { fn(); passed++; console.log(` PASS ${name}`); }
69
+ catch (e) { failed++; console.log(` FAIL ${name}\n ${e.message}`); }
70
+ }
71
+
72
+ // ===========================================================================
73
+ // The inventory — own-scoped surfaces, one stated reason each.
74
+ // ===========================================================================
75
+
76
+ const OWN_SCOPED_SURFACES = [
77
+ {
78
+ file: 'src/bongos/routes/me.js',
79
+ why: 'the /me aggregator: identity, rank, credits, streak, claims and prefs for the CALLER. Every slice keys on req.builder.id.',
80
+ crossOwner: [],
81
+ },
82
+ {
83
+ file: 'modules/builder-settings/routes/settings.js',
84
+ why: 'the per-builder preference domain (wandering, skill, sound, render, model-allocation, display name) carved out of /me — read and write, all keyed on req.builder.id.',
85
+ crossOwner: [],
86
+ },
87
+ {
88
+ file: 'modules/platform-identity/routes/profile.js',
89
+ why: "the builder's OWN cross-project profile controls (hide flag, handle, bio/links) — all keyed on req.builder.github_id.",
90
+ crossOwner: [],
91
+ },
92
+ {
93
+ file: 'modules/memory/routes/memory.js',
94
+ why: 'per-builder memory (ADR 0024 §4). The self endpoints are own-scoped; the five cross-builder endpoints name their target in the path and are gate-verified below.',
95
+ crossOwner: [
96
+ {
97
+ path: '/memory/builders/:builderId/files',
98
+ gate: /requirePermission\(\s*['"]memory\.read\.any['"]\s*\)/,
99
+ why: 'forensic LIST of another builder\'s memory metadata — permission-gated on the memory.read.any atom and audit-logged.',
100
+ },
101
+ {
102
+ path: '/memory/builders/:builderId/file',
103
+ gate: /requirePermission\(\s*['"]memory\.read\.any['"]\s*\)/,
104
+ why: 'forensic READ of another builder\'s memory file — permission-gated on the memory.read.any atom and audit-logged.',
105
+ },
106
+ {
107
+ path: '/memory/bfg/builders/:builderId/files',
108
+ gate: /requireBfgPrincipal/,
109
+ why: 'the BFG session-analysis LIST — gated on the BFG principal identity, stricter than any rank (ADR 0026 §6C).',
110
+ },
111
+ {
112
+ path: '/memory/bfg/builders/:builderId/file',
113
+ gate: /requireBfgPrincipal/,
114
+ why: 'the BFG session-analysis READ — gated on the BFG principal identity.',
115
+ },
116
+ {
117
+ path: '/memory/builders/:builderId/bfg-write',
118
+ gate: /requireBfgPrincipal/,
119
+ why: 'the BFG cross-builder WRITE — gated on the BFG principal identity plus a kill switch.',
120
+ },
121
+ ],
122
+ },
123
+ ];
124
+
125
+ // Floors that keep this guard from going quietly vacuous (a regex that stops
126
+ // matching would otherwise "pass" by checking nothing).
127
+ const MIN_OWN_SCOPED_ROUTES_TOTAL = 28;
128
+ const MIN_OWN_SCOPED_ROUTES_PER_FILE = 3;
129
+
130
+ // ===========================================================================
131
+ // Machinery
132
+ // ===========================================================================
133
+
134
+ /**
135
+ * Blank out comments while preserving every byte offset and newline, so route
136
+ * indices and line numbers stay true. Comment prose talks ABOUT req.body.builder
137
+ * constantly; only real code may be judged.
138
+ */
139
+ function blankComments(src) {
140
+ const out = src.split('');
141
+ let i = 0;
142
+ let state = 'code'; // code | line | block | sq | dq | tpl
143
+ while (i < src.length) {
144
+ const c = src[i];
145
+ const d = src[i + 1];
146
+ if (state === 'code') {
147
+ if (c === '/' && d === '/') { out[i] = ' '; out[i + 1] = ' '; i += 2; state = 'line'; continue; }
148
+ if (c === '/' && d === '*') { out[i] = ' '; out[i + 1] = ' '; i += 2; state = 'block'; continue; }
149
+ if (c === "'") { state = 'sq'; i++; continue; }
150
+ if (c === '"') { state = 'dq'; i++; continue; }
151
+ if (c === '`') { state = 'tpl'; i++; continue; }
152
+ i++; continue;
153
+ }
154
+ if (state === 'line') {
155
+ if (c === '\n') { state = 'code'; i++; continue; }
156
+ out[i] = ' '; i++; continue;
157
+ }
158
+ if (state === 'block') {
159
+ if (c === '*' && d === '/') { out[i] = ' '; out[i + 1] = ' '; i += 2; state = 'code'; continue; }
160
+ if (c !== '\n') out[i] = ' ';
161
+ i++; continue;
162
+ }
163
+ // inside a string literal — kept verbatim (literals are evidence, see below)
164
+ if (c === '\\') { i += 2; continue; }
165
+ if ((state === 'sq' && c === "'") || (state === 'dq' && c === '"') || (state === 'tpl' && c === '`')) { state = 'code'; i++; continue; }
166
+ i++;
167
+ }
168
+ return out.join('');
169
+ }
170
+
171
+ /**
172
+ * Does this identifier NAME A BUILDER — i.e. is it a subject selector rather
173
+ * than a payload field? This is the guard's contract, so it is a written list,
174
+ * not a vibe: anything containing "builder" or "owner", plus the explicit set of
175
+ * other ways one account points at another. Deliberately NOT here: `handle`,
176
+ * `display_name`, `anthropic_user_id` — payload the caller sets on THEMSELVES.
177
+ */
178
+ const SUBJECT_NAMES = new Set([
179
+ 'githubid', 'githublogin', 'githubuser', 'githubuserid', 'login',
180
+ 'actas', 'asbuilder', 'onbehalf', 'onbehalfof', 'impersonate', 'impersonateas',
181
+ 'targetid', 'targetlogin', 'targetbuilder', 'subject', 'subjectid',
182
+ 'accountid', 'memberid', 'principal', 'principalid',
183
+ ]);
184
+ function namesABuilder(name) {
185
+ const k = String(name).toLowerCase().replace(/[_-]/g, '');
186
+ if (k.includes('builder') || k.includes('owner')) return true;
187
+ return SUBJECT_NAMES.has(k);
188
+ }
189
+
190
+ const REQUEST_CONTAINERS = 'body|query|params|headers';
191
+ const ROUTE_DECL = /\brouter\.(get|post|put|patch|delete|all)\(\s*(['"`])([^'"`\n]+)\2/g;
192
+ const HANDLER_START = /(?:async\s*)?\(\s*_?req\s*,/;
193
+
194
+ /** Split a route file into { verb, routePath, decl, body, line } records. */
195
+ function parseRoutes(code) {
196
+ const decls = [...code.matchAll(ROUTE_DECL)];
197
+ return decls.map((m, i) => {
198
+ const start = m.index;
199
+ const end = i + 1 < decls.length ? decls[i + 1].index : code.length;
200
+ const window = code.slice(start, end);
201
+ const hIdx = window.search(HANDLER_START);
202
+ return {
203
+ verb: m[1],
204
+ routePath: m[3],
205
+ line: code.slice(0, start).split('\n').length,
206
+ // the middleware chain (where the gates live) vs the handler (where the
207
+ // subject is read). When the handler can't be located, both halves fall
208
+ // back to the whole window — conservative, never silently narrower.
209
+ decl: hIdx >= 0 ? window.slice(0, hIdx) : window,
210
+ body: hIdx >= 0 ? window.slice(hIdx) : window,
211
+ };
212
+ });
213
+ }
214
+
215
+ /**
216
+ * Every way this route pulls a named thing out of the request, as a flat list of
217
+ * { how, name } — direct reads, optional chaining, destructuring, aliases of a
218
+ * container, rest elements, literal bracket access, computed access (judged by
219
+ * the string literals in the route's array literals, which is where a copy-these
220
+ * -fields loop keeps its key list), and header lookups via req.get().
221
+ */
222
+ function requestReads(routeBody) {
223
+ const reads = [];
224
+ const containerRe = String.raw`req\s*\??\.\s*(?:${REQUEST_CONTAINERS})`;
225
+
226
+ // Aliases: `const body = req.body` / `const { a, ...rest } = req.query`.
227
+ const aliases = new Set();
228
+ for (const m of routeBody.matchAll(new RegExp(String.raw`(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*${containerRe}\b`, 'g'))) {
229
+ aliases.add(m[1]);
230
+ }
231
+ // Re-derived on every use: the destructuring pass below can discover MORE
232
+ // aliases (rest elements), and each later pass must see them.
233
+ const containers = () => `(?:${containerRe}${aliases.size ? `|\\b(?:${[...aliases].join('|')})` : ''})`;
234
+
235
+ // Destructuring — `const { builder_id } = req.body`. A rest element becomes an
236
+ // alias itself: an object spread off the request IS the request.
237
+ for (const m of routeBody.matchAll(new RegExp(String.raw`(?:const|let|var)\s*\{([^}]*)\}\s*=\s*${containers()}\b`, 'g'))) {
238
+ for (const part of m[1].split(',')) {
239
+ const rest = part.match(/\.\.\.\s*([A-Za-z_$][\w$]*)/);
240
+ if (rest) { aliases.add(rest[1]); continue; }
241
+ const key = part.split(':')[0].split('=')[0].trim();
242
+ if (key) reads.push({ how: 'destructured from the request', name: key });
243
+ }
244
+ }
245
+
246
+ // Direct member reads — `req.query.builder_id`, `body?.owner`.
247
+ for (const m of routeBody.matchAll(new RegExp(String.raw`${containers()}\s*\??\.\s*([A-Za-z_$][\w$]*)`, 'g'))) {
248
+ reads.push({ how: 'read from the request', name: m[1] });
249
+ }
250
+
251
+ // Literal bracket access — `req.body['builder_id']`. Exact, so judged exactly.
252
+ for (const m of routeBody.matchAll(new RegExp(String.raw`${containers()}\s*\[\s*(['"])([^'"]+)\1`, 'g'))) {
253
+ reads.push({ how: 'read from the request', name: m[2] });
254
+ }
255
+
256
+ // Variable bracket access — `req.body[k]`. The key is unknowable statically, so
257
+ // the string literals in the route's ARRAY literals are the candidate key set:
258
+ // that is exactly how the copy-these-fields loops in these files are written.
259
+ // Scoped to array literals so ordinary message/error strings can't false-positive.
260
+ if (new RegExp(String.raw`${containers()}\s*\[\s*[A-Za-z_$]`).test(routeBody)) {
261
+ for (const arr of routeBody.matchAll(/\[([^\][]*)\]/g)) {
262
+ for (const m of arr[1].matchAll(/(['"])([A-Za-z_][\w-]*)\1/g)) {
263
+ reads.push({ how: 'a candidate computed request key', name: m[2] });
264
+ }
265
+ }
266
+ }
267
+
268
+ // Header lookups by name.
269
+ for (const m of routeBody.matchAll(/\breq\s*\.\s*get\(\s*(['"])([^'"]+)\1/g)) {
270
+ reads.push({ how: 'read from a request header', name: m[2] });
271
+ }
272
+
273
+ return reads;
274
+ }
275
+
276
+ /** The `:name` segments a route declares — the route saying out loud what it takes. */
277
+ function pathParams(routePath) {
278
+ return [...routePath.matchAll(/:([A-Za-z_][\w]*)/g)].map((m) => m[1]);
279
+ }
280
+
281
+ // ===========================================================================
282
+ // Self-tests — the machinery above is the guard, so it gets proved too.
283
+ // ===========================================================================
284
+
285
+ console.log('guard machinery:');
286
+
287
+ t('blankComments erases comment prose but keeps offsets and string literals', () => {
288
+ const src = "const a = 1; // req.body.builder_id\n/* req.query.owner */ const s = 'builder_id';\n";
289
+ const out = blankComments(src);
290
+ assert.equal(out.length, src.length, 'offsets must be preserved');
291
+ assert.ok(!/req\.body\.builder_id/.test(out), 'line comments must be erased');
292
+ assert.ok(!/req\.query\.owner/.test(out), 'block comments must be erased');
293
+ assert.ok(/'builder_id'/.test(out), 'string literals are evidence and must survive');
294
+ });
295
+
296
+ t('namesABuilder separates subject selectors from self-payload fields', () => {
297
+ for (const n of ['builder_id', 'builderId', 'owner', 'target_builder', 'github_id', 'githubLogin', 'as_builder', 'login']) {
298
+ assert.equal(namesABuilder(n), true, `${n} names a builder`);
299
+ }
300
+ for (const n of ['handle', 'display_name', 'bio', 'links', 'limit', 'anthropic_user_id', 'anthropic_email', 'files', 'path', 'hide_stats', 'preferred_disciplines', 'user-agent']) {
301
+ assert.equal(namesABuilder(n), false, `${n} is self-payload, not a subject`);
302
+ }
303
+ });
304
+
305
+ t('requestReads sees direct, optional-chained, destructured and aliased reads', () => {
306
+ const reads = (s) => requestReads(s).map((r) => r.name);
307
+ assert.ok(reads('const x = req.query.builder_id;').includes('builder_id'));
308
+ assert.ok(reads('const x = req.body?.owner;').includes('owner'));
309
+ assert.ok(reads('const { builder_id, y } = req.body;').includes('builder_id'));
310
+ assert.ok(reads('const b = req.body;\nconst v = b.builder_id;').includes('builder_id'));
311
+ assert.ok(reads('const { a, ...rest } = req.body;\nconst v = rest.owner_id;').includes('owner_id'));
312
+ assert.ok(reads("const v = req.body['builder_id'];").includes('builder_id'));
313
+ assert.ok(reads("for (const k of ['builder_id']) f[k] = req.body[k];").includes('builder_id'));
314
+ assert.ok(reads("const v = req.get('x-builder-id');").includes('x-builder-id'));
315
+ // ...but an ordinary message string is not a candidate key: no bracket read, no scan.
316
+ assert.ok(!reads("return res.fail('builder_not_found', 404);").includes('builder_not_found'));
317
+ });
318
+
319
+ // ===========================================================================
320
+ // The guard
321
+ // ===========================================================================
322
+
323
+ console.log('\nown-scope guard (every own-scoped route keys on the session):');
324
+
325
+ let totalOwnScoped = 0;
326
+ let totalCrossOwner = 0;
327
+
328
+ for (const surface of OWN_SCOPED_SURFACES) {
329
+ const abs = path.join(repo, surface.file);
330
+ const raw = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null;
331
+
332
+ t(`${surface.file} — inventoried own-scoped surface exists and declares routes`, () => {
333
+ assert.ok(raw !== null, `${surface.file} is in the own-scoped inventory but does not exist — update the inventory or restore the file`);
334
+ const rawDecls = (raw.match(/\brouter\.(?:get|post|put|patch|delete|all)\(/g) || []).length;
335
+ const parsed = parseRoutes(blankComments(raw)).length;
336
+ assert.ok(parsed > 0, 'no routes parsed — the route-declaration regex has rotted');
337
+ assert.equal(parsed, rawDecls, `parsed ${parsed} routes but the file declares ${rawDecls} — the guard is not seeing every route`);
338
+ });
339
+ if (raw === null) continue;
340
+
341
+ const code = blankComments(raw);
342
+ const routes = parseRoutes(code);
343
+ const exemptions = surface.crossOwner || [];
344
+ const usedExemptions = new Set();
345
+ let ownScopedHere = 0;
346
+
347
+ for (const r of routes) {
348
+ const id = `${surface.file}:${r.line} ${r.verb.toUpperCase()} ${r.routePath}`;
349
+ const subjectParams = pathParams(r.routePath).filter(namesABuilder);
350
+
351
+ if (subjectParams.length > 0) {
352
+ // Cross-owner: names its target in the path. Allowed only with a stated
353
+ // reason AND a gate the guard confirms is really there.
354
+ totalCrossOwner++;
355
+ t(`${id} — cross-owner route is exempted with a reason AND carries its gate`, () => {
356
+ const ex = exemptions.find((e) => e.path === r.routePath);
357
+ assert.ok(
358
+ ex,
359
+ `takes a builder from the path (:${subjectParams.join(', :')}) but is not on the cross-owner exemption list for this file. `
360
+ + 'If it is deliberately cross-owner, add it with a stated reason and the gate that protects it; otherwise it must not name a builder.'
361
+ );
362
+ usedExemptions.add(ex.path);
363
+ assert.ok(ex.why && ex.why.length > 20, 'a cross-owner exemption must carry a stated reason');
364
+ // The exemption is only as strong as what it demands, so the demand
365
+ // itself is constrained: it must name a real privilege atom, not a
366
+ // regex that matches anything the author happens to have written.
367
+ assert.match(
368
+ ex.gate.source, /require(?:Permission|Rank|BfgPrincipal|Archon)/,
369
+ 'a cross-owner exemption must require a real gate (requirePermission / requireRank / requireBfgPrincipal / requireArchon)'
370
+ );
371
+ assert.ok(
372
+ ex.gate.test(r.decl),
373
+ `the exemption requires ${ex.gate} on the middleware chain and it is NOT there — a cross-owner route without its gate is the hole this guard exists to catch`
374
+ );
375
+ });
376
+ continue;
377
+ }
378
+
379
+ // Own-scoped: the path names no builder, so the subject can only be the session.
380
+ ownScopedHere++;
381
+ totalOwnScoped++;
382
+
383
+ t(`${id} — own-scoped route never takes its subject from the request`, () => {
384
+ const offenders = requestReads(r.body).filter((x) => namesABuilder(x.name));
385
+ assert.equal(
386
+ offenders.length, 0,
387
+ `${offenders.map((o) => `"${o.name}" (${o.how})`).join(', ')} — this route's path names no builder, so its subject MUST come from req.builder. `
388
+ + 'If it is genuinely meant to act on someone else, name them in the path, gate it, and add a cross-owner exemption.'
389
+ );
390
+ });
391
+
392
+ t(`${id} — own-scoped route derives its subject from the authenticated session`, () => {
393
+ assert.ok(/\brequireBuilder\b/.test(r.decl), 'an own-scoped route must sit behind requireBuilder');
394
+ const readsSession = /\breq\s*\.\s*builder\b/.test(r.body) || /\bassertSelf\s*\(\s*req\b/.test(r.body);
395
+ const ignoresRequest = /\(\s*_req\s*,/.test(r.body);
396
+ assert.ok(
397
+ readsSession || ignoresRequest,
398
+ 'neither reads req.builder nor declares its request unused (_req) — it is scoped to nobody, which is not own-scope'
399
+ );
400
+ });
401
+ }
402
+
403
+ t(`${surface.file} — contributes a real number of own-scoped routes (not vacuous)`, () => {
404
+ assert.ok(
405
+ ownScopedHere >= MIN_OWN_SCOPED_ROUTES_PER_FILE,
406
+ `only ${ownScopedHere} own-scoped routes found (floor ${MIN_OWN_SCOPED_ROUTES_PER_FILE}) — either routes moved out or the parser stopped seeing them`
407
+ );
408
+ });
409
+
410
+ t(`${surface.file} — every listed cross-owner exemption still names a real route`, () => {
411
+ const stale = exemptions.filter((e) => !usedExemptions.has(e.path)).map((e) => e.path);
412
+ assert.equal(stale.length, 0, `stale exemption(s) for route(s) that no longer exist: ${stale.join(', ')} — an exemption for a deleted route silently widens the guard`);
413
+ });
414
+ }
415
+
416
+ // ===========================================================================
417
+ // Discovery backstop + lane proof
418
+ // ===========================================================================
419
+
420
+ console.log('\ncoverage (the guard cannot be dodged by adding a new file, or parked out of CI):');
421
+
422
+ function routeFiles() {
423
+ const out = [];
424
+ const walk = (dir) => {
425
+ let entries;
426
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
427
+ for (const e of entries) {
428
+ const p = path.join(dir, e.name);
429
+ if (e.isDirectory()) { if (e.name !== 'node_modules') walk(p); }
430
+ else if (e.name.endsWith('.js')) out.push(p);
431
+ }
432
+ };
433
+ walk(path.join(repo, 'src'));
434
+ walk(path.join(repo, 'modules'));
435
+ return out;
436
+ }
437
+
438
+ t('every file in the repo that mounts a /me route is in the own-scoped inventory', () => {
439
+ const inventory = new Set(OWN_SCOPED_SURFACES.map((s) => s.file.split('/').join(path.sep)));
440
+ const missing = [];
441
+ for (const abs of routeFiles()) {
442
+ const code = blankComments(fs.readFileSync(abs, 'utf8'));
443
+ const declaresMe = parseRoutes(code).some((r) => r.routePath === '/me' || r.routePath.startsWith('/me/'));
444
+ if (!declaresMe) continue;
445
+ const rel = path.relative(repo, abs);
446
+ if (!inventory.has(rel)) missing.push(rel.split(path.sep).join('/'));
447
+ }
448
+ assert.equal(
449
+ missing.length, 0,
450
+ `these files mount /me routes but are not in OWN_SCOPED_SURFACES: ${missing.join(', ')}. `
451
+ + 'Nothing cross-owner is ever mounted at /me, so add them to the inventory.'
452
+ );
453
+ });
454
+
455
+ t('the guard checks a real number of own-scoped routes overall', () => {
456
+ assert.ok(
457
+ totalOwnScoped >= MIN_OWN_SCOPED_ROUTES_TOTAL,
458
+ `only ${totalOwnScoped} own-scoped routes checked (floor ${MIN_OWN_SCOPED_ROUTES_TOTAL})`
459
+ );
460
+ assert.ok(totalCrossOwner > 0, 'no cross-owner route was exercised — the gate-verification path is untested');
461
+ });
462
+
463
+ t('this guard runs in the DB-free unit lane (it is not parked as integration or known-failing)', () => {
464
+ const runner = fs.readFileSync(path.join(repo, 'scripts', 'gds', 'run-unit-tests.js'), 'utf8');
465
+ assert.ok(
466
+ !/own_scope_guard/.test(runner),
467
+ 'own_scope_guard is named in run-unit-tests.js — if it landed in INTEGRATION or KNOWN_FAILING it would stop gating anything (task 1002282)'
468
+ );
469
+ });
470
+
471
+ console.log(`\n${passed} passed, ${failed} failed`);
472
+ process.exit(failed === 0 ? 0 : 1);