@bridge_gpt/mcp-server 0.2.73 → 0.2.74

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.
Files changed (90) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agents.generated.js +3 -3
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +3 -0
  6. package/build/command-provisioning.js +4 -3
  7. package/build/commands.generated.js +5 -5
  8. package/build/conductor/bridge-api-client.js +26 -1
  9. package/build/conductor/command-drift.js +1 -1
  10. package/build/conductor/declared-extras.js +335 -0
  11. package/build/conductor/doctor.js +2 -0
  12. package/build/conductor/driver-pass-output.js +104 -0
  13. package/build/conductor/driver-pass.js +571 -0
  14. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  15. package/build/conductor/epic-implementer-cli.js +33 -0
  16. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  17. package/build/conductor/epic-server-sfcc.js +58 -80
  18. package/build/conductor/epic-server.js +57 -4
  19. package/build/conductor/gate-discovery.js +46 -6
  20. package/build/conductor/gate-settings-review.js +51 -14
  21. package/build/credential-delivery.js +280 -0
  22. package/build/credential-launch-safety.js +142 -0
  23. package/build/credential-materialization.js +91 -16
  24. package/build/credential-references-node-deps.js +29 -0
  25. package/build/credential-references.js +1394 -0
  26. package/build/credential-references.test-fixtures.js +211 -0
  27. package/build/credential-scan-conventions.js +145 -0
  28. package/build/credential-scan.js +517 -0
  29. package/build/credential-store.js +50 -0
  30. package/build/credentials-cli.js +252 -3
  31. package/build/dependency-install-declarations.js +47 -1
  32. package/build/docs.generated.js +8 -1
  33. package/build/doctor.js +41 -0
  34. package/build/drive-epic.js +297 -37
  35. package/build/epic-branch-ci-summary.js +18 -1
  36. package/build/epic-capability-statement.js +71 -3
  37. package/build/epic-ci-workflow-drift.js +52 -13
  38. package/build/epic-ci-workflow-install.js +31 -6
  39. package/build/epic-ci-workflow-v3.js +273 -0
  40. package/build/epic-ci-workflow.js +128 -7
  41. package/build/epic-implementer-bin.js +161 -70
  42. package/build/epic-launch-context.js +102 -7
  43. package/build/epic-server-record.js +30 -15
  44. package/build/executor/credential-delivery-step.js +168 -0
  45. package/build/executor/deps.js +3 -1
  46. package/build/executor/env.js +39 -1
  47. package/build/executor/epic-server-context.js +23 -7
  48. package/build/executor/guarded-fast-forward-push.js +13 -8
  49. package/build/executor/job-runner.js +159 -17
  50. package/build/executor/permissions.js +85 -3
  51. package/build/executor/prompt-spec.js +37 -3
  52. package/build/executor-launch.js +4 -2
  53. package/build/git-exclude-lock.js +187 -0
  54. package/build/index.js +398 -269
  55. package/build/install-bridge-conductor-answers.js +84 -21
  56. package/build/install-bridge-conductor-apply.js +30 -1
  57. package/build/install-bridge-conductor-assessment.js +375 -48
  58. package/build/install-bridge-conductor-compact.js +27 -2
  59. package/build/install-bridge-conductor-contracts.js +10 -1
  60. package/build/install-bridge-conductor-gate.js +124 -11
  61. package/build/install-bridge-conductor-setup.js +46 -8
  62. package/build/install-bridge-conductor.js +625 -113
  63. package/build/install-bridge.js +88 -11
  64. package/build/install-doctor.js +38 -8
  65. package/build/install-sfcc-detection.js +120 -0
  66. package/build/install-sfcc-setup.js +185 -0
  67. package/build/mcp-grant-candidates.js +108 -96
  68. package/build/mcp-invoke.js +168 -4
  69. package/build/mcp-provisioning.js +21 -4
  70. package/build/mcp-server-invocation.js +13 -0
  71. package/build/merge-workflow-install.js +9 -1
  72. package/build/pipelines.generated.js +2 -1
  73. package/build/plane/status.js +8 -2
  74. package/build/printed-remedy-commands.js +5 -0
  75. package/build/project-root.js +40 -0
  76. package/build/readme.generated.js +1 -1
  77. package/build/repository-state-paths.js +5 -2
  78. package/build/repository-toolchains.js +6 -3
  79. package/build/setup-epic.js +116 -15
  80. package/build/sfcc/credentials.js +3 -2
  81. package/build/sfcc/hostname.js +98 -2
  82. package/build/sfcc/tool-wrapper.js +6 -95
  83. package/build/start-tickets.js +193 -29
  84. package/build/test-support/executor-source-files.js +200 -0
  85. package/build/testing-config-client.js +25 -2
  86. package/build/third-party-mcp-targets.js +35 -4
  87. package/build/version.generated.js +3 -3
  88. package/build/with-credentials.js +208 -0
  89. package/build/worktree-credential-delivery.js +340 -0
  90. package/package.json +1 -1
@@ -0,0 +1,1394 @@
1
+ /**
2
+ * Worker credential references (BAPI-1646).
3
+ *
4
+ * The repository owner approves which of the project's EXISTING credentials
5
+ * workers may use. This module stores references to them — where each secret
6
+ * lives and who may receive it — and never the values. The record is kept at
7
+ * `~/.config/bridge/worker-credentials/<repo>.json` (family `worker-credentials`
8
+ * in `repository-state-paths.ts`), OUTSIDE every worktree, so nothing a worker
9
+ * edits or commits can widen what it receives.
10
+ *
11
+ * This module only RECORDS, VALIDATES, RESOLVES, and DIAGNOSES references. It
12
+ * delivers nothing to a worker: no caller of `forWorkerLaunch()` or
13
+ * `forMcpServer()` exists yet (delivery is a later ticket).
14
+ *
15
+ * Schema version 1:
16
+ *
17
+ * { version: 1, repo_name, approved_at, credentials: [ { name, level, source, consumers } ] }
18
+ *
19
+ * Sources (closed): `file`, `file_keys`, `host_mcp_env`, `store_bundle`.
20
+ * Consumers (closed): `worktree_file`, `env`, `mcp_server`.
21
+ * Levels (closed): `sandbox`, `restricted` (MCP consumers only), `production`
22
+ * (recorded so the owner sees it is known, but never delivered).
23
+ *
24
+ * Security boundary:
25
+ * - Records, statuses, list output, doctor output, and refusals hold NAMES and
26
+ * approved locations only. Resolved values live only in the maps returned by
27
+ * `forWorkerLaunch()` and `forMcpServer()`.
28
+ * - Refusal and error text is fixed. It never interpolates a rejected path,
29
+ * selector, field name, parser message, or filesystem exception.
30
+ * - Source locations are the approved ABSOLUTE paths in the record. Resolution
31
+ * never reads a project file inside a worktree.
32
+ * - Callers pass `excludedRoots` (for example the worker's worktree) to withhold
33
+ * any entry whose backing path is inside them. That check, and the
34
+ * one-level-per-source check, compare `path.resolve()` results lexically:
35
+ * a symlink alias of the same file is NOT detected.
36
+ * - Reserved worker variable names are refused by importing
37
+ * `isWorkerEnvNameReserved()` from `executor/env.ts`. No list is copied here.
38
+ * - Nothing here writes to stdout or stderr, and nothing reads ambient
39
+ * operator state except through the injected dependencies.
40
+ */
41
+ import { createHash } from "node:crypto";
42
+ import path from "path";
43
+ import { validateMcpTarget } from "./bridge-config.js";
44
+ import { resolveClaudeUserConfigPath } from "./claude-user-config-doctor.js";
45
+ import { validateWorktreeRelativeCredentialPath } from "./credential-materialization.js";
46
+ import { parseCredentialStoreJson, resolveCredentialStorePath, withCredentialStoreLock, } from "./credential-store.js";
47
+ import { isWorkerEnvFileName } from "./executor/env-file-guard.js";
48
+ import { isWorkerEnvNameReserved } from "./executor/env.js";
49
+ import { resolveCursorUserConfigPath } from "./mcp-host-targets.js";
50
+ import { repositoryStateRecordPath } from "./repository-state-paths.js";
51
+ // ---------------------------------------------------------------------------
52
+ // Types
53
+ // ---------------------------------------------------------------------------
54
+ export const CREDENTIAL_REFERENCES_VERSION = 1;
55
+ export const CREDENTIAL_REFERENCES_MAX_ENTRIES = 32;
56
+ /** `file_keys` sources larger than this are `unreadable`. */
57
+ export const CREDENTIAL_REFERENCES_MAX_SOURCE_BYTES = 64 * 1024;
58
+ const LEVELS = ["sandbox", "restricted", "production"];
59
+ // ---------------------------------------------------------------------------
60
+ // Fixed refusal text
61
+ // ---------------------------------------------------------------------------
62
+ const REFUSAL_TEXT = {
63
+ record_shape: "the record is not an object with the expected fields",
64
+ version: "the record version is not supported",
65
+ repository: "the record names a different repository",
66
+ approved_at: "approved_at is not a valid timestamp",
67
+ credentials_list: "credentials is not a list of at most 32 entries",
68
+ entry_shape: "the entry is not an object with the expected fields",
69
+ entry_name: "the entry name is not valid",
70
+ entry_name_duplicate: "the entry name is used more than once",
71
+ level: "the level is not one of sandbox, restricted, production",
72
+ source_kind: "the source kind is not supported",
73
+ source_shape: "the source has missing, malformed, or unknown fields",
74
+ source_path: "the source path must be absolute and contain no control characters",
75
+ source_dotenv_file: "a whole dotenv file cannot be a source; reference its keys with file_keys",
76
+ source_format: "the source format must be dotenv or json",
77
+ source_host: "the source host must be claude or cursor",
78
+ source_selector: "a source key selector is malformed",
79
+ source_keys: "the source keys are missing, malformed, or too many",
80
+ variable_name: "a variable name is not valid",
81
+ variable_reserved: "a variable name is reserved for the worker environment",
82
+ consumers_list: "consumers is not a list of supported consumers",
83
+ consumer_kind: "a consumer kind is not supported",
84
+ consumer_shape: "a consumer has missing, malformed, or unknown fields",
85
+ consumer_incompatible: "a consumer kind is not compatible with the source kind",
86
+ consumer_restricted: "a restricted entry may have only mcp_server consumers",
87
+ consumer_production: "a production entry must have no consumers",
88
+ dest_invalid: "a worktree destination must be a relative path with no '..' and no control characters",
89
+ dest_control_path: "a worktree destination cannot be, or be under, a worker control path",
90
+ dest_dotenv: "a worktree destination cannot be a dotenv file",
91
+ dest_duplicate: "a worktree destination is used by more than one consumer",
92
+ mcp_server: "an mcp_server consumer names an invalid target",
93
+ mcp_server_bapi: "an mcp_server consumer must spell Bridge's own server as bridge, not bapi",
94
+ mcp_fingerprint: "a launch_fingerprint must be 64 lower-case hex characters",
95
+ env_collision: "a variable is delivered to the shell by more than one entry",
96
+ mcp_collision: "a variable is delivered to the same MCP server by more than one entry",
97
+ one_level: "a restricted entry shares its source with a sandbox entry that reaches workers",
98
+ value_shaped: "the proposal contains a value-shaped field; it must hold names and paths only",
99
+ };
100
+ // ---------------------------------------------------------------------------
101
+ // Small predicates
102
+ // ---------------------------------------------------------------------------
103
+ /** Prompt-safe entry name rule, mirroring grant names (`mcp-grant.ts`). */
104
+ const ENTRY_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
105
+ /** Same syntax as `WORKER_ENV_NAME_PATTERN` in `executor/env.ts` (not exported there). */
106
+ const VARIABLE_NAME_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
107
+ /** Same rule as `FINGERPRINT_RE` in `mcp-grant.ts`. */
108
+ const FINGERPRINT_RE = /^[0-9a-f]{64}$/;
109
+ const DOTENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/;
110
+ const HOST_ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
111
+ const MAX_KEYS = 32;
112
+ const MAX_CONSUMERS = 16;
113
+ const CONTROL_PATH_SEGMENTS = new Set([".git", ".claude", ".cursor", ".bridge", ".mcp.json"]);
114
+ const VALUE_SHAPED_FIELDS = new Set(["value", "values", "secret", "token", "password"]);
115
+ function hasControlChars(value) {
116
+ for (let i = 0; i < value.length; i++) {
117
+ const code = value.charCodeAt(i);
118
+ if (code <= 0x1f || code === 0x7f)
119
+ return true;
120
+ }
121
+ return false;
122
+ }
123
+ function isPlainObject(value) {
124
+ return value !== null && typeof value === "object" && !Array.isArray(value);
125
+ }
126
+ function hasOnlyKeys(obj, allowed) {
127
+ return Object.keys(obj).every((k) => allowed.includes(k));
128
+ }
129
+ function isIsoTimestamp(value) {
130
+ return (typeof value === "string" &&
131
+ value.length <= 64 &&
132
+ /^\d{4}-\d{2}-\d{2}T/.test(value) &&
133
+ !Number.isNaN(Date.parse(value)));
134
+ }
135
+ function isAbsoluteSafePath(value) {
136
+ return (typeof value === "string" &&
137
+ value.length > 0 &&
138
+ value.length <= 4096 &&
139
+ !hasControlChars(value) &&
140
+ (path.posix.isAbsolute(value) || path.win32.isAbsolute(value)));
141
+ }
142
+ function errorCode(err) {
143
+ return err && typeof err === "object" ? err.code : undefined;
144
+ }
145
+ function sha256Hex(data) {
146
+ return createHash("sha256").update(data).digest("hex");
147
+ }
148
+ /** The single launch-fingerprint implementation (SHA-256 of the launcher). */
149
+ export function computeLaunchFingerprint(command, args) {
150
+ return sha256Hex(JSON.stringify([command, ...args]));
151
+ }
152
+ /** Map a consumer's `server` to its target identifier: `bridge` is the shim's `bapi`. */
153
+ export function mcpTargetForConsumer(server) {
154
+ return server === "bridge" ? "bapi" : server;
155
+ }
156
+ function pathSegments(value) {
157
+ return value.split(/[\\/]+/).filter((s) => s.length > 0 && s !== ".");
158
+ }
159
+ function lastSegment(value) {
160
+ const segments = value.split(/[\\/]+/).filter((s) => s.length > 0);
161
+ return segments.length > 0 ? segments[segments.length - 1] : "";
162
+ }
163
+ function storeDepsFor(deps) {
164
+ return {
165
+ env: deps.env,
166
+ homedir: deps.homedir,
167
+ platform: deps.platform,
168
+ readFile: deps.readFile,
169
+ stat: deps.stat,
170
+ };
171
+ }
172
+ async function storeBackingPaths(deps) {
173
+ const resolution = await resolveCredentialStorePath(storeDepsFor(deps));
174
+ return resolution.found ? [resolution.path] : [resolution.primaryPath, resolution.fallbackPath];
175
+ }
176
+ /** Build the context from the injected deps. Never throws; a failure leaves paths empty. */
177
+ export async function buildCredentialValidationContext(deps) {
178
+ try {
179
+ const homedir = deps.homedir();
180
+ let storePaths = [];
181
+ try {
182
+ storePaths = await storeBackingPaths(deps);
183
+ }
184
+ catch {
185
+ storePaths = [];
186
+ }
187
+ return { homedir, platform: deps.platform, storePaths };
188
+ }
189
+ catch {
190
+ return undefined;
191
+ }
192
+ }
193
+ function hostConfigPath(host, homedir, platform) {
194
+ return host === "claude" ? resolveClaudeUserConfigPath(homedir, platform) : resolveCursorUserConfigPath(homedir);
195
+ }
196
+ /** Resolved backing path(s) of a source; empty when the context cannot supply them. */
197
+ function backingPaths(source, ctx) {
198
+ switch (source.kind) {
199
+ case "file":
200
+ case "file_keys":
201
+ return [path.resolve(source.path)];
202
+ case "host_mcp_env":
203
+ return ctx ? [path.resolve(hostConfigPath(source.host, ctx.homedir, ctx.platform))] : [];
204
+ case "store_bundle":
205
+ return ctx ? ctx.storePaths.map((p) => path.resolve(p)) : [];
206
+ }
207
+ }
208
+ function isWithinRoot(candidate, root) {
209
+ const rel = path.relative(path.resolve(root), path.resolve(candidate));
210
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
211
+ }
212
+ // ---------------------------------------------------------------------------
213
+ // Validation
214
+ // ---------------------------------------------------------------------------
215
+ class Refusals {
216
+ list = [];
217
+ add(entry, code) {
218
+ this.list.push({ entry, reason: REFUSAL_TEXT[code] });
219
+ }
220
+ }
221
+ function validateVariableNames(names, label, refusals) {
222
+ let ok = true;
223
+ for (const name of names) {
224
+ if (!VARIABLE_NAME_RE.test(name)) {
225
+ refusals.add(label, "variable_name");
226
+ ok = false;
227
+ }
228
+ else if (isWorkerEnvNameReserved(name)) {
229
+ refusals.add(label, "variable_reserved");
230
+ ok = false;
231
+ }
232
+ }
233
+ return ok;
234
+ }
235
+ function isJsonPointer(value) {
236
+ if (value === "")
237
+ return true;
238
+ if (!value.startsWith("/") || value.length > 256 || hasControlChars(value))
239
+ return false;
240
+ return !/~(?![01])/.test(value);
241
+ }
242
+ function validateKeyMap(raw, selectorOk, label, refusals) {
243
+ if (!isPlainObject(raw)) {
244
+ refusals.add(label, "source_keys");
245
+ return null;
246
+ }
247
+ const names = Object.keys(raw);
248
+ if (names.length === 0 || names.length > MAX_KEYS) {
249
+ refusals.add(label, "source_keys");
250
+ return null;
251
+ }
252
+ let ok = validateVariableNames(names, label, refusals);
253
+ const out = {};
254
+ for (const name of [...names].sort()) {
255
+ const selector = raw[name];
256
+ if (typeof selector !== "string" || !selectorOk(selector)) {
257
+ refusals.add(label, "source_selector");
258
+ ok = false;
259
+ continue;
260
+ }
261
+ out[name] = selector;
262
+ }
263
+ return ok ? out : null;
264
+ }
265
+ function validateTargetName(value) {
266
+ if (typeof value !== "string" || value.length > 128)
267
+ return false;
268
+ const target = validateMcpTarget(value);
269
+ return target.ok && target.value === value;
270
+ }
271
+ function validateSource(raw, label, refusals) {
272
+ if (!isPlainObject(raw)) {
273
+ refusals.add(label, "source_shape");
274
+ return null;
275
+ }
276
+ switch (raw.kind) {
277
+ case "file": {
278
+ if (!hasOnlyKeys(raw, ["kind", "path"])) {
279
+ refusals.add(label, "source_shape");
280
+ return null;
281
+ }
282
+ if (!isAbsoluteSafePath(raw.path)) {
283
+ refusals.add(label, "source_path");
284
+ return null;
285
+ }
286
+ if (isWorkerEnvFileName(lastSegment(raw.path)) || isWorkerEnvFileName(lastSegment(raw.path).toLowerCase())) {
287
+ refusals.add(label, "source_dotenv_file");
288
+ return null;
289
+ }
290
+ return { kind: "file", path: raw.path };
291
+ }
292
+ case "file_keys": {
293
+ if (!hasOnlyKeys(raw, ["kind", "path", "format", "keys"])) {
294
+ refusals.add(label, "source_shape");
295
+ return null;
296
+ }
297
+ if (!isAbsoluteSafePath(raw.path)) {
298
+ refusals.add(label, "source_path");
299
+ return null;
300
+ }
301
+ if (raw.format !== "dotenv" && raw.format !== "json") {
302
+ refusals.add(label, "source_format");
303
+ return null;
304
+ }
305
+ const format = raw.format;
306
+ const keys = validateKeyMap(raw.keys, format === "dotenv" ? (s) => DOTENV_KEY_RE.test(s) : isJsonPointer, label, refusals);
307
+ return keys ? { kind: "file_keys", path: raw.path, format, keys } : null;
308
+ }
309
+ case "host_mcp_env": {
310
+ if (!hasOnlyKeys(raw, ["kind", "host", "server", "keys"])) {
311
+ refusals.add(label, "source_shape");
312
+ return null;
313
+ }
314
+ if (raw.host !== "claude" && raw.host !== "cursor") {
315
+ refusals.add(label, "source_host");
316
+ return null;
317
+ }
318
+ if (!validateTargetName(raw.server)) {
319
+ refusals.add(label, "source_shape");
320
+ return null;
321
+ }
322
+ const keys = validateKeyMap(raw.keys, (s) => HOST_ENV_KEY_RE.test(s), label, refusals);
323
+ return keys ? { kind: "host_mcp_env", host: raw.host, server: raw.server, keys } : null;
324
+ }
325
+ case "store_bundle": {
326
+ if (!hasOnlyKeys(raw, ["kind", "target", "keys"])) {
327
+ refusals.add(label, "source_shape");
328
+ return null;
329
+ }
330
+ if (!validateTargetName(raw.target)) {
331
+ refusals.add(label, "source_shape");
332
+ return null;
333
+ }
334
+ const keys = raw.keys;
335
+ if (!Array.isArray(keys) ||
336
+ keys.length === 0 ||
337
+ keys.length > MAX_KEYS ||
338
+ keys.some((k) => typeof k !== "string") ||
339
+ new Set(keys).size !== keys.length) {
340
+ refusals.add(label, "source_keys");
341
+ return null;
342
+ }
343
+ if (!validateVariableNames(keys, label, refusals))
344
+ return null;
345
+ return { kind: "store_bundle", target: raw.target, keys: [...keys].sort() };
346
+ }
347
+ default:
348
+ refusals.add(label, "source_kind");
349
+ return null;
350
+ }
351
+ }
352
+ function validateDestination(dest, label, refusals) {
353
+ if (typeof dest !== "string" || dest.length > 1024 || hasControlChars(dest)) {
354
+ refusals.add(label, "dest_invalid");
355
+ return null;
356
+ }
357
+ const safe = validateWorktreeRelativeCredentialPath(dest);
358
+ if (!safe.ok) {
359
+ refusals.add(label, "dest_invalid");
360
+ return null;
361
+ }
362
+ const segments = pathSegments(safe.value);
363
+ if (segments.length === 0) {
364
+ refusals.add(label, "dest_invalid");
365
+ return null;
366
+ }
367
+ if (segments.some((s) => CONTROL_PATH_SEGMENTS.has(s.toLowerCase()))) {
368
+ refusals.add(label, "dest_control_path");
369
+ return null;
370
+ }
371
+ const base = segments[segments.length - 1];
372
+ if (isWorkerEnvFileName(base) || isWorkerEnvFileName(base.toLowerCase())) {
373
+ refusals.add(label, "dest_dotenv");
374
+ return null;
375
+ }
376
+ return safe.value;
377
+ }
378
+ function validateConsumer(raw, label, refusals) {
379
+ if (!isPlainObject(raw)) {
380
+ refusals.add(label, "consumer_shape");
381
+ return null;
382
+ }
383
+ switch (raw.kind) {
384
+ case "worktree_file": {
385
+ if (!hasOnlyKeys(raw, ["kind", "dest"])) {
386
+ refusals.add(label, "consumer_shape");
387
+ return null;
388
+ }
389
+ const dest = validateDestination(raw.dest, label, refusals);
390
+ return dest === null ? null : { kind: "worktree_file", dest };
391
+ }
392
+ case "env":
393
+ if (!hasOnlyKeys(raw, ["kind"])) {
394
+ refusals.add(label, "consumer_shape");
395
+ return null;
396
+ }
397
+ return { kind: "env" };
398
+ case "mcp_server": {
399
+ if (!hasOnlyKeys(raw, ["kind", "server", "launch_fingerprint"])) {
400
+ refusals.add(label, "consumer_shape");
401
+ return null;
402
+ }
403
+ if (raw.server === "bapi") {
404
+ refusals.add(label, "mcp_server_bapi");
405
+ return null;
406
+ }
407
+ if (!validateTargetName(raw.server)) {
408
+ refusals.add(label, "mcp_server");
409
+ return null;
410
+ }
411
+ const consumer = { kind: "mcp_server", server: raw.server };
412
+ if (raw.launch_fingerprint !== undefined) {
413
+ if (typeof raw.launch_fingerprint !== "string" || !FINGERPRINT_RE.test(raw.launch_fingerprint)) {
414
+ refusals.add(label, "mcp_fingerprint");
415
+ return null;
416
+ }
417
+ consumer.launch_fingerprint = raw.launch_fingerprint;
418
+ }
419
+ return consumer;
420
+ }
421
+ default:
422
+ refusals.add(label, "consumer_kind");
423
+ return null;
424
+ }
425
+ }
426
+ function validateEntry(raw, index, refusals) {
427
+ const fallbackLabel = `entry ${index + 1}`;
428
+ if (!isPlainObject(raw)) {
429
+ refusals.add(fallbackLabel, "entry_shape");
430
+ return null;
431
+ }
432
+ const label = typeof raw.name === "string" && ENTRY_NAME_RE.test(raw.name) ? raw.name : fallbackLabel;
433
+ const before = refusals.list.length;
434
+ if (!hasOnlyKeys(raw, ["name", "level", "source", "consumers"]))
435
+ refusals.add(label, "entry_shape");
436
+ if (label === fallbackLabel)
437
+ refusals.add(label, "entry_name");
438
+ if (typeof raw.level !== "string" || !LEVELS.includes(raw.level)) {
439
+ refusals.add(label, "level");
440
+ }
441
+ const source = validateSource(raw.source, label, refusals);
442
+ const consumers = [];
443
+ if (!Array.isArray(raw.consumers) || raw.consumers.length > MAX_CONSUMERS) {
444
+ refusals.add(label, "consumers_list");
445
+ }
446
+ else {
447
+ for (const candidate of raw.consumers) {
448
+ const consumer = validateConsumer(candidate, label, refusals);
449
+ if (consumer)
450
+ consumers.push(consumer);
451
+ }
452
+ }
453
+ if (refusals.list.length > before || !source)
454
+ return null;
455
+ const level = raw.level;
456
+ // Level rules.
457
+ if (level === "production" && consumers.length > 0)
458
+ refusals.add(label, "consumer_production");
459
+ if (level === "restricted" && consumers.some((c) => c.kind !== "mcp_server")) {
460
+ refusals.add(label, "consumer_restricted");
461
+ }
462
+ // Source/consumer compatibility.
463
+ for (const consumer of consumers) {
464
+ const compatible = source.kind === "file" ? consumer.kind === "worktree_file" : consumer.kind !== "worktree_file";
465
+ if (!compatible)
466
+ refusals.add(label, "consumer_incompatible");
467
+ }
468
+ if (refusals.list.length > before)
469
+ return null;
470
+ return { name: raw.name, level, source, consumers };
471
+ }
472
+ function outputVariableNames(source) {
473
+ switch (source.kind) {
474
+ case "file":
475
+ return [];
476
+ case "file_keys":
477
+ case "host_mcp_env":
478
+ return Object.keys(source.keys);
479
+ case "store_bundle":
480
+ return [...source.keys];
481
+ }
482
+ }
483
+ function reachesWorkerEnvOrFile(entry) {
484
+ return entry.consumers.some((c) => c.kind === "worktree_file" || c.kind === "env");
485
+ }
486
+ function detectCollisions(entries, ctx, refusals) {
487
+ const names = new Set();
488
+ const dests = new Map();
489
+ const envVars = new Map();
490
+ const mcpVars = new Map();
491
+ for (const entry of entries) {
492
+ if (names.has(entry.name))
493
+ refusals.add(entry.name, "entry_name_duplicate");
494
+ names.add(entry.name);
495
+ const vars = outputVariableNames(entry.source);
496
+ for (const consumer of entry.consumers) {
497
+ if (consumer.kind === "worktree_file") {
498
+ const key = pathSegments(consumer.dest).join("/").toLowerCase();
499
+ const owner = dests.get(key);
500
+ if (owner !== undefined)
501
+ refusals.add(entry.name, "dest_duplicate");
502
+ else
503
+ dests.set(key, entry.name);
504
+ }
505
+ else if (consumer.kind === "env") {
506
+ for (const v of vars) {
507
+ const owner = envVars.get(v);
508
+ if (owner !== undefined && owner !== entry.name)
509
+ refusals.add(entry.name, "env_collision");
510
+ else if (owner === undefined)
511
+ envVars.set(v, entry.name);
512
+ }
513
+ }
514
+ }
515
+ const targets = new Set(entry.consumers.filter((c) => c.kind === "mcp_server").map((c) => mcpTargetForConsumer(c.server)));
516
+ for (const target of targets) {
517
+ for (const v of vars) {
518
+ const key = `${target}\u0000${v}`;
519
+ const owner = mcpVars.get(key);
520
+ if (owner !== undefined && owner !== entry.name)
521
+ refusals.add(entry.name, "mcp_collision");
522
+ else if (owner === undefined)
523
+ mcpVars.set(key, entry.name);
524
+ }
525
+ }
526
+ }
527
+ // One level per source: a restricted entry may not share a backing path with a
528
+ // sandbox file/file_keys entry that reaches a worktree or the shell.
529
+ const sandboxPaths = new Set();
530
+ for (const entry of entries) {
531
+ if (entry.level !== "sandbox" || !reachesWorkerEnvOrFile(entry))
532
+ continue;
533
+ if (entry.source.kind === "file" || entry.source.kind === "file_keys")
534
+ sandboxPaths.add(path.resolve(entry.source.path));
535
+ }
536
+ for (const entry of entries) {
537
+ if (entry.level !== "restricted")
538
+ continue;
539
+ if (backingPaths(entry.source, ctx).some((p) => sandboxPaths.has(p)))
540
+ refusals.add(entry.name, "one_level");
541
+ }
542
+ }
543
+ function orderedEntry(entry) {
544
+ return { name: entry.name, level: entry.level, source: entry.source, consumers: entry.consumers };
545
+ }
546
+ /**
547
+ * Validate a parsed record against the expected repository. Refusals are fixed
548
+ * text plus an entry label; nothing the owner wrote is echoed back. `context`
549
+ * supplies resolved host/store paths for the one-level-per-source check.
550
+ */
551
+ export function validateCredentialReferenceRecord(raw, expectedRepoName, context) {
552
+ const refusals = new Refusals();
553
+ if (!isPlainObject(raw) || !hasOnlyKeys(raw, ["version", "repo_name", "approved_at", "credentials"])) {
554
+ refusals.add("record", "record_shape");
555
+ return { ok: false, refusals: refusals.list };
556
+ }
557
+ if (raw.version !== CREDENTIAL_REFERENCES_VERSION)
558
+ refusals.add("record", "version");
559
+ if (raw.repo_name !== expectedRepoName)
560
+ refusals.add("record", "repository");
561
+ if (!isIsoTimestamp(raw.approved_at))
562
+ refusals.add("record", "approved_at");
563
+ if (!Array.isArray(raw.credentials) || raw.credentials.length > CREDENTIAL_REFERENCES_MAX_ENTRIES) {
564
+ refusals.add("record", "credentials_list");
565
+ }
566
+ if (refusals.list.length > 0)
567
+ return { ok: false, refusals: refusals.list };
568
+ const entries = [];
569
+ raw.credentials.forEach((candidate, index) => {
570
+ const entry = validateEntry(candidate, index, refusals);
571
+ if (entry)
572
+ entries.push(entry);
573
+ });
574
+ detectCollisions(entries, context, refusals);
575
+ if (refusals.list.length > 0)
576
+ return { ok: false, refusals: refusals.list };
577
+ return {
578
+ ok: true,
579
+ record: {
580
+ version: CREDENTIAL_REFERENCES_VERSION,
581
+ repo_name: expectedRepoName,
582
+ approved_at: raw.approved_at,
583
+ credentials: entries.map(orderedEntry),
584
+ },
585
+ };
586
+ }
587
+ // ---------------------------------------------------------------------------
588
+ // Record reader
589
+ // ---------------------------------------------------------------------------
590
+ /** The record path for a repository, or null when the name is unusable. */
591
+ export function credentialReferencesPath(repoName, deps) {
592
+ const resolved = repositoryStateRecordPath("worker-credentials", repoName, deps);
593
+ return resolved.ok ? resolved.path : null;
594
+ }
595
+ /** Serialize a record deterministically: 2-space indent and a trailing newline. */
596
+ export function formatCredentialReferenceRecord(record) {
597
+ return `${JSON.stringify(record, null, 2)}\n`;
598
+ }
599
+ /**
600
+ * Read the record for `repoName`. Only `ENOENT` is `absent`. The digest is the
601
+ * SHA-256 of the ORIGINAL bytes (never of parsed or reformatted JSON), `"absent"`
602
+ * for `ENOENT`, and null when the bytes cannot be read. Never throws.
603
+ */
604
+ export async function readCredentialReferenceRecord(repoName, deps) {
605
+ try {
606
+ const resolved = repositoryStateRecordPath("worker-credentials", repoName, deps);
607
+ if (!resolved.ok) {
608
+ return { state: "record_unusable", reason: "repository_name_unusable", digest: null, path: null };
609
+ }
610
+ let bytes;
611
+ try {
612
+ bytes = await deps.readBytes(resolved.path);
613
+ }
614
+ catch (err) {
615
+ if (errorCode(err) === "ENOENT")
616
+ return { state: "absent", digest: "absent", path: resolved.path };
617
+ return { state: "record_unusable", reason: "record_unreadable", digest: null, path: resolved.path };
618
+ }
619
+ const digest = sha256Hex(bytes);
620
+ const unusable = (reason) => ({
621
+ state: "record_unusable",
622
+ reason,
623
+ digest,
624
+ path: resolved.path,
625
+ });
626
+ let parsed;
627
+ try {
628
+ parsed = JSON.parse(Buffer.from(bytes).toString("utf-8"));
629
+ }
630
+ catch {
631
+ return unusable("record_invalid_json");
632
+ }
633
+ if (isPlainObject(parsed)) {
634
+ if (parsed.version !== CREDENTIAL_REFERENCES_VERSION)
635
+ return unusable("record_unsupported_version");
636
+ if (parsed.repo_name !== resolved.repoName)
637
+ return unusable("record_repository_mismatch");
638
+ }
639
+ const validated = validateCredentialReferenceRecord(parsed, resolved.repoName, await buildCredentialValidationContext(deps));
640
+ if (!validated.ok)
641
+ return unusable("record_invalid");
642
+ return { state: "ok", record: validated.record, digest, path: resolved.path };
643
+ }
644
+ catch {
645
+ return { state: "record_unusable", reason: "record_unreadable", digest: null, path: null };
646
+ }
647
+ }
648
+ // ---------------------------------------------------------------------------
649
+ // Source parsing
650
+ // ---------------------------------------------------------------------------
651
+ /** Parse dotenv text as inert data. Returns null on a syntax error or a duplicate key. */
652
+ function parseDotenv(text) {
653
+ const out = new Map();
654
+ for (const rawLine of text.split(/\r?\n/)) {
655
+ let line = rawLine.trim();
656
+ if (line === "" || line.startsWith("#"))
657
+ continue;
658
+ if (/^export\s/.test(line))
659
+ line = line.replace(/^export\s+/, "");
660
+ const eq = line.indexOf("=");
661
+ if (eq <= 0)
662
+ return null;
663
+ const key = line.slice(0, eq).trim();
664
+ if (!DOTENV_KEY_RE.test(key))
665
+ return null;
666
+ let value = line.slice(eq + 1).trim();
667
+ const first = value[0];
668
+ if (first === '"' || first === "'") {
669
+ if (value.length < 2 || value[value.length - 1] !== first)
670
+ return null;
671
+ value = value.slice(1, -1);
672
+ }
673
+ if (out.has(key))
674
+ return null;
675
+ out.set(key, value);
676
+ }
677
+ return out;
678
+ }
679
+ function selectJsonPointer(root, pointer) {
680
+ if (pointer === "")
681
+ return { found: true, value: root };
682
+ let node = root;
683
+ for (const rawToken of pointer.slice(1).split("/")) {
684
+ const token = rawToken.replace(/~1/g, "/").replace(/~0/g, "~");
685
+ if (Array.isArray(node)) {
686
+ if (!/^(0|[1-9]\d*)$/.test(token))
687
+ return { found: false };
688
+ const index = Number(token);
689
+ if (index >= node.length)
690
+ return { found: false };
691
+ node = node[index];
692
+ }
693
+ else if (isPlainObject(node)) {
694
+ if (!Object.prototype.hasOwnProperty.call(node, token))
695
+ return { found: false };
696
+ node = node[token];
697
+ }
698
+ else {
699
+ return { found: false };
700
+ }
701
+ }
702
+ return { found: true, value: node };
703
+ }
704
+ const REASON_PRECEDENCE = ["source_missing", "unreadable", "parse_error", "key_missing"];
705
+ function pickReason(reasons) {
706
+ for (const reason of REASON_PRECEDENCE)
707
+ if (reasons.includes(reason))
708
+ return reason;
709
+ return "unreadable";
710
+ }
711
+ /** Select every wanted variable, all or nothing. */
712
+ function selectAll(wanted) {
713
+ const values = {};
714
+ const reasons = [];
715
+ for (const item of wanted) {
716
+ const picked = item.pick();
717
+ if (typeof picked === "string") {
718
+ reasons.push(picked);
719
+ }
720
+ else if (picked.value.includes("\u0000")) {
721
+ reasons.push("parse_error");
722
+ }
723
+ else {
724
+ values[item.variable] = picked.value;
725
+ }
726
+ }
727
+ return reasons.length > 0 ? { ok: false, reason: pickReason(reasons) } : { ok: true, values };
728
+ }
729
+ function classifyFsError(err) {
730
+ return errorCode(err) === "ENOENT" ? "source_missing" : "unreadable";
731
+ }
732
+ /** Inspect a source as a regular file with a symlink-following stat. */
733
+ async function inspectRegularFile(filePath, deps) {
734
+ try {
735
+ await deps.lstat(filePath);
736
+ }
737
+ catch (err) {
738
+ return { ok: false, reason: classifyFsError(err) };
739
+ }
740
+ try {
741
+ const stat = await deps.stat(filePath);
742
+ if (!stat.isFile())
743
+ return { ok: false, reason: "unreadable" };
744
+ return { ok: true, stat };
745
+ }
746
+ catch (err) {
747
+ // A dangling symlink: lstat succeeded but its target is missing.
748
+ return { ok: false, reason: classifyFsError(err) };
749
+ }
750
+ }
751
+ async function resolveFileKeys(source, deps) {
752
+ const inspected = await inspectRegularFile(source.path, deps);
753
+ if (!inspected.ok)
754
+ return inspected;
755
+ if (inspected.stat.size > CREDENTIAL_REFERENCES_MAX_SOURCE_BYTES)
756
+ return { ok: false, reason: "unreadable" };
757
+ let bytes;
758
+ try {
759
+ bytes = await deps.readBytes(source.path);
760
+ }
761
+ catch (err) {
762
+ return { ok: false, reason: classifyFsError(err) };
763
+ }
764
+ if (bytes.length > CREDENTIAL_REFERENCES_MAX_SOURCE_BYTES)
765
+ return { ok: false, reason: "unreadable" };
766
+ const text = Buffer.from(bytes).toString("utf-8");
767
+ if (source.format === "dotenv") {
768
+ const parsed = parseDotenv(text);
769
+ if (!parsed)
770
+ return { ok: false, reason: "parse_error" };
771
+ return selectAll(Object.entries(source.keys).map(([variable, selector]) => ({
772
+ variable,
773
+ pick: () => (parsed.has(selector) ? { value: parsed.get(selector) } : "key_missing"),
774
+ })));
775
+ }
776
+ let doc;
777
+ try {
778
+ doc = JSON.parse(text);
779
+ }
780
+ catch {
781
+ return { ok: false, reason: "parse_error" };
782
+ }
783
+ return selectAll(Object.entries(source.keys).map(([variable, pointer]) => ({
784
+ variable,
785
+ pick: () => {
786
+ const found = selectJsonPointer(doc, pointer);
787
+ if (!found.found)
788
+ return "key_missing";
789
+ return typeof found.value === "string" ? { value: found.value } : "parse_error";
790
+ },
791
+ })));
792
+ }
793
+ async function resolveHostMcpEnv(source, deps) {
794
+ const configPath = hostConfigPath(source.host, deps.homedir(), deps.platform);
795
+ let text;
796
+ try {
797
+ text = await deps.readFile(configPath);
798
+ }
799
+ catch (err) {
800
+ return { ok: false, reason: classifyFsError(err) };
801
+ }
802
+ let doc;
803
+ try {
804
+ doc = JSON.parse(text);
805
+ }
806
+ catch {
807
+ return { ok: false, reason: "parse_error" };
808
+ }
809
+ const servers = isPlainObject(doc) && isPlainObject(doc.mcpServers) ? doc.mcpServers : null;
810
+ const server = servers && Object.prototype.hasOwnProperty.call(servers, source.server) ? servers[source.server] : undefined;
811
+ const env = isPlainObject(server) && isPlainObject(server.env) ? server.env : null;
812
+ return selectAll(Object.entries(source.keys).map(([variable, hostKey]) => ({
813
+ variable,
814
+ pick: () => {
815
+ if (!env || !Object.prototype.hasOwnProperty.call(env, hostKey))
816
+ return "key_missing";
817
+ const value = env[hostKey];
818
+ if (typeof value !== "string")
819
+ return "parse_error";
820
+ return value.length > 0 ? { value } : "key_missing";
821
+ },
822
+ })));
823
+ }
824
+ async function resolveStoreBundle(source, deps) {
825
+ // Never the env-first bundle helper: it returns ambient environment values first.
826
+ const resolution = await resolveCredentialStorePath(storeDepsFor(deps));
827
+ let storePath;
828
+ if (resolution.found) {
829
+ storePath = resolution.path;
830
+ }
831
+ else {
832
+ // The fallback stat error is swallowed by the resolver; classify it here.
833
+ try {
834
+ await deps.stat(resolution.fallbackPath);
835
+ return { ok: false, reason: "unreadable" };
836
+ }
837
+ catch (err) {
838
+ return { ok: false, reason: classifyFsError(err) };
839
+ }
840
+ }
841
+ let text;
842
+ try {
843
+ text = await deps.readFile(storePath);
844
+ }
845
+ catch (err) {
846
+ return { ok: false, reason: classifyFsError(err) };
847
+ }
848
+ const parsed = parseCredentialStoreJson(text);
849
+ if (!parsed.ok)
850
+ return { ok: false, reason: "parse_error" };
851
+ const store = parsed.value;
852
+ const bundle = Object.prototype.hasOwnProperty.call(store, source.target) ? store[source.target] : undefined;
853
+ return selectAll(source.keys.map((variable) => ({
854
+ variable,
855
+ pick: () => {
856
+ if (!bundle || !Object.prototype.hasOwnProperty.call(bundle, variable))
857
+ return "key_missing";
858
+ const trimmed = typeof bundle[variable] === "string" ? bundle[variable].trim() : "";
859
+ return trimmed.length > 0 ? { value: trimmed } : "key_missing";
860
+ },
861
+ })));
862
+ }
863
+ async function backingPathsFor(source, deps) {
864
+ switch (source.kind) {
865
+ case "file":
866
+ case "file_keys":
867
+ return [source.path];
868
+ case "host_mcp_env":
869
+ return [hostConfigPath(source.host, deps.homedir(), deps.platform)];
870
+ case "store_bundle":
871
+ return storeBackingPaths(deps);
872
+ }
873
+ }
874
+ /** Resolve one source. Never throws; an unexpected failure is `unreadable`. */
875
+ async function resolveSource(source, deps, options) {
876
+ try {
877
+ if (options?.excludedRoots && options.excludedRoots.length > 0) {
878
+ const backing = await backingPathsFor(source, deps);
879
+ if (backing.some((p) => options.excludedRoots.some((root) => isWithinRoot(p, root)))) {
880
+ return { ok: false, reason: "unreadable" };
881
+ }
882
+ }
883
+ if (source.kind === "file") {
884
+ const inspected = await inspectRegularFile(source.path, deps);
885
+ return inspected.ok ? { ok: true, kind: "file", path: source.path } : inspected;
886
+ }
887
+ const resolved = source.kind === "file_keys"
888
+ ? await resolveFileKeys(source, deps)
889
+ : source.kind === "host_mcp_env"
890
+ ? await resolveHostMcpEnv(source, deps)
891
+ : await resolveStoreBundle(source, deps);
892
+ return resolved.ok ? { ok: true, kind: "keys", values: resolved.values } : resolved;
893
+ }
894
+ catch {
895
+ return { ok: false, reason: "unreadable" };
896
+ }
897
+ }
898
+ // ---------------------------------------------------------------------------
899
+ // Status mapping
900
+ // ---------------------------------------------------------------------------
901
+ function stateForReason(reason) {
902
+ return reason === "source_missing" || reason === "key_missing" || reason === "launch_mismatch" ? "missing" : "unreadable";
903
+ }
904
+ function statusFor(entry, reason, sourcePaths) {
905
+ const status = {
906
+ name: entry.name,
907
+ level: entry.level,
908
+ state: reason === null ? "present" : stateForReason(reason),
909
+ consumers: entry.consumers,
910
+ };
911
+ if (reason !== null)
912
+ status.reason = reason;
913
+ if (sourcePaths)
914
+ status.source_paths = sourcePaths;
915
+ return status;
916
+ }
917
+ /**
918
+ * Sandbox entries for a worker launch: `worktree_file` specs and a merged shell
919
+ * variable map. Never a restricted or production entry, never an MCP-only piece.
920
+ */
921
+ export async function forWorkerLaunch(repoName, deps, options) {
922
+ const result = { state: "absent", files: [], env: {}, unavailable: [] };
923
+ try {
924
+ const read = await readCredentialReferenceRecord(repoName, deps);
925
+ result.state = read.state;
926
+ if (read.state !== "ok")
927
+ return result;
928
+ for (const entry of read.record.credentials) {
929
+ if (entry.level !== "sandbox")
930
+ continue;
931
+ const fileConsumers = entry.consumers.filter((c) => c.kind === "worktree_file");
932
+ const wantsEnv = entry.consumers.some((c) => c.kind === "env");
933
+ if (fileConsumers.length === 0 && !wantsEnv)
934
+ continue;
935
+ const resolved = await resolveSource(entry.source, deps, options);
936
+ if (!resolved.ok) {
937
+ result.unavailable.push({ name: entry.name, reason: resolved.reason });
938
+ continue;
939
+ }
940
+ if (resolved.kind === "file") {
941
+ for (const consumer of fileConsumers) {
942
+ result.files.push({ name: entry.name, source: resolved.path, dest: consumer.dest });
943
+ }
944
+ }
945
+ else if (wantsEnv) {
946
+ Object.assign(result.env, resolved.values);
947
+ }
948
+ }
949
+ }
950
+ catch {
951
+ result.files = [];
952
+ result.env = {};
953
+ result.state = "record_unusable";
954
+ }
955
+ return result;
956
+ }
957
+ /**
958
+ * Variables for one MCP server target: sandbox and restricted entries with an
959
+ * `mcp_server` consumer naming it (`bridge` matches the `bapi` target). Never a
960
+ * production entry and never a non-MCP piece of a restricted entry. A
961
+ * fingerprinted consumer needs a matching `launch`; otherwise it is withheld as
962
+ * `launch_mismatch`, reported only when every consumer for the target fails.
963
+ */
964
+ export async function forMcpServer(server, launch, repoName, deps, options) {
965
+ const result = { state: "absent", env: {}, unavailable: [] };
966
+ try {
967
+ const target = mcpTargetForConsumer(server);
968
+ const read = await readCredentialReferenceRecord(repoName, deps);
969
+ result.state = read.state;
970
+ if (read.state !== "ok")
971
+ return result;
972
+ const launchFingerprint = launch ? computeLaunchFingerprint(launch.command, launch.args) : null;
973
+ for (const entry of read.record.credentials) {
974
+ if (entry.level === "production")
975
+ continue;
976
+ const forTarget = entry.consumers.filter((c) => c.kind === "mcp_server" && mcpTargetForConsumer(c.server) === target);
977
+ if (forTarget.length === 0)
978
+ continue;
979
+ const eligible = forTarget.some((c) => c.launch_fingerprint === undefined || (launchFingerprint !== null && c.launch_fingerprint === launchFingerprint));
980
+ if (!eligible) {
981
+ result.unavailable.push({ name: entry.name, reason: "launch_mismatch" });
982
+ continue;
983
+ }
984
+ // One resolution per entry, however many eligible consumers it has.
985
+ const resolved = await resolveSource(entry.source, deps, options);
986
+ if (!resolved.ok)
987
+ result.unavailable.push({ name: entry.name, reason: resolved.reason });
988
+ else if (resolved.kind === "keys")
989
+ Object.assign(result.env, resolved.values);
990
+ }
991
+ }
992
+ catch {
993
+ result.env = {};
994
+ result.state = "record_unusable";
995
+ }
996
+ return result;
997
+ }
998
+ /**
999
+ * Names-only status for EVERY entry, production included. Returns no values.
1000
+ * Restricted entries also carry their approved backing path(s), even when the
1001
+ * source is missing or unreadable.
1002
+ */
1003
+ export async function statusOnly(repoName, deps, options) {
1004
+ let read;
1005
+ try {
1006
+ read = await readCredentialReferenceRecord(repoName, deps);
1007
+ }
1008
+ catch {
1009
+ return { state: "record_unusable", record_digest: null, record_path: null, reason: "record_unreadable", statuses: [] };
1010
+ }
1011
+ if (read.state === "absent") {
1012
+ return { state: "absent", record_digest: "absent", record_path: read.path, statuses: [] };
1013
+ }
1014
+ if (read.state === "record_unusable") {
1015
+ return {
1016
+ state: "record_unusable",
1017
+ record_digest: read.digest,
1018
+ record_path: read.path,
1019
+ reason: read.reason,
1020
+ statuses: [],
1021
+ };
1022
+ }
1023
+ const statuses = [];
1024
+ for (const entry of read.record.credentials) {
1025
+ let sourcePaths;
1026
+ if (entry.level === "restricted") {
1027
+ try {
1028
+ sourcePaths = await backingPathsFor(entry.source, deps);
1029
+ }
1030
+ catch {
1031
+ sourcePaths = [];
1032
+ }
1033
+ }
1034
+ const resolved = await resolveSource(entry.source, deps, options);
1035
+ statuses.push(statusFor(entry, resolved.ok ? null : resolved.reason, sourcePaths));
1036
+ }
1037
+ return { state: "ok", record_digest: read.digest, record_path: read.path, statuses };
1038
+ }
1039
+ let tempCounter = 0;
1040
+ function defaultTempSuffix() {
1041
+ tempCounter += 1;
1042
+ return `${process.pid}.${tempCounter}`;
1043
+ }
1044
+ /**
1045
+ * Publish a record durably, following `writeMcpGrant()`: a same-directory
1046
+ * exclusive temp file (mode 0600), write, fsync, close, chmod, atomic rename
1047
+ * (the commit point), then a best-effort directory fsync. The directory is held at
1048
+ * 0700 on POSIX. A failure before the rename leaves the previous record in place.
1049
+ */
1050
+ async function writeRecordFile(record, recordPath, deps) {
1051
+ const isPosix = deps.platform !== "win32";
1052
+ const dir = path.dirname(recordPath);
1053
+ const tempPath = path.join(dir, `${path.basename(recordPath)}.${(deps.tempSuffix ?? defaultTempSuffix)()}.tmp`);
1054
+ let handle;
1055
+ try {
1056
+ await deps.mkdir(dir, { recursive: true });
1057
+ if (isPosix)
1058
+ await deps.chmod(dir, 0o700);
1059
+ handle = await deps.open(tempPath, "wx", isPosix ? 0o600 : undefined);
1060
+ await handle.writeFile(formatCredentialReferenceRecord(record), { encoding: "utf-8" });
1061
+ await handle.sync();
1062
+ await handle.close();
1063
+ handle = undefined;
1064
+ if (isPosix)
1065
+ await deps.chmod(tempPath, 0o600);
1066
+ await deps.rename(tempPath, recordPath);
1067
+ }
1068
+ catch {
1069
+ if (handle) {
1070
+ try {
1071
+ await handle.close();
1072
+ }
1073
+ catch {
1074
+ /* a close failure must not mask the write failure */
1075
+ }
1076
+ }
1077
+ if (deps.unlink) {
1078
+ try {
1079
+ await deps.unlink(tempPath);
1080
+ }
1081
+ catch {
1082
+ /* best-effort cleanup; the previous record is untouched */
1083
+ }
1084
+ }
1085
+ return { ok: false };
1086
+ }
1087
+ if (isPosix) {
1088
+ try {
1089
+ const dirHandle = await deps.open(dir, "r");
1090
+ try {
1091
+ await dirHandle.sync();
1092
+ }
1093
+ finally {
1094
+ await dirHandle.close();
1095
+ }
1096
+ }
1097
+ catch {
1098
+ /* best-effort: the file itself was fsynced and renamed */
1099
+ }
1100
+ }
1101
+ return { ok: true };
1102
+ }
1103
+ /** True when a node (outside `keys` maps) carries a value-shaped field. */
1104
+ function hasValueShapedField(node, depth = 0) {
1105
+ if (depth > 8)
1106
+ return true;
1107
+ if (Array.isArray(node))
1108
+ return node.some((child) => hasValueShapedField(child, depth + 1));
1109
+ if (!isPlainObject(node))
1110
+ return false;
1111
+ for (const [key, child] of Object.entries(node)) {
1112
+ if (VALUE_SHAPED_FIELDS.has(key))
1113
+ return true;
1114
+ if (key === "env" && isPlainObject(child) && Object.values(child).every((v) => typeof v === "string"))
1115
+ return true;
1116
+ // `keys` maps are reference data (variable name -> selector), not field names.
1117
+ if (key === "keys")
1118
+ continue;
1119
+ if (hasValueShapedField(child, depth + 1))
1120
+ return true;
1121
+ }
1122
+ return false;
1123
+ }
1124
+ /** Validate proposal text and build the full record. Writes nothing. */
1125
+ export async function buildRecordFromProposal(proposalText, repoName, deps, now) {
1126
+ const refusals = new Refusals();
1127
+ let raw;
1128
+ try {
1129
+ raw = JSON.parse(proposalText);
1130
+ }
1131
+ catch {
1132
+ refusals.add("proposal", "record_shape");
1133
+ return { ok: false, refusals: refusals.list };
1134
+ }
1135
+ if (hasValueShapedField(raw)) {
1136
+ refusals.add("proposal", "value_shaped");
1137
+ return { ok: false, refusals: refusals.list };
1138
+ }
1139
+ if (!isPlainObject(raw) || !hasOnlyKeys(raw, ["credentials"]) || !Array.isArray(raw.credentials)) {
1140
+ refusals.add("proposal", "record_shape");
1141
+ return { ok: false, refusals: refusals.list };
1142
+ }
1143
+ const candidate = {
1144
+ version: CREDENTIAL_REFERENCES_VERSION,
1145
+ repo_name: repoName,
1146
+ approved_at: now().toISOString(),
1147
+ credentials: raw.credentials,
1148
+ };
1149
+ return validateCredentialReferenceRecord(candidate, repoName, await buildCredentialValidationContext(deps));
1150
+ }
1151
+ function diffEntries(current, next) {
1152
+ const before = new Map(current.credentials.map((e) => [e.name, JSON.stringify(e)]));
1153
+ const after = new Map(next.credentials.map((e) => [e.name, JSON.stringify(e)]));
1154
+ const added = [...after.keys()].filter((n) => !before.has(n)).sort();
1155
+ const removed = [...before.keys()].filter((n) => !after.has(n)).sort();
1156
+ const changed = [...after.keys()].filter((n) => before.has(n) && before.get(n) !== after.get(n)).sort();
1157
+ return { added, removed, changed };
1158
+ }
1159
+ /**
1160
+ * Replace the whole record. Validates first; then, under the credential-store
1161
+ * lock, re-reads the current bytes and refuses unless their digest equals
1162
+ * `expectDigest`. Never throws; failures are fixed text.
1163
+ */
1164
+ export async function applyCredentialReferences(input) {
1165
+ const { repoName, proposalText, expectDigest, deps } = input;
1166
+ try {
1167
+ const resolved = repositoryStateRecordPath("worker-credentials", repoName, deps);
1168
+ if (!resolved.ok) {
1169
+ return { ok: false, kind: "repository", message: "the repository name is not usable as a record name" };
1170
+ }
1171
+ const built = await buildRecordFromProposal(proposalText, resolved.repoName, deps, deps.approvedAt ?? (() => new Date()));
1172
+ if (!built.ok) {
1173
+ return { ok: false, kind: "validation", message: "the proposal was refused; nothing was written", refusals: built.refusals };
1174
+ }
1175
+ const record = built.record;
1176
+ const outcome = await withCredentialStoreLock({ ...deps, readFile: deps.readFile }, async () => {
1177
+ const current = await readCredentialReferenceRecord(resolved.repoName, deps);
1178
+ if (current.digest === null) {
1179
+ return {
1180
+ ok: false,
1181
+ kind: "current_unreadable",
1182
+ message: "the current record could not be read; nothing was written",
1183
+ };
1184
+ }
1185
+ if (current.digest !== expectDigest) {
1186
+ return {
1187
+ ok: false,
1188
+ kind: "stale_digest",
1189
+ message: "the record changed since it was listed; nothing was written",
1190
+ changes: current.state === "ok" ? diffEntries(current.record, record) : current.state === "absent" ? diffEntries({ ...record, credentials: [] }, record) : null,
1191
+ };
1192
+ }
1193
+ const written = await writeRecordFile(record, resolved.path, deps);
1194
+ if (!written.ok) {
1195
+ return { ok: false, kind: "write", message: "the record could not be written; the previous record is unchanged" };
1196
+ }
1197
+ return { ok: true, record, path: resolved.path, status: await statusOnly(resolved.repoName, deps) };
1198
+ }, () => ({ ok: false, kind: "lock", message: "exclusive credential storage could not be acquired; nothing was written" }), true);
1199
+ return outcome;
1200
+ }
1201
+ catch {
1202
+ return { ok: false, kind: "write", message: "the record could not be applied; the previous record is unchanged" };
1203
+ }
1204
+ }
1205
+ export function describeSource(source) {
1206
+ switch (source.kind) {
1207
+ case "file":
1208
+ return { kind: "file", location: source.path, key_names: [] };
1209
+ case "file_keys":
1210
+ return {
1211
+ kind: "file_keys",
1212
+ location: source.path,
1213
+ key_names: Object.entries(source.keys).map(([variable, selector]) => `${variable}<-${selector || "(whole document)"}`),
1214
+ };
1215
+ case "host_mcp_env":
1216
+ return {
1217
+ kind: "host_mcp_env",
1218
+ location: `${source.host} MCP server ${source.server}`,
1219
+ key_names: Object.entries(source.keys).map(([variable, key]) => `${variable}<-${key}`),
1220
+ };
1221
+ case "store_bundle":
1222
+ return { kind: "store_bundle", location: `credential store target ${source.target}`, key_names: [...source.keys] };
1223
+ }
1224
+ }
1225
+ export function describeConsumer(consumer) {
1226
+ switch (consumer.kind) {
1227
+ case "worktree_file":
1228
+ return `worktree file ${consumer.dest}`;
1229
+ case "env":
1230
+ return "shell variables";
1231
+ case "mcp_server":
1232
+ return `MCP server ${consumer.server}`;
1233
+ }
1234
+ }
1235
+ /** Project the validated record plus shared status into value-free metadata. */
1236
+ export function projectCredentialMetadata(record, statuses) {
1237
+ const byName = new Map(statuses.map((s) => [s.name, s]));
1238
+ return record.credentials.map((entry) => {
1239
+ const status = byName.get(entry.name);
1240
+ return {
1241
+ name: entry.name,
1242
+ level: entry.level,
1243
+ source: describeSource(entry.source),
1244
+ consumers: entry.consumers.map(describeConsumer),
1245
+ status: status
1246
+ ? {
1247
+ state: status.state,
1248
+ ...(status.reason ? { reason: status.reason } : {}),
1249
+ ...(status.source_paths ? { source_paths: status.source_paths } : {}),
1250
+ }
1251
+ : null,
1252
+ excluded_from_delivery: entry.level === "production",
1253
+ };
1254
+ });
1255
+ }
1256
+ function statusText(status) {
1257
+ if (!status)
1258
+ return "not checked";
1259
+ return status.reason ? `${status.state} (${status.reason})` : status.state;
1260
+ }
1261
+ function entryLines(entry, indent) {
1262
+ const lines = [
1263
+ `${indent}${entry.name} [${entry.level}]${entry.excluded_from_delivery ? " excluded from delivery" : ""}`,
1264
+ `${indent} source: ${entry.source.kind}, ${entry.source.location}`,
1265
+ ];
1266
+ if (entry.source.key_names.length > 0)
1267
+ lines.push(`${indent} keys: ${entry.source.key_names.join(", ")}`);
1268
+ lines.push(`${indent} consumers: ${entry.consumers.length > 0 ? entry.consumers.join("; ") : "none"}`);
1269
+ lines.push(`${indent} status: ${statusText(entry.status)}`);
1270
+ if (entry.status?.source_paths && entry.status.source_paths.length > 0) {
1271
+ lines.push(`${indent} source paths: ${entry.status.source_paths.join(", ")}`);
1272
+ }
1273
+ return lines;
1274
+ }
1275
+ const RECORD_UNUSABLE_TEXT = {
1276
+ repository_name_unusable: "the repository name is not usable as a record name",
1277
+ record_unreadable: "the record file could not be read",
1278
+ record_invalid_json: "the record file is not valid JSON",
1279
+ record_unsupported_version: "the record file has an unsupported version",
1280
+ record_repository_mismatch: "the record file names a different repository",
1281
+ record_invalid: "the record file failed validation",
1282
+ };
1283
+ export function describeRecordUnusable(reason) {
1284
+ return reason ? RECORD_UNUSABLE_TEXT[reason] : "the record file cannot be used";
1285
+ }
1286
+ /** Text for `credentials references list`. Names and locations only. */
1287
+ export function formatCredentialReferenceList(repoName, result, record) {
1288
+ if (result.state === "absent")
1289
+ return `No worker credential references are recorded for ${repoName}.`;
1290
+ if (result.state === "record_unusable" || !record) {
1291
+ return [
1292
+ `The worker credential references record for ${repoName} cannot be used: ${describeRecordUnusable(result.reason)}.`,
1293
+ "Workers receive no referenced credentials until it is replaced.",
1294
+ ].join("\n");
1295
+ }
1296
+ const metadata = projectCredentialMetadata(record, result.statuses);
1297
+ if (metadata.length === 0)
1298
+ return `The worker credential references record for ${repoName} lists no credentials.`;
1299
+ const lines = [`Worker credential references for ${repoName} (${metadata.length}):`];
1300
+ for (const entry of metadata) {
1301
+ lines.push("");
1302
+ lines.push(...entryLines(entry, " "));
1303
+ }
1304
+ return lines.join("\n");
1305
+ }
1306
+ /** JSON for `credentials references list --json`. */
1307
+ export function credentialReferenceListJson(repoName, result, record) {
1308
+ return {
1309
+ repo_name: repoName,
1310
+ state: result.state,
1311
+ record_digest: result.record_digest,
1312
+ ...(result.reason ? { reason: result.reason } : {}),
1313
+ credentials: record ? projectCredentialMetadata(record, result.statuses) : [],
1314
+ };
1315
+ }
1316
+ /** Status lines printed after a successful apply. */
1317
+ export function formatApplyStatusLines(result) {
1318
+ const lines = [];
1319
+ for (const status of result.statuses) {
1320
+ const suffix = status.reason ? ` (${status.reason})` : "";
1321
+ lines.push(` ${status.name} [${status.level}]: ${status.state}${suffix}`);
1322
+ if (status.state !== "present") {
1323
+ lines.push(` warning: this source is ${status.state === "missing" ? "missing" : "not readable"}; workers will not receive it until it is fixed.`);
1324
+ }
1325
+ }
1326
+ return lines;
1327
+ }
1328
+ async function recordModeTooWide(recordPath, deps) {
1329
+ if (deps.platform === "win32" || recordPath === null)
1330
+ return null;
1331
+ try {
1332
+ return ((await deps.stat(recordPath)).mode & 0o077) !== 0;
1333
+ }
1334
+ catch {
1335
+ return null;
1336
+ }
1337
+ }
1338
+ /** Collect the diagnostic. Read-only; never throws or writes. */
1339
+ export async function collectCredentialReferenceDiagnostic(deps) {
1340
+ if (deps.repoName === null)
1341
+ return { state: "no_repository" };
1342
+ const repoName = deps.repoName;
1343
+ try {
1344
+ const read = await readCredentialReferenceRecord(repoName, deps);
1345
+ if (read.state === "absent")
1346
+ return { state: "absent", repoName };
1347
+ if (read.state === "record_unusable") {
1348
+ return {
1349
+ state: "unusable",
1350
+ repoName,
1351
+ reason: read.reason,
1352
+ modeTooWide: await recordModeTooWide(read.path, deps),
1353
+ };
1354
+ }
1355
+ const status = await statusOnly(repoName, deps);
1356
+ return {
1357
+ state: "present",
1358
+ repoName,
1359
+ entries: projectCredentialMetadata(read.record, status.statuses),
1360
+ modeTooWide: await recordModeTooWide(read.path, deps),
1361
+ };
1362
+ }
1363
+ catch {
1364
+ return { state: "unusable", repoName, reason: "record_unreadable", modeTooWide: null };
1365
+ }
1366
+ }
1367
+ /** Render the doctor section. Names, approved locations, and closed reasons only. */
1368
+ export function formatCredentialReferenceDiagnosticReport(diagnostic) {
1369
+ const lines = ["", "Worker credential references (advisory)", ""];
1370
+ const modeLines = (modeTooWide) => modeTooWide === true
1371
+ ? [" WARNING the record file is readable or writable by other users; its mode should be 0600."]
1372
+ : modeTooWide === null
1373
+ ? [" NOTE the record file's permissions could not be checked."]
1374
+ : [];
1375
+ switch (diagnostic.state) {
1376
+ case "no_repository":
1377
+ lines.push(" NOT CHECKED the repository name could not be resolved from this folder.");
1378
+ break;
1379
+ case "absent":
1380
+ lines.push(` ABSENT no credential references for ${diagnostic.repoName}. Workers receive no referenced credentials.`);
1381
+ break;
1382
+ case "unusable":
1383
+ lines.push(` UNUSABLE the credential references for ${diagnostic.repoName} cannot be used: ${describeRecordUnusable(diagnostic.reason)}.`, " Workers receive no referenced credentials and keep working.", ...modeLines(diagnostic.modeTooWide));
1384
+ break;
1385
+ case "present":
1386
+ lines.push(` PRESENT ${diagnostic.entries.length} credential reference(s) for ${diagnostic.repoName}`);
1387
+ for (const entry of diagnostic.entries)
1388
+ lines.push(...entryLines(entry, " "));
1389
+ lines.push(...modeLines(diagnostic.modeTooWide));
1390
+ break;
1391
+ }
1392
+ lines.push(" Reference values are never printed. Production entries are inspected but never delivered.");
1393
+ return lines.join("\n");
1394
+ }