@bridge_gpt/mcp-server 0.2.73 → 0.2.75

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 (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -4,11 +4,14 @@
4
4
  * The whole point of this command is that it needs no Bridge web session: a user who has
5
5
  * a Bridge API key can connect GitHub without ever opening the setup UI. The flow is
6
6
  *
7
- * mint → browser (install on GitHub) → poll → pick a repository → confirm
7
+ * mint → browser (sign in to GitHub, prove access, confirm) → poll → pick a
8
+ * repository → confirm
8
9
  *
9
10
  * and the browser half authenticates to *GitHub*, not to Bridge. Bridge never asks for,
10
11
  * accepts, echoes, or transports a GitHub credential. The only thing crossing between
11
12
  * the browser and this process is a Bridge-issued state nonce, held in memory.
13
+ * BAPI-1697: the browser page proves the person can change at least one repository of
14
+ * the installation, and candidates are limited to those repositories.
12
15
  *
13
16
  * Two properties are load-bearing and easy to erode:
14
17
  *
@@ -33,9 +36,10 @@ const USAGE = `Usage: connect-github [--repo <repo_name>] [--handoff | --resume
33
36
 
34
37
  Connect a GitHub repository to a Bridge project from your terminal.
35
38
 
36
- Opens the GitHub App install page in your browser, waits for you to install it,
37
- then asks which repository to connect. You are never asked for a GitHub token or
38
- password — you authenticate to GitHub in the browser.
39
+ Opens a Bridge page in your browser. You sign in to GitHub there, choose or install
40
+ the GitHub App installation, and confirm. Bridge connects only repositories you can
41
+ change on GitHub. Then this command asks which repository to connect. You are never
42
+ asked for a GitHub token or password — you authenticate to GitHub in the browser.
39
43
 
40
44
  If you do not administer the GitHub organization yourself, use the delegated
41
45
  handoff: mint a link with --handoff, send it to whoever does, and finish with
@@ -44,7 +48,7 @@ handoff: mint a link with --handoff, send it to whoever does, and finish with
44
48
  Options:
45
49
  --repo <repo_name> Bridge project to connect (inferred from this directory
46
50
  when omitted; you will be asked to confirm).
47
- --handoff Print a shareable install link (valid 72 hours) instead of
51
+ --handoff Print a shareable connect link (valid 72 hours) instead of
48
52
  connecting here. Does not open a browser or wait.
49
53
  --resume Look up an outstanding handoff and finish connecting it.
50
54
  Works from any machine holding this project's API key.
@@ -280,7 +284,7 @@ export async function openGithubInstallPage(deps, installUrl) {
280
284
  // ---------------------------------------------------------------------------
281
285
  const STEPS = [
282
286
  "Connect GitHub",
283
- "Complete GitHub in browser",
287
+ "Sign in to GitHub and confirm in browser",
284
288
  "Verify connection",
285
289
  "Choose repository",
286
290
  "Confirm connection",
@@ -298,7 +302,8 @@ function candidateLabel(c) {
298
302
  const OUTCOME_MESSAGES = {
299
303
  expired: "The connection request expired before GitHub reported back. Run connect-github again.",
300
304
  invalid: "This connection request is no longer valid. Run connect-github again.",
301
- "verification-failed": "Bridge could not verify the GitHub installation. Run connect-github again.",
305
+ "verification-failed": "Bridge could not confirm your GitHub access to that installation. You need push " +
306
+ "access to at least one of its repositories. Run connect-github again.",
302
307
  "no-repositories": "The GitHub App installation did not include any repositories Bridge can access. " +
303
308
  "Re-run connect-github and grant access to at least one repository.",
304
309
  conflict: "This GitHub installation or project is already connected to a different Bridge " +
@@ -315,6 +320,17 @@ const FAILURE_MESSAGES = {
315
320
  deadline: "Timed out waiting for GitHub. If you completed the install, run connect-github again " +
316
321
  "to pick up the connection.",
317
322
  };
323
+ /**
324
+ * Show who proved GitHub access before the admin picks a repository (BAPI-1697).
325
+ *
326
+ * Both values come from the server's stored proof and were validated as GitHub logins
327
+ * by the parser. Nothing is printed when either is missing (an older server).
328
+ */
329
+ function reportProvenIdentity(deps, login, account) {
330
+ if (!login || !account)
331
+ return;
332
+ deps.stderr(`GitHub access confirmed by ${login} for the ${account} account.`);
333
+ }
318
334
  /** The no-connection-made framing, used for every unsuccessful terminal path. */
319
335
  function reportNoConnection(deps, detail) {
320
336
  deps.stderr("");
@@ -397,8 +413,8 @@ export async function runGithubConnectionFlow(deps, api, repoName) {
397
413
  deps.stderr("Your request to install the GitHub App was sent to an organization owner for approval.");
398
414
  deps.stderr("That approval happens on GitHub and does not return here, so this command cannot " +
399
415
  "wait for it.");
400
- deps.stderr("Once an owner approves the install, finish the connection with the manual steps in " +
401
- "the GitHub App setup guide (docs/install/github-app.md).");
416
+ deps.stderr("Once an owner approves the install, run connect-github again to finish the connection. " +
417
+ "See the GitHub App setup guide (docs/install/github-app.md).");
402
418
  return 1;
403
419
  }
404
420
  if (result.status === "connected") {
@@ -413,6 +429,7 @@ export async function runGithubConnectionFlow(deps, api, repoName) {
413
429
  if (candidates.length === 0) {
414
430
  return reportNoConnection(deps, OUTCOME_MESSAGES["no-repositories"]);
415
431
  }
432
+ reportProvenIdentity(deps, result.provenGithubLogin, result.provenGithubAccount);
416
433
  renderStep(deps, 3);
417
434
  const selected = await chooseCandidate(deps, candidates);
418
435
  if (!selected)
@@ -460,8 +477,8 @@ export async function runGithubHandoffMintFlow(deps, api, repoName) {
460
477
  deps.stderr("");
461
478
  deps.stderr(`Send this link to whoever administers your GitHub organization.`);
462
479
  deps.stderr(`It works once and expires ${formatExpiry(minted.value.expiresAt)}.`);
463
- deps.stderr("They'll finish in their browser — ask them to ping you, then run " +
464
- "`connect-github --resume`.");
480
+ deps.stderr("They'll sign in to GitHub and confirm in their browser — ask them to ping you, " +
481
+ "then run `connect-github --resume`.");
465
482
  return 0;
466
483
  }
467
484
  /** Render an expiry for humans without pretending to know the reader's locale. */
@@ -489,7 +506,8 @@ const HANDOFF_STATUS_MESSAGES = {
489
506
  pending: "Nobody has completed the link yet. Ask them to open it, then run connect-github --resume again.",
490
507
  expired: "The link expired before it was used. Run connect-github --handoff to create a new one.",
491
508
  revoked: "This link was revoked. Run connect-github --handoff to create a new one.",
492
- "verification-failed": "Bridge could not verify the GitHub installation. Run connect-github --handoff to create a new link.",
509
+ "verification-failed": "Bridge could not confirm GitHub access for this link, or the confirmation is more " +
510
+ "than 72 hours old. Run connect-github --handoff to create a new link.",
493
511
  "no-repositories": "The GitHub App installation did not include any repositories Bridge can access. " +
494
512
  "Create a new link with connect-github --handoff and ask them to grant access to at least one repository.",
495
513
  conflict: "This GitHub installation or project is already connected to a different Bridge " +
@@ -572,14 +590,12 @@ export async function runGithubHandoffResumeFlow(deps, api, repoName) {
572
590
  if (selected.status !== "staged") {
573
591
  const message = HANDOFF_STATUS_MESSAGES[selected.status] ?? HANDOFF_STATUS_MESSAGES.failed;
574
592
  if (selected.status === "pending" || selected.status === "expired") {
575
- // AC-8 fallback. Bridge cannot safely discover an existing installation on an org
576
- // it was never called back about, so this deliberately does NOT claim to have
577
- // detected one — it points at the documented manual path instead.
593
+ // AC-8 (BAPI-1697): an existing installation no longer dead-ends. The link signs
594
+ // the recipient in to GitHub first and offers the installations they can change.
578
595
  deps.stderr("");
579
596
  deps.stderr(message);
580
- deps.stderr("If the GitHub App is already installed on that organization, GitHub may not " +
581
- "send Bridge a callback at all. In that case follow the manual installation-ID " +
582
- "steps in the GitHub App setup guide (docs/install/github-app.md).");
597
+ deps.stderr("If the GitHub App is already installed on that organization, the same link " +
598
+ "still works: it asks them to sign in to GitHub and choose the installation.");
583
599
  // `pending` is a live state, not a failure; `expired` is terminal.
584
600
  return selected.status === "pending" ? 0 : 1;
585
601
  }
@@ -591,6 +607,7 @@ export async function runGithubHandoffResumeFlow(deps, api, repoName) {
591
607
  if (candidates.length === 0) {
592
608
  return reportNoConnection(deps, OUTCOME_MESSAGES["no-repositories"]);
593
609
  }
610
+ reportProvenIdentity(deps, selected.provenGithubLogin, selected.provenGithubAccount);
594
611
  const chosen = await chooseCandidate(deps, candidates);
595
612
  if (!chosen)
596
613
  return 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
+ }