@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,280 @@
1
+ /**
2
+ * BAPI-1647: shared, value-free pieces of referenced-credential delivery.
3
+ *
4
+ * Child 1 (`credential-references.ts`, BAPI-1646) owns the record and the three
5
+ * resolvers. This module adds what every DELIVERY channel needs on top of them,
6
+ * without becoming a second credential authority:
7
+ *
8
+ * - a closed vocabulary of delivery OUTCOMES (occupied destination, failed
9
+ * exclusion, reserved name, …), kept separate from child 1's source
10
+ * `CredentialStatusReason` so neither vocabulary drifts;
11
+ * - one fixed-text notice formatter that accepts only validated names and
12
+ * closed reasons, so no value, path, or exception text can reach a notice;
13
+ * - names-only projections of a validated record (which entry owns which
14
+ * variable, which file destinations are approved, which MCP keys a target
15
+ * is declared to receive), never a resolved value;
16
+ * - the MCP declaration-eligibility rule shared by the validators,
17
+ * provisioning, and the shim;
18
+ * - production resolver dependencies that refuse to read a source that sits
19
+ * inside the launch worktree.
20
+ *
21
+ * Nothing here reads a credential value except through the injected child 1
22
+ * resolver dependencies, and nothing here returns one.
23
+ */
24
+ import { realpath as fsRealpath } from "fs/promises";
25
+ import path from "path";
26
+ import { computeLaunchFingerprint, mcpTargetForConsumer, readCredentialReferenceRecord, } from "./credential-references.js";
27
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
28
+ import { getThirdPartyTargetDefinition } from "./third-party-mcp-targets.js";
29
+ const REASON_TEXT = {
30
+ source_missing: "its source is missing (source_missing)",
31
+ unreadable: "its source could not be read (unreadable)",
32
+ parse_error: "its source could not be parsed (parse_error)",
33
+ key_missing: "a key it needs is missing from its source (key_missing)",
34
+ launch_mismatch: "the MCP server launch no longer matches the approved launch (launch_mismatch)",
35
+ dest_occupied: "its destination is already occupied by another file or link",
36
+ dest_unsafe: "its destination is not safely inside the worktree",
37
+ dest_unavailable: "its destination could not be inspected",
38
+ exclude_failed: "its destination could not be added to the local git exclude",
39
+ windows_gated: "not supported on Windows yet",
40
+ reserved_name: "the variable name is reserved for the worker environment",
41
+ name_collision: "the variable name is already set by the worker environment",
42
+ reconcile_failed: "an earlier Bridge link for it could not be removed",
43
+ state_write_failed: "Bridge could not record the link it would create",
44
+ restricted_launcher: "a restricted credential is never given to a server launched from inside the worktree",
45
+ };
46
+ /** Prompt- and log-safe name rule (entry names and variable names both satisfy it). */
47
+ const SAFE_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/;
48
+ function safeName(name) {
49
+ return SAFE_NAME_RE.test(name) ? name : "(unnamed credential)";
50
+ }
51
+ /** Fixed text for one notice. Never a value, a path, or exception text. */
52
+ export function formatCredentialNotice(notice) {
53
+ return `credential '${safeName(notice.name)}' was not provided: ${REASON_TEXT[notice.reason]}`;
54
+ }
55
+ /** The one notice for a record that cannot be used: zero credentials delivered. */
56
+ export function formatRecordUnusableNotice(reason) {
57
+ return `the approved credential reference record could not be used${reason ? ` (${reason})` : ""}; no referenced credentials were provided`;
58
+ }
59
+ /** Drop exact duplicates while keeping first-seen order. */
60
+ export function dedupeNotices(notices) {
61
+ const seen = new Set();
62
+ const out = [];
63
+ for (const notice of notices) {
64
+ const key = `${notice.name}\u0000${notice.reason}`;
65
+ if (seen.has(key))
66
+ continue;
67
+ seen.add(key);
68
+ out.push(notice);
69
+ }
70
+ return out;
71
+ }
72
+ /**
73
+ * All notice lines for one launch: at most one record-level line (so
74
+ * `record_unusable` is reported once however many resolvers ran) followed by
75
+ * the deduplicated per-credential lines.
76
+ */
77
+ export function formatNoticeLines(recordState, notices, recordReason) {
78
+ if (recordState === "record_unusable")
79
+ return [formatRecordUnusableNotice(recordReason)];
80
+ return dedupeNotices(notices).map(formatCredentialNotice);
81
+ }
82
+ /** The output variable names a source is declared to produce. A `file` source has none. */
83
+ export function declaredOutputKeys(source) {
84
+ if (source.kind === "file")
85
+ return [];
86
+ if (source.kind === "store_bundle")
87
+ return [...source.keys];
88
+ return Object.keys(source.keys);
89
+ }
90
+ export function emptyApprovalMetadata() {
91
+ return { files: [], envOwners: {}, mcp: [], keyLevels: {} };
92
+ }
93
+ /** Project a validated record to names-only metadata. Never reads a source. */
94
+ export function projectApprovalMetadata(record) {
95
+ const meta = emptyApprovalMetadata();
96
+ if (!record)
97
+ return meta;
98
+ for (const entry of record.credentials) {
99
+ if (entry.level === "production")
100
+ continue;
101
+ const keys = declaredOutputKeys(entry.source);
102
+ for (const key of keys) {
103
+ // The stricter level wins if two entries ever named one key.
104
+ if (meta.keyLevels[key] !== "restricted")
105
+ meta.keyLevels[key] = entry.level;
106
+ }
107
+ for (const consumer of entry.consumers) {
108
+ if (consumer.kind === "worktree_file" && entry.level === "sandbox") {
109
+ meta.files.push({ entry: entry.name, dest: consumer.dest });
110
+ }
111
+ else if (consumer.kind === "env" && entry.level === "sandbox") {
112
+ for (const key of keys)
113
+ meta.envOwners[key] = entry.name;
114
+ }
115
+ else if (consumer.kind === "mcp_server") {
116
+ meta.mcp.push({
117
+ entry: entry.name,
118
+ level: entry.level,
119
+ target: mcpTargetForConsumer(consumer.server),
120
+ ...(consumer.launch_fingerprint !== undefined ? { launchFingerprint: consumer.launch_fingerprint } : {}),
121
+ keys,
122
+ });
123
+ }
124
+ }
125
+ }
126
+ return meta;
127
+ }
128
+ /** One explicit, names-only record read for a launch. Never throws. */
129
+ export async function readApprovalMetadata(repoName, deps) {
130
+ try {
131
+ const read = await readCredentialReferenceRecord(repoName, deps);
132
+ if (read.state === "ok")
133
+ return { state: "ok", metadata: projectApprovalMetadata(read.record) };
134
+ if (read.state === "absent")
135
+ return { state: "absent", metadata: emptyApprovalMetadata() };
136
+ return { state: "record_unusable", reason: read.reason, metadata: emptyApprovalMetadata() };
137
+ }
138
+ catch {
139
+ return { state: "record_unusable", reason: "record_unreadable", metadata: emptyApprovalMetadata() };
140
+ }
141
+ }
142
+ /** Remove restricted entries' keys from a merged resolver value map. */
143
+ export function withoutRestrictedKeys(values, metadata) {
144
+ const out = {};
145
+ const removed = [];
146
+ for (const [key, value] of Object.entries(values)) {
147
+ if (metadata.keyLevels[key] === "restricted")
148
+ removed.push(key);
149
+ else
150
+ out[key] = value;
151
+ }
152
+ return { values: out, removed };
153
+ }
154
+ /** Entry names of restricted MCP declarations for a target (for notices). */
155
+ export function restrictedEntriesForTarget(metadata, target) {
156
+ const t = mcpTargetForConsumer(target);
157
+ return [...new Set(metadata.mcp.filter((d) => d.target === t && d.level === "restricted").map((d) => d.entry))];
158
+ }
159
+ /**
160
+ * Whether a target is REFERENCE-BACKED for a given launch: non-production
161
+ * declarations naming the target, matching the launch fingerprint when required
162
+ * (or whenever a declaration carries one), collectively cover every key the
163
+ * registry requires. Independent of source availability: an eligible target
164
+ * stays launchable when a source later turns out missing.
165
+ */
166
+ export function mcpReferenceEligibility(metadata, target, launch, options) {
167
+ const t = mcpTargetForConsumer(target);
168
+ const fingerprint = launch ? computeLaunchFingerprint(launch.command, launch.args) : null;
169
+ const matched = metadata.mcp.filter((d) => {
170
+ if (d.target !== t || d.level === "production")
171
+ return false;
172
+ if (d.launchFingerprint === undefined)
173
+ return !options.requireFingerprint;
174
+ if (options.ignoreFingerprintMatch === true)
175
+ return true;
176
+ return fingerprint !== null && d.launchFingerprint === fingerprint;
177
+ });
178
+ const keys = [...new Set(matched.flatMap((d) => d.keys))].sort();
179
+ if (matched.length === 0)
180
+ return { eligible: false, matched, keys };
181
+ const required = getThirdPartyTargetDefinition(t)?.requiredEnvKeys ?? [];
182
+ const eligible = required.every((key) => keys.includes(key));
183
+ return { eligible, matched, keys };
184
+ }
185
+ /** Targets (by shim target name) any non-production declaration names. */
186
+ export function declaredMcpTargets(metadata) {
187
+ return new Set(metadata.mcp.map((d) => d.target));
188
+ }
189
+ // ---------------------------------------------------------------------------
190
+ // Production resolver dependencies
191
+ // ---------------------------------------------------------------------------
192
+ function isInside(child, root) {
193
+ const rel = path.relative(root, child);
194
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
195
+ }
196
+ function insideWorktreeError() {
197
+ const err = new Error("credential source is inside the worker worktree");
198
+ err.code = "EACCES";
199
+ return err;
200
+ }
201
+ /**
202
+ * Child 1 resolver dependencies for one launch. Built from the owner's
203
+ * environment and home (the same configuration root the grant reader uses,
204
+ * through `repositoryStateRecordPath`). When `worktreeRoot` is given, every
205
+ * source read is refused when its CANONICAL path sits inside the worktree,
206
+ * which closes the gap child 1 documents for its lexical-only `excludedRoots`
207
+ * check (a link from outside pointing back in).
208
+ */
209
+ export function createLaunchCredentialReferenceDeps(env, worktreeRoot, options = {}) {
210
+ const realpath = options.realpath ?? ((p) => fsRealpath(p));
211
+ const base = { ...createNodeCredentialReferenceDeps(env), ...(options.homedir ? { homedir: options.homedir } : {}) };
212
+ if (!worktreeRoot)
213
+ return base;
214
+ let canonicalRoot = null;
215
+ const rootOf = () => {
216
+ canonicalRoot ??= realpath(worktreeRoot).catch(() => path.resolve(worktreeRoot));
217
+ return canonicalRoot;
218
+ };
219
+ const guard = async (p) => {
220
+ const root = await rootOf();
221
+ if (isInside(path.resolve(p), path.resolve(worktreeRoot)) || isInside(path.resolve(p), root)) {
222
+ throw insideWorktreeError();
223
+ }
224
+ let canonical;
225
+ try {
226
+ canonical = await realpath(p);
227
+ }
228
+ catch {
229
+ return; // absent: let the real read report it (source_missing)
230
+ }
231
+ if (isInside(canonical, root))
232
+ throw insideWorktreeError();
233
+ };
234
+ return {
235
+ ...base,
236
+ readFile: async (p) => {
237
+ await guard(p);
238
+ return base.readFile(p);
239
+ },
240
+ readBytes: async (p) => {
241
+ await guard(p);
242
+ return base.readBytes(p);
243
+ },
244
+ stat: async (p) => {
245
+ await guard(p);
246
+ return base.stat(p);
247
+ },
248
+ lstat: async (p) => {
249
+ await guard(p);
250
+ return base.lstat(p);
251
+ },
252
+ };
253
+ }
254
+ /** The `excludedRoots` option for a launch worktree. */
255
+ export function launchResolveOptions(worktreeRoot) {
256
+ return worktreeRoot ? { excludedRoots: [worktreeRoot] } : {};
257
+ }
258
+ /**
259
+ * BAPI-1647: the legacy-path registry targets whose `.bridge/config` entry is
260
+ * bundle-less and whose CURRENT command and args match an approved
261
+ * fingerprinted declaration covering the required keys. Used by provisioning
262
+ * to decide whether to register a bundle-less entry at all.
263
+ */
264
+ export function legacyReferenceBackedTargets(metadata, entries) {
265
+ const out = new Set();
266
+ for (const entry of entries) {
267
+ if (entry.target === "bapi" || entry.command === undefined || entry.args === undefined)
268
+ continue;
269
+ if (entry.secretBundle !== undefined && entry.secretBundle.trim().length > 0)
270
+ continue;
271
+ const eligibility = mcpReferenceEligibility(metadata, entry.target, { command: entry.command, args: entry.args }, { requireFingerprint: true });
272
+ if (eligibility.eligible)
273
+ out.add(entry.target);
274
+ }
275
+ return out;
276
+ }
277
+ /** True when the record has an applicable `bridge` (shim `bapi`) consumer. */
278
+ export function hasBridgeConsumer(metadata) {
279
+ return metadata.mcp.some((d) => d.target === "bapi");
280
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * BAPI-1647: may a RESTRICTED credential reach this MCP server launch?
3
+ *
4
+ * A restricted value must never be handed to code the worker controls. A server
5
+ * whose executable, or whose script argument, lives inside the worktree (for
6
+ * example `node ./server.js`) is exactly that: the worker can edit the file and
7
+ * print the variable. So before the shim overlays a restricted value it resolves
8
+ * the launch the way the operating system will — the executable through the
9
+ * child's real `PATH` (and `PATHEXT` on Windows), relative paths against the
10
+ * launch directory — and canonicalizes every location with `realpath` before
11
+ * comparing it with the worktree root's own `realpath`. Text prefixes are never
12
+ * trusted.
13
+ *
14
+ * The answer is `safe`, `inside_worktree`, or `indeterminate` (a launch form the
15
+ * check cannot resolve with confidence: an inline `-e`/`-c` program, an
16
+ * executable it cannot find, a path it cannot canonicalize). Only `safe` may
17
+ * receive restricted values. The check never changes the command, never blocks
18
+ * the launch, and never touches sandbox overlays.
19
+ */
20
+ import { realpath as fsRealpath, stat as fsStat } from "fs/promises";
21
+ import path from "path";
22
+ export function defaultLauncherSafetyDeps(platform = process.platform) {
23
+ return {
24
+ platform,
25
+ realpath: (p) => fsRealpath(p),
26
+ isFile: async (p) => {
27
+ try {
28
+ return (await fsStat(p)).isFile();
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ },
34
+ };
35
+ }
36
+ /** Interpreters whose first non-option argument is a program file. */
37
+ const SCRIPT_INTERPRETERS = new Set([
38
+ "node", "nodejs", "bun", "deno", "tsx", "ts-node", "python", "python3", "ruby", "perl", "php",
39
+ "sh", "bash", "zsh", "dash", "pwsh", "powershell",
40
+ ]);
41
+ /** Options that carry an inline program: the launch cannot be resolved. */
42
+ const INLINE_PROGRAM_FLAGS = new Set(["-e", "--eval", "-p", "--print", "-c", "-Command", "-command", "--command"]);
43
+ function isWithin(child, root, api) {
44
+ const rel = api.relative(root, child);
45
+ return rel === "" || (!rel.startsWith("..") && !api.isAbsolute(rel));
46
+ }
47
+ function interpreterName(command, api) {
48
+ return api.basename(command).toLowerCase().replace(/\.(exe|cmd|bat)$/, "");
49
+ }
50
+ async function resolveExecutable(input, deps, api) {
51
+ const { command } = input;
52
+ if (command.length === 0)
53
+ return null;
54
+ const hasSeparator = command.includes("/") || (deps.platform === "win32" && command.includes("\\"));
55
+ const exts = deps.platform === "win32"
56
+ ? ["", ...(input.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => e.length > 0)]
57
+ : [""];
58
+ const candidatesFor = (base) => exts.map((ext) => `${base}${ext}`);
59
+ if (hasSeparator || api.isAbsolute(command)) {
60
+ for (const candidate of candidatesFor(api.resolve(input.cwd, command))) {
61
+ if (await deps.isFile(candidate))
62
+ return candidate;
63
+ }
64
+ return null;
65
+ }
66
+ const delimiter = deps.platform === "win32" ? ";" : ":";
67
+ const dirs = (input.env.PATH ?? input.env.Path ?? "").split(delimiter);
68
+ for (const dir of dirs) {
69
+ // An empty PATH component means the launch directory itself.
70
+ const base = dir.length === 0 ? input.cwd : api.resolve(input.cwd, dir);
71
+ for (const candidate of candidatesFor(api.join(base, command))) {
72
+ if (await deps.isFile(candidate))
73
+ return candidate;
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ /** Classify one launch for restricted delivery. Never throws. */
79
+ export async function checkRestrictedLauncher(input, deps = defaultLauncherSafetyDeps()) {
80
+ const api = deps.platform === "win32" ? path.win32 : path.posix;
81
+ try {
82
+ let root;
83
+ try {
84
+ root = await deps.realpath(input.worktreeRoot);
85
+ }
86
+ catch {
87
+ return "indeterminate";
88
+ }
89
+ const executable = await resolveExecutable(input, deps, api);
90
+ if (executable === null)
91
+ return "indeterminate";
92
+ let canonicalExe;
93
+ try {
94
+ canonicalExe = await deps.realpath(executable);
95
+ }
96
+ catch {
97
+ return "indeterminate";
98
+ }
99
+ if (isWithin(canonicalExe, root, api))
100
+ return "inside_worktree";
101
+ const interpreter = SCRIPT_INTERPRETERS.has(interpreterName(input.command, api));
102
+ let scriptSeen = false;
103
+ for (const arg of input.args) {
104
+ if (interpreter && !scriptSeen) {
105
+ // An inline program (`-e`, `-c`, `--eval`, combined `-lc`) or a module
106
+ // looked up from the launch directory (`-m`) cannot be resolved.
107
+ if (INLINE_PROGRAM_FLAGS.has(arg) || arg === "-m")
108
+ return "indeterminate";
109
+ if (/^-[A-Za-z]{2,}$/.test(arg) && /[cem]/.test(arg.slice(1)))
110
+ return "indeterminate";
111
+ }
112
+ const looksLikePath = arg.includes("/") || (deps.platform === "win32" && arg.includes("\\")) || arg.startsWith(".");
113
+ const isScriptPosition = interpreter && !scriptSeen && !arg.startsWith("-");
114
+ if (!looksLikePath && !isScriptPosition)
115
+ continue;
116
+ if (isScriptPosition)
117
+ scriptSeen = true;
118
+ const candidate = api.resolve(input.cwd, arg);
119
+ if (!(await deps.isFile(candidate))) {
120
+ // A script position that names no file cannot be resolved with
121
+ // confidence (`node server` loads `./server.js`); any other path-shaped
122
+ // argument that names nothing is data.
123
+ if (isScriptPosition)
124
+ return "indeterminate";
125
+ continue;
126
+ }
127
+ let canonical;
128
+ try {
129
+ canonical = await deps.realpath(candidate);
130
+ }
131
+ catch {
132
+ return "indeterminate";
133
+ }
134
+ if (isWithin(canonical, root, api))
135
+ return "inside_worktree";
136
+ }
137
+ return "safe";
138
+ }
139
+ catch {
140
+ return "indeterminate";
141
+ }
142
+ }
@@ -53,15 +53,67 @@ export function validateWorktreeRelativeCredentialPath(relPath) {
53
53
  // ---------------------------------------------------------------------------
54
54
  // Materialization
55
55
  // ---------------------------------------------------------------------------
56
+ function errnoCode(err) {
57
+ return err && typeof err === "object" ? err.code : undefined;
58
+ }
59
+ function isWithin(child, root) {
60
+ const rel = path.relative(root, child);
61
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
62
+ }
63
+ function failure(reason, error) {
64
+ return { ok: false, reason, error };
65
+ }
66
+ /**
67
+ * BAPI-1647: prove every EXISTING parent of `destPath` (from the worktree root
68
+ * down) canonicalizes to a location under `realRoot`. A parent the worktree
69
+ * turned into a link pointing elsewhere is `dest_unsafe`; the first absent
70
+ * component ends the walk (everything below it is absent too); any error other
71
+ * than `ENOENT` is `dest_unavailable`.
72
+ */
73
+ async function checkParentChain(worktreeRoot, relDest, realRoot, deps) {
74
+ const segments = relDest.split(/[\\/]+/).filter((s) => s.length > 0 && s !== ".");
75
+ let current = worktreeRoot;
76
+ for (const segment of segments.slice(0, -1)) {
77
+ current = path.join(current, segment);
78
+ let canonical;
79
+ try {
80
+ canonical = await deps.realpath(current);
81
+ }
82
+ catch (err) {
83
+ if (errnoCode(err) === "ENOENT")
84
+ return null;
85
+ return failure("dest_unavailable", `unable to inspect a parent directory of the credential destination`);
86
+ }
87
+ if (!isWithin(canonical, realRoot)) {
88
+ return failure("dest_unsafe", `refusing a credential destination whose parent resolves outside the worktree`);
89
+ }
90
+ }
91
+ return null;
92
+ }
56
93
  /**
57
94
  * Materialize a canonical credential file into a worktree. On non-Windows this
58
95
  * creates an idempotent symlink; on Windows it is gated (see module docs) and
59
96
  * copies nothing. Never overwrites an unrelated file or a foreign symlink.
97
+ *
98
+ * BAPI-1647 hardening:
99
+ * - only `ENOENT` from `lstat` means the destination is absent; any other
100
+ * inspection error is `dest_unavailable`, never "safe to create";
101
+ * - every existing parent is `realpath`-checked against the worktree root's
102
+ * `realpath`, before creating directories and again immediately before the
103
+ * link is made or an existing matching link is accepted, so a link the
104
+ * worktree controls cannot redirect the write;
105
+ * - a destination that became occupied between inspection and creation
106
+ * (`EEXIST`) is `dest_occupied`, never overwritten.
107
+ *
108
+ * Concurrency assumption: this runs before any worker exists in the worktree —
109
+ * on the executor after the worktree lock is held, on `start-tickets` before any
110
+ * tab opens — so the only party that could race the parent checks is not yet
111
+ * running.
60
112
  */
61
113
  export async function materializeFileCredentialForWorktree(spec, worktreeRoot, deps) {
62
114
  const validated = validateWorktreeRelativeCredentialPath(spec.worktreeRelativeDestPath);
63
115
  if (!validated.ok) {
64
- return { ok: false, error: validated.error };
116
+ return failure("invalid_dest", validated.error);
65
117
  }
66
118
  const destPath = path.join(worktreeRoot, validated.value);
67
119
  if (deps.platform === "win32") {
@@ -69,39 +121,62 @@ export async function materializeFileCredentialForWorktree(spec, worktreeRoot, d
69
121
  // settled. The structured action lets callers warn without failing the row.
70
122
  return { ok: true, action: "windows-gated" };
71
123
  }
72
- // Inspect the destination without following symlinks.
124
+ let realRoot;
73
125
  try {
74
- const existing = await deps.lstat(destPath);
126
+ realRoot = await deps.realpath(worktreeRoot);
127
+ }
128
+ catch {
129
+ return failure("dest_unavailable", "unable to resolve the worktree root");
130
+ }
131
+ const parents = await checkParentChain(worktreeRoot, validated.value, realRoot, deps);
132
+ if (parents)
133
+ return parents;
134
+ // Inspect the destination without following symlinks. Only ENOENT is absent.
135
+ let existing = null;
136
+ try {
137
+ existing = await deps.lstat(destPath);
138
+ }
139
+ catch (err) {
140
+ if (errnoCode(err) !== "ENOENT") {
141
+ return failure("dest_unavailable", `unable to inspect the credential destination at ${destPath}`);
142
+ }
143
+ }
144
+ if (existing) {
75
145
  if (existing.isSymbolicLink()) {
76
146
  let currentTarget;
77
147
  try {
78
148
  currentTarget = await deps.readlink(destPath);
79
149
  }
80
150
  catch {
81
- return { ok: false, error: `unable to inspect existing symlink at ${destPath}` };
151
+ return failure("dest_unavailable", `unable to inspect existing symlink at ${destPath}`);
82
152
  }
83
153
  if (currentTarget === spec.canonicalSourcePath) {
154
+ const recheck = await checkParentChain(worktreeRoot, validated.value, realRoot, deps);
155
+ if (recheck)
156
+ return recheck;
84
157
  return { ok: true, action: "already-present" };
85
158
  }
86
- return {
87
- ok: false,
88
- error: `refusing to overwrite an existing symlink at ${destPath} that points elsewhere`,
89
- };
159
+ return failure("dest_occupied", `refusing to overwrite an existing symlink at ${destPath} that points elsewhere`);
90
160
  }
91
- return {
92
- ok: false,
93
- error: `refusing to overwrite an existing file at ${destPath}`,
94
- };
161
+ return failure("dest_occupied", `refusing to overwrite an existing file at ${destPath}`);
162
+ }
163
+ try {
164
+ await deps.mkdir(path.dirname(destPath), { recursive: true });
95
165
  }
96
166
  catch {
97
- /* ENOENT (or otherwise absent) — safe to create below. */
167
+ return failure("create_failed", `failed to create credential symlink at ${destPath}`);
98
168
  }
169
+ const recheck = await checkParentChain(worktreeRoot, validated.value, realRoot, deps);
170
+ if (recheck)
171
+ return recheck;
99
172
  try {
100
- await deps.mkdir(path.dirname(destPath), { recursive: true });
101
173
  await deps.symlink(spec.canonicalSourcePath, destPath);
102
174
  }
103
- catch {
104
- return { ok: false, error: `failed to create credential symlink at ${destPath}` };
175
+ catch (err) {
176
+ if (errnoCode(err) === "EEXIST") {
177
+ return failure("dest_occupied", `refusing to overwrite a credential destination that appeared at ${destPath}`);
178
+ }
179
+ return failure("create_failed", `failed to create credential symlink at ${destPath}`);
105
180
  }
106
181
  return { ok: true, action: "created" };
107
182
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Node-backed dependencies for `credential-references.ts` (BAPI-1646). Kept in
3
+ * their own file so the reference module itself stays free of ambient `fs`/`os`
4
+ * access; the CLI and `doctor` build their defaults here.
5
+ */
6
+ import { chmod, lstat, mkdir, open, readFile, rename, stat, unlink, writeFile } from "fs/promises";
7
+ import os from "os";
8
+ export function createNodeCredentialReferenceDeps(env) {
9
+ return {
10
+ env,
11
+ homedir: os.homedir,
12
+ platform: process.platform,
13
+ readFile: (p) => readFile(p, "utf-8"),
14
+ readBytes: (p) => readFile(p),
15
+ lstat: (p) => lstat(p),
16
+ stat: (p) => stat(p),
17
+ };
18
+ }
19
+ export function createNodeCredentialReferenceApplyDeps(env) {
20
+ return {
21
+ ...createNodeCredentialReferenceDeps(env),
22
+ mkdir: (p, o) => mkdir(p, o),
23
+ writeFile: (p, d, o) => writeFile(p, d, o),
24
+ rename: (a, b) => rename(a, b),
25
+ chmod: (p, m) => chmod(p, m),
26
+ unlink: (p) => unlink(p),
27
+ open: (p, flags, mode) => open(p, flags, mode),
28
+ };
29
+ }