@bridge_gpt/mcp-server 0.2.71 → 0.2.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -17
- package/build/agent-launchers/claude-executor-adapter.js +22 -3
- package/build/agent-notes.js +171 -95
- package/build/agents.generated.js +7 -7
- package/build/bridge-permissions.js +31 -0
- package/build/bridge-worktree-inspection.js +237 -0
- package/build/check-evidence.js +6 -0
- package/build/ci-system-detection.js +50 -0
- package/build/ci-trigger-adapters.js +631 -0
- package/build/ci-trigger-install.js +106 -0
- package/build/claude-review-workflow.js +1 -1
- package/build/cli-help.js +6 -0
- package/build/codex-auto-recovery.js +126 -0
- package/build/codex-launcher-pin.js +33 -2
- package/build/codex-skill-adapter.js +5 -1
- package/build/command-host.js +33 -0
- package/build/commands.generated.js +7 -6
- package/build/conductor/bridge-api-client.js +1352 -50
- package/build/conductor/bring-up-facts.js +18 -5
- package/build/conductor/command-drift-production.js +42 -17
- package/build/conductor/command-drift.js +47 -0
- package/build/conductor/declare-blocked.js +554 -0
- package/build/conductor/doctor.js +187 -28
- package/build/conductor/driver-commands.js +141 -0
- package/build/conductor/driver-guard.js +277 -0
- package/build/conductor/driver-lapse.js +321 -0
- package/build/conductor/driver-register.js +176 -0
- package/build/conductor/driver-release.js +174 -0
- package/build/conductor/driver-session-state.js +315 -0
- package/build/conductor/epic-branch-ci-inspection.js +222 -29
- package/build/conductor/epic-implementer-cli.js +213 -13
- package/build/conductor/epic-server-database.js +162 -0
- package/build/conductor/epic-server-guidance.js +278 -0
- package/build/conductor/epic-server-journal.js +239 -0
- package/build/conductor/epic-server-processes.js +324 -0
- package/build/conductor/epic-server-recipe.js +397 -0
- package/build/conductor/epic-server-runtime.js +1207 -0
- package/build/conductor/epic-server-sfcc.js +107 -0
- package/build/conductor/epic-server-state.js +427 -0
- package/build/conductor/epic-server.js +594 -0
- package/build/conductor/gate-discovery.js +281 -10
- package/build/conductor/gate-settings-review.js +525 -5
- package/build/conductor/git-hooks-uninstall.js +112 -0
- package/build/conductor/git-hooks.js +81 -15
- package/build/conductor/guided-repair.js +10 -1
- package/build/conductor/install-doctor.js +2 -4
- package/build/conductor/launch-need-probes.js +6 -53
- package/build/conductor/launch-plan.js +318 -121
- package/build/conductor/local-merge.js +12 -1
- package/build/conductor/merge-execution-contract.js +1 -1
- package/build/conductor/merged-child-check.js +2 -1
- package/build/conductor/prerequisite-inputs.js +1213 -0
- package/build/conductor/readiness-assessment.js +93 -0
- package/build/conductor/readiness-cli.js +30 -9
- package/build/conductor/readiness-prerequisites.js +77 -5
- package/build/conductor/readiness-sections.js +146 -126
- package/build/conductor/readiness.js +21 -3
- package/build/conductor/recovery-cli.js +236 -15
- package/build/conductor/recovery-operations.js +34 -4
- package/build/conductor/repair-contract.js +33 -0
- package/build/conductor/tools.js +36 -4
- package/build/conductor/wait-run-attention.js +115 -0
- package/build/conductor/wait-run-cli.js +300 -21
- package/build/conductor/worker-database-doctor-inspector.js +34 -2
- package/build/conductor/worker-setup-tally.js +27 -0
- package/build/credential-store.js +96 -21
- package/build/dependency-install-declarations.js +212 -0
- package/build/docs.generated.js +4 -4
- package/build/doctor.js +91 -8
- package/build/drive-epic-help.js +23 -4
- package/build/drive-epic.js +1841 -340
- package/build/engine-paths.js +20 -0
- package/build/epic-branch-ci-summary.js +140 -0
- package/build/epic-capability-statement.js +107 -0
- package/build/epic-ci-workflow-drift.js +30 -15
- package/build/epic-ci-workflow-install.js +110 -42
- package/build/epic-ci-workflow-v2.js +274 -0
- package/build/epic-ci-workflow.js +38 -12
- package/build/epic-implementer-bin.js +2184 -52
- package/build/epic-launch-context.js +607 -0
- package/build/epic-launch-profile.js +1 -1
- package/build/epic-server-record.js +273 -0
- package/build/epic-shared/bridge-client.js +11 -3
- package/build/escalation-reachability.js +43 -0
- package/build/executor/ci-fix-test-runs.js +334 -0
- package/build/executor/cli.js +2 -0
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/credentials.js +1 -1
- package/build/executor/delivery-observations.js +113 -0
- package/build/executor/delivery-outcome.js +30 -0
- package/build/executor/dependency-refresh-runner.js +132 -0
- package/build/executor/dependency-refresh.js +530 -0
- package/build/executor/deps.js +4 -0
- package/build/executor/env.js +119 -17
- package/build/executor/epic-server-context.js +141 -0
- package/build/executor/gate-qualification-job.js +127 -26
- package/build/executor/harness-coverage.js +19 -0
- package/build/executor/http-client.js +87 -6
- package/build/executor/index.js +2 -1
- package/build/executor/install-preflight.js +1 -1
- package/build/executor/job-runner.js +659 -87
- package/build/executor/likely-tests.js +94 -97
- package/build/executor/observation.js +8 -0
- package/build/executor/pre-pr-checks.js +363 -0
- package/build/executor/prompt-spec.js +127 -5
- package/build/executor/reconcile-overlap-job.js +5 -3
- package/build/executor/required-verification.js +28 -0
- package/build/executor/required-work-diagnostics.js +32 -0
- package/build/executor/required-work-ledger.js +955 -39
- package/build/executor/results.js +100 -0
- package/build/executor/service-discovery.js +42 -0
- package/build/executor/service-lifecycle.js +109 -2
- package/build/executor/service-uninstall.js +205 -0
- package/build/executor/service-unit.js +5 -3
- package/build/executor/terminal-mutation.js +8 -0
- package/build/executor/test-clock.js +3 -0
- package/build/executor/verification-hints.js +179 -0
- package/build/executor/worker-command.js +126 -5
- package/build/executor/worker-database-config.js +281 -0
- package/build/executor/worker-database-target.js +16 -12
- package/build/executor/worker-database.js +575 -116
- package/build/executor/worker-finalization.js +71 -10
- package/build/executor/worker-guard-hook.js +10 -2
- package/build/executor/worker-resources.js +25 -3
- package/build/executor/worker-verification-guidance.js +55 -5
- package/build/executor/worktree-inspection.js +42 -0
- package/build/executor/worktree.js +20 -1
- package/build/executor-launch.js +54 -2
- package/build/generated-assets-catalog.js +2 -2
- package/build/github-sign-in.js +1 -1
- package/build/index.js +1111 -381
- package/build/init.js +29 -14
- package/build/install-bridge-conductor-answers.js +465 -0
- package/build/install-bridge-conductor-apply.js +259 -0
- package/build/install-bridge-conductor-assessment.js +895 -0
- package/build/install-bridge-conductor-compact.js +161 -0
- package/build/install-bridge-conductor-contracts.js +63 -0
- package/build/install-bridge-conductor-gate.js +1383 -188
- package/build/install-bridge-conductor-setup.js +637 -92
- package/build/install-bridge-conductor.js +3163 -740
- package/build/install-bridge.js +601 -128
- package/build/install-maintenance.js +127 -0
- package/build/install-reexec.js +1 -1
- package/build/launcher-config-inspection.js +162 -1
- package/build/local-cleanup.js +59 -0
- package/build/mcp-grant-candidates.js +767 -0
- package/build/mcp-grant-doctor.js +63 -0
- package/build/mcp-grant.js +288 -0
- package/build/mcp-host-targets.js +8 -0
- package/build/mcp-identity.js +23 -0
- package/build/mcp-install-state.js +68 -2
- package/build/mcp-invoke.js +126 -13
- package/build/mcp-presets.js +107 -0
- package/build/mcp-provisioning.js +134 -2
- package/build/mcp-registration-doctor.js +31 -2
- package/build/mcp-server-invocation.js +6 -1
- package/build/merge-workflow-install.js +236 -111
- package/build/package-script-semantics.js +10 -0
- package/build/pipeline-utils.js +1 -1
- package/build/pipelines.generated.js +6 -6
- package/build/plan-discovery.js +97 -4
- package/build/plan-execution-ledger.js +248 -9
- package/build/plan-generation-io.js +262 -0
- package/build/plan-generation.js +424 -0
- package/build/plane/build-freshness.js +6 -1
- package/build/plane/cli.js +75 -9
- package/build/plane/plane-freshness.js +23 -7
- package/build/plane/preflight.js +50 -10
- package/build/plane/shutdown.js +19 -0
- package/build/plane/terminal-run-cleanup.js +23 -5
- package/build/plane/terminal-run-status.js +4 -0
- package/build/printed-remedy-commands.js +229 -15
- package/build/readiness-check.js +1 -1
- package/build/readiness-prerequisites.generated.js +311 -4
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +38 -0
- package/build/repository-toolchains.js +50 -8
- package/build/run-unit-tests-launcher.js +8 -1
- package/build/setup-change-policy.js +32 -0
- package/build/setup-epic.js +1192 -198
- package/build/setup-progress.js +44 -0
- package/build/setup-question.js +180 -0
- package/build/start-tickets.js +4 -0
- package/build/test-command-detection.js +32 -88
- package/build/test-support/notes-fs.js +40 -0
- package/build/third-party-mcp-targets.js +30 -0
- package/build/ticket-delivery-enrollment.js +30 -8
- package/build/ticket-delivery-run-scope.js +128 -0
- package/build/upgrade-cli.js +85 -2
- package/build/v2-readiness-requirements.js +28 -1
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktrees.js +105 -0
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
- package/docs/EPIC-IMPLEMENTER.md +5 -0
- package/docs/epic-implementer/getting-started.md +42 -15
- package/docs/epic-implementer/self-hosting.md +14 -1
- package/package.json +2 -2
|
@@ -0,0 +1,767 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP grant candidates: discovery, normalization, and publication (BAPI-1545).
|
|
3
|
+
*
|
|
4
|
+
* The grant setup item offers the owner a set of extra MCP servers to approve
|
|
5
|
+
* for every Epic Implementer worker in one repository. The choices come from:
|
|
6
|
+
*
|
|
7
|
+
* - the owner's host config: user-scope `mcpServers` in `~/.claude.json` and
|
|
8
|
+
* Cursor's `~/.cursor/mcp.json` (project-scope host entries are ignored);
|
|
9
|
+
* - the checkout's own MCP configs, `.mcp.json` and `.cursor/mcp.json`
|
|
10
|
+
* (BAPI-1636; `.vscode/mcp.json` is not read);
|
|
11
|
+
* - the repository's `.bridge/config` `[[mcp]]` entries, read from the
|
|
12
|
+
* checkout the owner runs install in (trusted at that moment only, because
|
|
13
|
+
* the owner is present);
|
|
14
|
+
* - the built-in Playwright preset (`mcp-presets.ts`).
|
|
15
|
+
*
|
|
16
|
+
* Bridge itself is never a candidate: it is always provisioned.
|
|
17
|
+
*
|
|
18
|
+
* BAPI-1636: every entry from every origin passes through ONE pure classifier,
|
|
19
|
+
* {@link classifyMcpGrantEntry}, and ends in exactly one state: offered,
|
|
20
|
+
* excluded with a fixed reason, or unclassifiable. A server that targets a
|
|
21
|
+
* Bridge API under any name, or carries another repository's credential, is
|
|
22
|
+
* never offered. The same classifier checks an existing grant (reported, never
|
|
23
|
+
* changed) and re-runs at publication through a fresh rediscovery, so a
|
|
24
|
+
* selection that went stale or unsafe is refused before anything is staged.
|
|
25
|
+
*
|
|
26
|
+
* Secrets never reach a grant. Every `env` value of an imported host or project
|
|
27
|
+
* entry is held in a {@link CandidateSecrets} store (which refuses to
|
|
28
|
+
* serialize), then moved into the credential store under a fresh grant-specific
|
|
29
|
+
* target at publication. The grant keeps only that target and the key names.
|
|
30
|
+
* The classifier may test those values for a Bridge URL and never copies one
|
|
31
|
+
* out. An entry whose ARGUMENTS look like a credential is not offered at all,
|
|
32
|
+
* and a non-`stdio` entry is not offered because its headers could carry
|
|
33
|
+
* secrets.
|
|
34
|
+
*
|
|
35
|
+
* The candidate fingerprint is a SHA-256 over the canonical inventory with every
|
|
36
|
+
* secret value left out. It changes when a command, an argument, a source, a key
|
|
37
|
+
* set, a non-secret value, or a declared bundle reference changes, and it does
|
|
38
|
+
* NOT change when only a secret value rotates (rotation is a credential-store
|
|
39
|
+
* operation). Fresh publication-specific bundle targets, package-read evidence,
|
|
40
|
+
* destination evidence, and existing-grant findings are never part of it, so
|
|
41
|
+
* none of them causes a repeated prompt.
|
|
42
|
+
*/
|
|
43
|
+
import { createHash, randomBytes } from "crypto";
|
|
44
|
+
import path from "path";
|
|
45
|
+
import { readBridgeConfig } from "./bridge-config.js";
|
|
46
|
+
import { upsertCredentialBundle, } from "./credential-store.js";
|
|
47
|
+
import { resolveClaudeUserConfigPath } from "./claude-user-config-doctor.js";
|
|
48
|
+
import { bridgeUrlOrigin, launcherTargetFor, parseLauncherPin, } from "./launcher-config-inspection.js";
|
|
49
|
+
import { resolveCursorUserConfigPath } from "./mcp-host-targets.js";
|
|
50
|
+
import { isLocalBuildLauncher, MCP_PACKAGE_NAME } from "./mcp-identity.js";
|
|
51
|
+
import { BRIDGE_RESERVED_SERVER_NAMES, isGrantableServerName, MCP_GRANT_MAX_SERVERS, MCP_GRANT_VERSION, writeMcpGrant, } from "./mcp-grant.js";
|
|
52
|
+
import { PLAYWRIGHT_PRESET_NAME, PLAYWRIGHT_PRESET_UNAVAILABLE_TEXT, playwrightPresetEntry } from "./mcp-presets.js";
|
|
53
|
+
import { getThirdPartyTargetDefinition } from "./third-party-mcp-targets.js";
|
|
54
|
+
/** Project origins map to the existing `repository` source, so grant schema version 1 is unchanged. */
|
|
55
|
+
const ORIGIN_SOURCE = {
|
|
56
|
+
claude: "host",
|
|
57
|
+
cursor: "host",
|
|
58
|
+
"project-claude": "repository",
|
|
59
|
+
"project-cursor": "repository",
|
|
60
|
+
repository: "repository",
|
|
61
|
+
preset: "preset",
|
|
62
|
+
};
|
|
63
|
+
/** Plain-language label for an origin. Never a path. */
|
|
64
|
+
export const CANDIDATE_ORIGIN_LABEL = {
|
|
65
|
+
claude: "Claude user config",
|
|
66
|
+
cursor: "Cursor user config",
|
|
67
|
+
"project-claude": "this repository's .mcp.json",
|
|
68
|
+
"project-cursor": "this repository's .cursor/mcp.json",
|
|
69
|
+
repository: "this repository's .bridge/config",
|
|
70
|
+
preset: "built-in preset",
|
|
71
|
+
};
|
|
72
|
+
/** The project MCP configs read for candidates, in order. Root keys come from the launcher target list. */
|
|
73
|
+
const PROJECT_CONFIG_ORIGINS = [
|
|
74
|
+
{ relPath: ".mcp.json", origin: "project-claude" },
|
|
75
|
+
{ relPath: ".cursor/mcp.json", origin: "project-cursor" },
|
|
76
|
+
];
|
|
77
|
+
/** The fixed text shown for each exclusion. Never includes a value. */
|
|
78
|
+
export const CANDIDATE_EXCLUSION_TEXT = {
|
|
79
|
+
not_stdio: "Not supported in this version",
|
|
80
|
+
secret_arg: "Not offered: an argument may contain a credential",
|
|
81
|
+
reserved_name: "Not offered: the name is reserved for the built-in Playwright preset",
|
|
82
|
+
invalid_name: "Not offered: the name is not a usable server name",
|
|
83
|
+
invalid_definition: "Not offered: the definition is incomplete",
|
|
84
|
+
bundle_keys_unknown: "Not offered: the credential keys its bundle supplies cannot be identified",
|
|
85
|
+
bridge_target: "Not offered: this is a Bridge server; workers already get Bridge for this repository.",
|
|
86
|
+
other_repository_credential: "Not offered: it carries a credential for a different repository.",
|
|
87
|
+
unclassifiable: "Not offered: setup cannot tell what this server connects to.",
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Literal imported env values, keyed by definition id. Kept apart from the
|
|
91
|
+
* candidates so no candidate, grant entry, or log line can carry one. It refuses
|
|
92
|
+
* to serialize.
|
|
93
|
+
*/
|
|
94
|
+
export class CandidateSecrets {
|
|
95
|
+
#values = new Map();
|
|
96
|
+
set(definitionId, values) {
|
|
97
|
+
this.#values.set(definitionId, { ...values });
|
|
98
|
+
}
|
|
99
|
+
get(definitionId) {
|
|
100
|
+
const values = this.#values.get(definitionId);
|
|
101
|
+
return values === undefined ? undefined : { ...values };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* True when any held value for `definitionId` satisfies `test`. Value-free:
|
|
105
|
+
* only the answer leaves the holder (BAPI-1636 uses it for Bridge URLs).
|
|
106
|
+
*/
|
|
107
|
+
anyValueMatches(definitionId, test) {
|
|
108
|
+
return Object.values(this.#values.get(definitionId) ?? {}).some(test);
|
|
109
|
+
}
|
|
110
|
+
toJSON() {
|
|
111
|
+
return "[redacted]";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// Credential-looking arguments
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
const SECRET_FLAG_WORDS = ["key", "token", "secret", "password"];
|
|
118
|
+
function urlHasUserInfo(value) {
|
|
119
|
+
if (!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value))
|
|
120
|
+
return false;
|
|
121
|
+
try {
|
|
122
|
+
const url = new URL(value);
|
|
123
|
+
return url.username.length > 0 || url.password.length > 0;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// An unparseable URL-looking value with an `@` before the path is treated as user info.
|
|
127
|
+
return /^[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/]*@/.test(value);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** True when a URL's query names a parameter like `password`, `sslpassword`, `api_key`, or `token`. */
|
|
131
|
+
function urlQueryNamesSecret(value) {
|
|
132
|
+
if (!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value))
|
|
133
|
+
return false;
|
|
134
|
+
const query = value.indexOf("?");
|
|
135
|
+
if (query === -1)
|
|
136
|
+
return false;
|
|
137
|
+
return value
|
|
138
|
+
.slice(query + 1)
|
|
139
|
+
.split(/[&;#]/)
|
|
140
|
+
.some((pair) => {
|
|
141
|
+
const name = pair.split("=")[0].toLowerCase();
|
|
142
|
+
return SECRET_FLAG_WORDS.some((word) => name.includes(word));
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
/** User info, or a secret-named query parameter. */
|
|
146
|
+
function urlLooksLikeCredential(value) {
|
|
147
|
+
return urlHasUserInfo(value) || urlQueryNamesSecret(value);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* True when an argument looks like it carries a credential: a flag whose name
|
|
151
|
+
* contains `key`, `token`, `secret`, or `password` (any case, split or `=`
|
|
152
|
+
* form), or a URL with user info or with a query parameter so named (for
|
|
153
|
+
* example a DSN's `?password=`). The value is never returned or printed.
|
|
154
|
+
*/
|
|
155
|
+
export function argumentLooksLikeCredential(arg) {
|
|
156
|
+
if (arg.startsWith("-")) {
|
|
157
|
+
const flag = arg.replace(/^-+/, "").split("=")[0].toLowerCase();
|
|
158
|
+
if (SECRET_FLAG_WORDS.some((word) => flag.includes(word)))
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
if (urlLooksLikeCredential(arg))
|
|
162
|
+
return true;
|
|
163
|
+
const eq = arg.indexOf("=");
|
|
164
|
+
return eq !== -1 && urlLooksLikeCredential(arg.slice(eq + 1));
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Env values held for one entry during classification only. Value-free from
|
|
168
|
+
* outside: only {@link anyValueMatches} answers, and it refuses to serialize.
|
|
169
|
+
*/
|
|
170
|
+
export class EntryEnvValues {
|
|
171
|
+
#values;
|
|
172
|
+
constructor(values) {
|
|
173
|
+
this.#values = { ...values };
|
|
174
|
+
}
|
|
175
|
+
anyValueMatches(test) {
|
|
176
|
+
return Object.values(this.#values).some(test);
|
|
177
|
+
}
|
|
178
|
+
/** The values, for staging into {@link CandidateSecrets}. Module-internal use only. */
|
|
179
|
+
copy() {
|
|
180
|
+
return { ...this.#values };
|
|
181
|
+
}
|
|
182
|
+
toJSON() {
|
|
183
|
+
return "[redacted]";
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** Build the known-Bridge-URL test from the production URL and the destination evidence. */
|
|
187
|
+
export function knownBridgeUrlMatcher(productionBaseUrl, destination) {
|
|
188
|
+
const production = bridgeUrlOrigin(productionBaseUrl);
|
|
189
|
+
return (value) => {
|
|
190
|
+
const origin = bridgeUrlOrigin(value);
|
|
191
|
+
if (origin === null)
|
|
192
|
+
return false;
|
|
193
|
+
return origin === production || (destination?.matchesUrl(value) ?? false);
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/** True when an argument, bare or as a `--flag=<url>` value, names a known Bridge URL. */
|
|
197
|
+
function argumentNamesBridgeUrl(arg, isKnownBridgeUrl) {
|
|
198
|
+
if (isKnownBridgeUrl(arg))
|
|
199
|
+
return true;
|
|
200
|
+
const eq = arg.indexOf("=");
|
|
201
|
+
return eq !== -1 && isKnownBridgeUrl(arg.slice(eq + 1));
|
|
202
|
+
}
|
|
203
|
+
/** The repository a credential-store target is scoped to, or null for any other target. */
|
|
204
|
+
function credentialTargetRepository(value) {
|
|
205
|
+
const bapi = /^bapi:([^:\s]+)$/.exec(value);
|
|
206
|
+
if (bapi)
|
|
207
|
+
return bapi[1];
|
|
208
|
+
const grant = /^mcp-grant:([^:\s]+):/.exec(value);
|
|
209
|
+
return grant ? grant[1] : null;
|
|
210
|
+
}
|
|
211
|
+
const SHELL_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
|
|
212
|
+
/** True for `sh -c`, `bash -c`, `zsh -c`, `cmd /c`, and the like: the target hides in one string. */
|
|
213
|
+
function isShellWrapper(command, args) {
|
|
214
|
+
const base = command.replace(/\\/g, "/").split("/").pop().toLowerCase().replace(/\.exe$/, "");
|
|
215
|
+
if (SHELL_COMMANDS.has(base))
|
|
216
|
+
return args.some((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a));
|
|
217
|
+
if (base === "cmd")
|
|
218
|
+
return args.some((a) => /^\/[ck]$/i.test(a));
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Classify one normalized entry. Pure and deterministic: no I/O, no logging,
|
|
223
|
+
* and the result never carries a command, an argument, or a value. The order is
|
|
224
|
+
* fixed: Bridge's own names are skipped, then `invalid_name`,
|
|
225
|
+
* `invalid_definition`, `not_stdio`, `bridge_target`,
|
|
226
|
+
* `other_repository_credential`, `reserved_name`, `secret_arg`,
|
|
227
|
+
* `bundle_keys_unknown`, and last `unclassifiable`.
|
|
228
|
+
*/
|
|
229
|
+
export function classifyMcpGrantEntry(entry, context) {
|
|
230
|
+
if (BRIDGE_RESERVED_SERVER_NAMES.includes(entry.name))
|
|
231
|
+
return { state: "skipped" };
|
|
232
|
+
const excluded = (reason) => ({ state: "excluded", reason });
|
|
233
|
+
if (!isGrantableServerName(entry.name))
|
|
234
|
+
return excluded("invalid_name");
|
|
235
|
+
if (!entry.definitionValid || entry.missingRequiredBundle === true)
|
|
236
|
+
return excluded("invalid_definition");
|
|
237
|
+
if (!entry.stdio)
|
|
238
|
+
return excluded("not_stdio");
|
|
239
|
+
// Each signal alone is enough.
|
|
240
|
+
const namesBridgeUrl = (value) => argumentNamesBridgeUrl(value, context.isKnownBridgeUrl);
|
|
241
|
+
if (parseLauncherPin(entry.args) !== null ||
|
|
242
|
+
entry.packageIdentity === "bridge" ||
|
|
243
|
+
entry.envKeys.some((k) => k.startsWith("BAPI_")) ||
|
|
244
|
+
entry.args.some(namesBridgeUrl) ||
|
|
245
|
+
Object.values(entry.plainEnv).some(context.isKnownBridgeUrl) ||
|
|
246
|
+
(entry.secretEnv?.anyValueMatches(context.isKnownBridgeUrl) ?? false)) {
|
|
247
|
+
return excluded("bridge_target");
|
|
248
|
+
}
|
|
249
|
+
// A reference may stand alone or be a `--flag=<target>` value. Secret env
|
|
250
|
+
// values are tested only for a Bridge URL (above), never read for this rule.
|
|
251
|
+
const flagValues = entry.args.flatMap((a) => (a.indexOf("=") === -1 ? [] : [a.slice(a.indexOf("=") + 1)]));
|
|
252
|
+
const references = [entry.declaredBundle, ...entry.args, ...flagValues, ...Object.values(entry.plainEnv)];
|
|
253
|
+
if (references.some((value) => {
|
|
254
|
+
if (value === undefined)
|
|
255
|
+
return false;
|
|
256
|
+
const repo = credentialTargetRepository(value);
|
|
257
|
+
return repo !== null && repo !== context.repoName;
|
|
258
|
+
})) {
|
|
259
|
+
return excluded("other_repository_credential");
|
|
260
|
+
}
|
|
261
|
+
if (entry.name === PLAYWRIGHT_PRESET_NAME && context.allowReservedName !== true)
|
|
262
|
+
return excluded("reserved_name");
|
|
263
|
+
if (entry.args.some(argumentLooksLikeCredential))
|
|
264
|
+
return excluded("secret_arg");
|
|
265
|
+
if (entry.declaredBundle !== undefined && entry.declaredBundleKeys === undefined)
|
|
266
|
+
return excluded("bundle_keys_unknown");
|
|
267
|
+
if (isShellWrapper(entry.command, entry.args))
|
|
268
|
+
return { state: "unclassifiable", reason: "unclassifiable" };
|
|
269
|
+
if (entry.packageIdentity === "unknown")
|
|
270
|
+
return { state: "unclassifiable", reason: "unclassifiable" };
|
|
271
|
+
return { state: "offered" };
|
|
272
|
+
}
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
// Read-only evidence collection and normalization
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
277
|
+
function isPlainObject(value) {
|
|
278
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
279
|
+
}
|
|
280
|
+
async function readJsonIfPresent(filePath, deps) {
|
|
281
|
+
try {
|
|
282
|
+
return JSON.parse(await deps.readFile(filePath));
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
// Missing or unreadable config offers nothing; it never fails setup.
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Read the package beside `node <abs-root>/build/index.js`, read-only, with the
|
|
291
|
+
* POSIX or Windows path rules the launcher path itself uses. Never throws; the
|
|
292
|
+
* package file's content never leaves this function.
|
|
293
|
+
*/
|
|
294
|
+
export async function collectLocalBuildPackageIdentity(entryPoint, readFile) {
|
|
295
|
+
const paths = entryPoint.startsWith("/") ? path.posix : path.win32;
|
|
296
|
+
const root = paths.dirname(paths.dirname(entryPoint));
|
|
297
|
+
try {
|
|
298
|
+
const parsed = JSON.parse(await readFile(paths.join(root, "package.json")));
|
|
299
|
+
const name = isPlainObject(parsed) ? parsed.name : undefined;
|
|
300
|
+
if (typeof name !== "string" || name.trim().length === 0)
|
|
301
|
+
return "unknown";
|
|
302
|
+
return name === MCP_PACKAGE_NAME ? "bridge" : "other";
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
return "unknown";
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/** Normalize one host or project config entry. Values stay in an {@link EntryEnvValues}. */
|
|
309
|
+
function normalizeConfigEntry(name, origin, raw) {
|
|
310
|
+
const invalid = {
|
|
311
|
+
name,
|
|
312
|
+
origin,
|
|
313
|
+
definitionValid: false,
|
|
314
|
+
stdio: true,
|
|
315
|
+
command: "",
|
|
316
|
+
args: [],
|
|
317
|
+
plainEnv: {},
|
|
318
|
+
envKeys: [],
|
|
319
|
+
};
|
|
320
|
+
if (!isPlainObject(raw))
|
|
321
|
+
return invalid;
|
|
322
|
+
const transport = raw.type;
|
|
323
|
+
if ((transport !== undefined && transport !== "stdio") || (raw.command === undefined && raw.url !== undefined)) {
|
|
324
|
+
return { ...invalid, definitionValid: true, stdio: false };
|
|
325
|
+
}
|
|
326
|
+
const command = raw.command;
|
|
327
|
+
const args = raw.args ?? [];
|
|
328
|
+
const env = raw.env ?? {};
|
|
329
|
+
if (typeof command !== "string" ||
|
|
330
|
+
command.trim().length === 0 ||
|
|
331
|
+
!Array.isArray(args) ||
|
|
332
|
+
args.some((a) => typeof a !== "string") ||
|
|
333
|
+
!isPlainObject(env) ||
|
|
334
|
+
Object.entries(env).some(([k, v]) => !ENV_KEY_RE.test(k) || typeof v !== "string")) {
|
|
335
|
+
return invalid;
|
|
336
|
+
}
|
|
337
|
+
const values = env;
|
|
338
|
+
return {
|
|
339
|
+
name,
|
|
340
|
+
origin,
|
|
341
|
+
definitionValid: true,
|
|
342
|
+
stdio: true,
|
|
343
|
+
command,
|
|
344
|
+
args: [...args],
|
|
345
|
+
plainEnv: {},
|
|
346
|
+
envKeys: Object.keys(values).sort(),
|
|
347
|
+
...(Object.keys(values).length > 0 ? { secretEnv: new EntryEnvValues(values) } : {}),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/** Normalize the `mcpServers` of one host or project config document. */
|
|
351
|
+
function normalizeServersDocument(doc, origin, rootKey) {
|
|
352
|
+
if (!isPlainObject(doc))
|
|
353
|
+
return [];
|
|
354
|
+
const servers = doc[rootKey];
|
|
355
|
+
if (!isPlainObject(servers))
|
|
356
|
+
return [];
|
|
357
|
+
return Object.entries(servers).map(([name, raw]) => normalizeConfigEntry(name, origin, raw));
|
|
358
|
+
}
|
|
359
|
+
async function normalizeRepositoryEntries(deps) {
|
|
360
|
+
const read = await readBridgeConfig(deps.cwd, { readFile: deps.readFile });
|
|
361
|
+
if (!read.ok)
|
|
362
|
+
return [];
|
|
363
|
+
return read.manifest.mcp.map((entry) => {
|
|
364
|
+
const name = entry.target;
|
|
365
|
+
const command = entry.command ?? "";
|
|
366
|
+
const registry = getThirdPartyTargetDefinition(name);
|
|
367
|
+
const normalized = {
|
|
368
|
+
name,
|
|
369
|
+
origin: "repository",
|
|
370
|
+
definitionValid: command.trim().length > 0,
|
|
371
|
+
stdio: true,
|
|
372
|
+
command,
|
|
373
|
+
args: [...(entry.args ?? [])],
|
|
374
|
+
plainEnv: {},
|
|
375
|
+
envKeys: [],
|
|
376
|
+
};
|
|
377
|
+
if (entry.secretBundle !== undefined) {
|
|
378
|
+
// The `.bridge/config` subset has no way to name the keys a bundle
|
|
379
|
+
// supplies, so only a registry target's keys are known. Copying an
|
|
380
|
+
// unrestricted bundle is never safe.
|
|
381
|
+
normalized.declaredBundle = entry.secretBundle;
|
|
382
|
+
if (registry !== undefined)
|
|
383
|
+
normalized.declaredBundleKeys = [...registry.requiredEnvKeys].sort();
|
|
384
|
+
}
|
|
385
|
+
else if (registry !== undefined && registry.requiredEnvKeys.length > 0) {
|
|
386
|
+
normalized.missingRequiredBundle = true;
|
|
387
|
+
}
|
|
388
|
+
return normalized;
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
/** Attach local-build package evidence, read through the injected seam. */
|
|
392
|
+
async function withPackageEvidence(entries, readFile) {
|
|
393
|
+
const out = [];
|
|
394
|
+
for (const entry of entries) {
|
|
395
|
+
if (entry.definitionValid && entry.stdio && isLocalBuildLauncher(entry.command, entry.args)) {
|
|
396
|
+
out.push({ ...entry, packageIdentity: await collectLocalBuildPackageIdentity(entry.args[0], readFile) });
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
out.push(entry);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
function canonicalDefinition(def) {
|
|
405
|
+
return JSON.stringify({
|
|
406
|
+
command: def.command,
|
|
407
|
+
args: def.args,
|
|
408
|
+
env: Object.keys(def.env).sort().map((k) => [k, def.env[k]]),
|
|
409
|
+
stagedEnvKeys: def.stagedEnvKeys,
|
|
410
|
+
declaredBundle: def.declaredBundle ?? null,
|
|
411
|
+
declaredBundleKeys: def.declaredBundleKeys ?? null,
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
function sha256(text) {
|
|
415
|
+
return createHash("sha256").update(text).digest("hex");
|
|
416
|
+
}
|
|
417
|
+
/** Turn an offered normalized entry into a raw definition. Host and project values are staged; others are plain. */
|
|
418
|
+
function offeredDefinition(entry) {
|
|
419
|
+
const staged = entry.secretEnv !== undefined;
|
|
420
|
+
return {
|
|
421
|
+
name: entry.name,
|
|
422
|
+
origin: entry.origin,
|
|
423
|
+
command: entry.command,
|
|
424
|
+
args: [...entry.args],
|
|
425
|
+
env: staged ? {} : { ...entry.plainEnv },
|
|
426
|
+
stagedEnvKeys: staged ? [...entry.envKeys] : [],
|
|
427
|
+
...(entry.declaredBundle !== undefined
|
|
428
|
+
? { declaredBundle: entry.declaredBundle, declaredBundleKeys: [...(entry.declaredBundleKeys ?? [])] }
|
|
429
|
+
: {}),
|
|
430
|
+
...(staged ? { secretValues: entry.secretEnv.copy() } : {}),
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
/** Normalize one published grant entry. Its metadata is trusted for key names, never resolved. */
|
|
434
|
+
function normalizeGrantEntry(server) {
|
|
435
|
+
const plainEnv = { ...(server.env ?? {}) };
|
|
436
|
+
return {
|
|
437
|
+
name: server.name,
|
|
438
|
+
origin: server.source === "preset" ? "preset" : server.source === "host" ? "claude" : "repository",
|
|
439
|
+
definitionValid: true,
|
|
440
|
+
stdio: server.transport === "stdio",
|
|
441
|
+
command: server.command,
|
|
442
|
+
args: [...server.args],
|
|
443
|
+
plainEnv,
|
|
444
|
+
envKeys: [...new Set([...Object.keys(plainEnv), ...(server.secret_env_keys ?? [])])].sort(),
|
|
445
|
+
...(server.secret_bundle !== undefined
|
|
446
|
+
? {
|
|
447
|
+
declaredBundle: server.secret_bundle,
|
|
448
|
+
// An already-published bundle's key names are declared in the grant itself,
|
|
449
|
+
// so the discovery-only registry rule does not apply.
|
|
450
|
+
...(server.secret_env_keys !== undefined ? { declaredBundleKeys: [...server.secret_env_keys] } : {}),
|
|
451
|
+
}
|
|
452
|
+
: {}),
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Check every server in a validated grant with the same rules. Read-only:
|
|
457
|
+
* bundle values are never resolved and nothing is written. Returns per-server
|
|
458
|
+
* findings (name plus fixed reason); a safe server yields none.
|
|
459
|
+
*/
|
|
460
|
+
export async function inspectExistingMcpGrant(grant, context, readFile) {
|
|
461
|
+
const entries = await withPackageEvidence(grant.servers.map(normalizeGrantEntry), readFile);
|
|
462
|
+
const findings = [];
|
|
463
|
+
for (const entry of entries) {
|
|
464
|
+
const result = classifyMcpGrantEntry(entry, { ...context, allowReservedName: entry.origin === "preset" });
|
|
465
|
+
if (result.state === "excluded" || result.state === "unclassifiable") {
|
|
466
|
+
findings.push({ name: entry.name, reason: result.reason });
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
return findings.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
470
|
+
}
|
|
471
|
+
async function readExistingGrant(deps, context) {
|
|
472
|
+
if (deps.readGrant === undefined)
|
|
473
|
+
return { state: "absent" };
|
|
474
|
+
let read;
|
|
475
|
+
try {
|
|
476
|
+
read = await deps.readGrant();
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
return { state: "unusable" };
|
|
480
|
+
}
|
|
481
|
+
if (read.state === "absent")
|
|
482
|
+
return { state: "absent" };
|
|
483
|
+
if (read.state === "unusable")
|
|
484
|
+
return { state: "unusable" };
|
|
485
|
+
return { state: "ok", findings: await inspectExistingMcpGrant(read.grant, context, deps.readFile) };
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Discover the candidate inventory. Deterministic: candidates sort by name, a
|
|
489
|
+
* name's definitions by id, and identical definitions collapse with every origin
|
|
490
|
+
* kept. Differing definitions under one name stay as alternatives. Read-only.
|
|
491
|
+
*/
|
|
492
|
+
export async function discoverMcpGrantCandidates(deps) {
|
|
493
|
+
const home = deps.homedir();
|
|
494
|
+
const context = {
|
|
495
|
+
repoName: deps.repoName,
|
|
496
|
+
isKnownBridgeUrl: knownBridgeUrlMatcher(deps.productionBaseUrl, deps.destination),
|
|
497
|
+
};
|
|
498
|
+
const entries = [
|
|
499
|
+
...normalizeServersDocument(await readJsonIfPresent(resolveClaudeUserConfigPath(home, deps.platform), deps), "claude", "mcpServers"),
|
|
500
|
+
...normalizeServersDocument(await readJsonIfPresent(resolveCursorUserConfigPath(home), deps), "cursor", "mcpServers"),
|
|
501
|
+
];
|
|
502
|
+
for (const project of PROJECT_CONFIG_ORIGINS) {
|
|
503
|
+
const rootKey = launcherTargetFor(project.relPath)?.topLevelKey ?? "mcpServers";
|
|
504
|
+
entries.push(...normalizeServersDocument(await readJsonIfPresent(path.join(deps.cwd, ...project.relPath.split("/")), deps), project.origin, rootKey));
|
|
505
|
+
}
|
|
506
|
+
entries.push(...(await normalizeRepositoryEntries(deps)));
|
|
507
|
+
const preset = playwrightPresetEntry();
|
|
508
|
+
if (preset !== null) {
|
|
509
|
+
entries.push({
|
|
510
|
+
name: preset.name,
|
|
511
|
+
origin: "preset",
|
|
512
|
+
definitionValid: true,
|
|
513
|
+
stdio: true,
|
|
514
|
+
command: preset.command,
|
|
515
|
+
args: [...preset.args],
|
|
516
|
+
plainEnv: {},
|
|
517
|
+
envKeys: [],
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
const definitions = [];
|
|
521
|
+
const exclusionList = [];
|
|
522
|
+
for (const entry of await withPackageEvidence(entries, deps.readFile)) {
|
|
523
|
+
const result = classifyMcpGrantEntry(entry, { ...context, allowReservedName: entry.origin === "preset" });
|
|
524
|
+
if (result.state === "skipped")
|
|
525
|
+
continue;
|
|
526
|
+
if (result.state === "offered")
|
|
527
|
+
definitions.push(offeredDefinition(entry));
|
|
528
|
+
else
|
|
529
|
+
exclusionList.push({ name: entry.name, origin: entry.origin, reason: result.reason });
|
|
530
|
+
}
|
|
531
|
+
const secrets = new CandidateSecrets();
|
|
532
|
+
const byName = new Map();
|
|
533
|
+
for (const raw of definitions) {
|
|
534
|
+
const canonical = canonicalDefinition(raw);
|
|
535
|
+
const source = ORIGIN_SOURCE[raw.origin];
|
|
536
|
+
// The source is part of identity: a host and a repository entry are different approvals.
|
|
537
|
+
const id = `${raw.name}#${sha256(`${source}\n${canonical}`).slice(0, 16)}`;
|
|
538
|
+
const defs = byName.get(raw.name) ?? new Map();
|
|
539
|
+
byName.set(raw.name, defs);
|
|
540
|
+
const existing = defs.get(id);
|
|
541
|
+
if (existing !== undefined) {
|
|
542
|
+
if (!existing.origins.includes(raw.origin))
|
|
543
|
+
existing.origins.push(raw.origin);
|
|
544
|
+
existing.origins.sort();
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
defs.set(id, {
|
|
548
|
+
id,
|
|
549
|
+
source,
|
|
550
|
+
origins: [raw.origin],
|
|
551
|
+
command: raw.command,
|
|
552
|
+
args: [...raw.args],
|
|
553
|
+
env: { ...raw.env },
|
|
554
|
+
stagedEnvKeys: [...raw.stagedEnvKeys],
|
|
555
|
+
...(raw.declaredBundle !== undefined ? { declaredBundle: raw.declaredBundle, declaredBundleKeys: [...(raw.declaredBundleKeys ?? [])] } : {}),
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
// Identical definitions share key names; the first origin's values are staged.
|
|
559
|
+
if (raw.secretValues !== undefined && secrets.get(id) === undefined)
|
|
560
|
+
secrets.set(id, raw.secretValues);
|
|
561
|
+
}
|
|
562
|
+
const candidates = [...byName.entries()]
|
|
563
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
564
|
+
.map(([name, defs]) => ({ name, definitions: [...defs.values()].sort((a, b) => (a.id < b.id ? -1 : 1)) }));
|
|
565
|
+
const exclusions = [...exclusionList].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.origin < b.origin ? -1 : a.origin > b.origin ? 1 : a.reason < b.reason ? -1 : 1));
|
|
566
|
+
const presetUnavailable = preset === null;
|
|
567
|
+
return {
|
|
568
|
+
candidates,
|
|
569
|
+
exclusions,
|
|
570
|
+
presetUnavailable,
|
|
571
|
+
fingerprint: computeCandidateFingerprint(candidates, exclusions, presetUnavailable),
|
|
572
|
+
secrets,
|
|
573
|
+
existingGrant: await readExistingGrant(deps, context),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
/** The canonical, secret-free fingerprint of an inventory. */
|
|
577
|
+
export function computeCandidateFingerprint(candidates, exclusions, presetUnavailable) {
|
|
578
|
+
const canonical = {
|
|
579
|
+
version: 1,
|
|
580
|
+
candidates: candidates.map((c) => ({
|
|
581
|
+
name: c.name,
|
|
582
|
+
definitions: c.definitions.map((d) => ({
|
|
583
|
+
source: d.source,
|
|
584
|
+
origins: d.origins,
|
|
585
|
+
transport: "stdio",
|
|
586
|
+
command: d.command,
|
|
587
|
+
args: d.args,
|
|
588
|
+
env: Object.keys(d.env).sort().map((k) => [k, d.env[k]]),
|
|
589
|
+
staged_env_keys: d.stagedEnvKeys,
|
|
590
|
+
declared_bundle: d.declaredBundle ?? null,
|
|
591
|
+
declared_bundle_keys: d.declaredBundleKeys ?? null,
|
|
592
|
+
})),
|
|
593
|
+
})),
|
|
594
|
+
exclusions: exclusions.map((e) => [e.name, e.origin, e.reason]),
|
|
595
|
+
preset_unavailable: presetUnavailable,
|
|
596
|
+
};
|
|
597
|
+
return sha256(JSON.stringify(canonical));
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* The plain-language exclusion lines for display. Names and fixed text only.
|
|
601
|
+
* BAPI-1636: an already-granted server that fails the current rules is listed
|
|
602
|
+
* too, as still active; this never changes the grant.
|
|
603
|
+
*/
|
|
604
|
+
export function describeInventoryExclusions(inventory) {
|
|
605
|
+
const lines = inventory.exclusions.map((e) => `${e.name} (${CANDIDATE_ORIGIN_LABEL[e.origin]}): ${CANDIDATE_EXCLUSION_TEXT[e.reason]}`);
|
|
606
|
+
if (inventory.existingGrant?.state === "ok") {
|
|
607
|
+
for (const finding of inventory.existingGrant.findings) {
|
|
608
|
+
lines.push(`${finding.name} (already approved and still active for workers): ${CANDIDATE_EXCLUSION_TEXT[finding.reason]}`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (inventory.presetUnavailable)
|
|
612
|
+
lines.push(PLAYWRIGHT_PRESET_UNAVAILABLE_TEXT);
|
|
613
|
+
return lines;
|
|
614
|
+
}
|
|
615
|
+
// ---------------------------------------------------------------------------
|
|
616
|
+
// Selection (BAPI-1636: moved from the conductor; Enter now means none)
|
|
617
|
+
// ---------------------------------------------------------------------------
|
|
618
|
+
/** The grant selection prompt. The default it shows is the default it applies. */
|
|
619
|
+
export const GRANT_SELECTION_PROMPT = ' Servers to approve (numbers separated by commas, "all", or "none") [none]: ';
|
|
620
|
+
/**
|
|
621
|
+
* Parse a selection answer into offered-list positions. Null when unusable.
|
|
622
|
+
* Blank and `none` select nothing; only an explicit `all` selects everything.
|
|
623
|
+
*/
|
|
624
|
+
export function parseGrantSelection(answer, count) {
|
|
625
|
+
const text = answer.trim().toLowerCase();
|
|
626
|
+
if (text === "none" || text === "")
|
|
627
|
+
return [];
|
|
628
|
+
if (text === "all")
|
|
629
|
+
return Array.from({ length: count }, (_, i) => i);
|
|
630
|
+
const picked = new Set();
|
|
631
|
+
for (const part of text.split(",")) {
|
|
632
|
+
const n = Number(part.trim());
|
|
633
|
+
if (!Number.isInteger(n) || n < 1 || n > count)
|
|
634
|
+
return null;
|
|
635
|
+
picked.add(n - 1);
|
|
636
|
+
}
|
|
637
|
+
return [...picked].sort((a, b) => a - b);
|
|
638
|
+
}
|
|
639
|
+
function indexDefinitions(inventory) {
|
|
640
|
+
const byId = new Map();
|
|
641
|
+
for (const candidate of inventory.candidates) {
|
|
642
|
+
for (const def of candidate.definitions)
|
|
643
|
+
byId.set(def.id, { name: candidate.name, def });
|
|
644
|
+
}
|
|
645
|
+
return byId;
|
|
646
|
+
}
|
|
647
|
+
function sameDefinition(a, b) {
|
|
648
|
+
return a.source === b.source && canonicalDefinition(a) === canonicalDefinition(b);
|
|
649
|
+
}
|
|
650
|
+
/** A refusal naming a safe server name and the fixed reason. Never an id or a value. */
|
|
651
|
+
function refusalFor(name, fresh) {
|
|
652
|
+
const excluded = fresh.exclusions.find((e) => e.name === name);
|
|
653
|
+
return excluded !== undefined
|
|
654
|
+
? `${name} can no longer be approved: ${CANDIDATE_EXCLUSION_TEXT[excluded.reason]}`
|
|
655
|
+
: `${name} is no longer offered`;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Check a selection against a FRESH inventory before anything is staged. The
|
|
659
|
+
* fresh inventory is a new discovery, so the classifier has already run again
|
|
660
|
+
* on every entry with refreshed package and destination evidence. A selection is
|
|
661
|
+
* refused when an id is no longer offered, a definition's canonical launch
|
|
662
|
+
* metadata changed (compared in full, not by the truncated id hash), a server is
|
|
663
|
+
* named twice, or the selection is over the limit. Errors carry only a safe
|
|
664
|
+
* server name and fixed text.
|
|
665
|
+
*/
|
|
666
|
+
export function revalidateMcpGrantSelection(fresh, selectedDefinitionIds, approved) {
|
|
667
|
+
const approvedById = indexDefinitions(approved);
|
|
668
|
+
const freshById = indexDefinitions(fresh);
|
|
669
|
+
const chosen = [];
|
|
670
|
+
const names = new Set();
|
|
671
|
+
for (const id of selectedDefinitionIds) {
|
|
672
|
+
const shown = approvedById.get(id);
|
|
673
|
+
if (shown === undefined) {
|
|
674
|
+
// An id that was never offered. Name the server only when the fresh
|
|
675
|
+
// inventory itself reports it, so a submitted id is never echoed.
|
|
676
|
+
const hash = id.indexOf("#");
|
|
677
|
+
const excluded = hash > 0 ? fresh.exclusions.find((e) => e.name === id.slice(0, hash)) : undefined;
|
|
678
|
+
return {
|
|
679
|
+
ok: false,
|
|
680
|
+
error: excluded !== undefined
|
|
681
|
+
? `${excluded.name} cannot be approved: ${CANDIDATE_EXCLUSION_TEXT[excluded.reason]}`
|
|
682
|
+
: "the selection names a server that is not offered",
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
const current = freshById.get(id);
|
|
686
|
+
if (current === undefined || current.name !== shown.name)
|
|
687
|
+
return { ok: false, error: refusalFor(shown.name, fresh) };
|
|
688
|
+
if (!sameDefinition(shown.def, current.def)) {
|
|
689
|
+
return { ok: false, error: `${shown.name} changed after it was shown; re-run setup to review it` };
|
|
690
|
+
}
|
|
691
|
+
if (names.has(current.name))
|
|
692
|
+
return { ok: false, error: "the selection names a server twice" };
|
|
693
|
+
names.add(current.name);
|
|
694
|
+
chosen.push(current);
|
|
695
|
+
}
|
|
696
|
+
if (chosen.length > MCP_GRANT_MAX_SERVERS)
|
|
697
|
+
return { ok: false, error: `at most ${MCP_GRANT_MAX_SERVERS} servers can be approved` };
|
|
698
|
+
return { ok: true, chosen };
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Publish an approved selection: rediscover and revalidate it, then stage every
|
|
702
|
+
* imported secret into a FRESH grant-specific credential-store target (never
|
|
703
|
+
* one the current grant references), then write the grant durably. Any refusal
|
|
704
|
+
* or failure stops before the grant is written, and a refusal stops before any
|
|
705
|
+
* credential is staged, so the previous grant and the credentials it references
|
|
706
|
+
* are left intact. Errors are fixed and name no value. The grant is written from
|
|
707
|
+
* the revalidated fresh definitions and the fresh inventory's fingerprint.
|
|
708
|
+
*/
|
|
709
|
+
export async function publishMcpGrant(repoName, inventory, selectedDefinitionIds, now, deps) {
|
|
710
|
+
let fresh;
|
|
711
|
+
try {
|
|
712
|
+
fresh = await deps.rediscover();
|
|
713
|
+
}
|
|
714
|
+
catch {
|
|
715
|
+
return { ok: false, error: "the servers could not be checked again before saving" };
|
|
716
|
+
}
|
|
717
|
+
const revalidated = revalidateMcpGrantSelection(fresh, selectedDefinitionIds, inventory);
|
|
718
|
+
if (!revalidated.ok)
|
|
719
|
+
return revalidated;
|
|
720
|
+
const chosen = [...revalidated.chosen].sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
721
|
+
// Every staged key set must be available before the first credential write.
|
|
722
|
+
for (const { name, def } of chosen) {
|
|
723
|
+
if (def.stagedEnvKeys.length === 0)
|
|
724
|
+
continue;
|
|
725
|
+
const values = fresh.secrets.get(def.id);
|
|
726
|
+
if (values === undefined || def.stagedEnvKeys.some((k) => typeof values[k] !== "string")) {
|
|
727
|
+
return { ok: false, error: `the credentials for ${name} could not be staged` };
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const suffix = deps.bundleSuffix ?? (() => `${now.getTime().toString(36)}-${randomBytes(4).toString("hex")}`);
|
|
731
|
+
const upsert = deps.upsertBundle ?? upsertCredentialBundle;
|
|
732
|
+
const servers = [];
|
|
733
|
+
for (const { name, def } of chosen) {
|
|
734
|
+
const entry = { name, source: def.source, transport: "stdio", command: def.command, args: [...def.args] };
|
|
735
|
+
if (Object.keys(def.env).length > 0)
|
|
736
|
+
entry.env = { ...def.env };
|
|
737
|
+
if (def.stagedEnvKeys.length > 0) {
|
|
738
|
+
const all = fresh.secrets.get(def.id);
|
|
739
|
+
// Only the approved key names are staged.
|
|
740
|
+
const values = {};
|
|
741
|
+
for (const key of def.stagedEnvKeys)
|
|
742
|
+
values[key] = all[key];
|
|
743
|
+
const target = `mcp-grant:${repoName}:${name}:${suffix()}`;
|
|
744
|
+
const staged = await upsert(target, values, deps.credentialStore, { createOnly: true });
|
|
745
|
+
if (!staged.ok)
|
|
746
|
+
return { ok: false, error: `the credentials for ${name} could not be stored` };
|
|
747
|
+
entry.secret_bundle = target;
|
|
748
|
+
entry.secret_env_keys = [...def.stagedEnvKeys];
|
|
749
|
+
}
|
|
750
|
+
else if (def.declaredBundle !== undefined) {
|
|
751
|
+
entry.secret_bundle = def.declaredBundle;
|
|
752
|
+
entry.secret_env_keys = [...(def.declaredBundleKeys ?? [])];
|
|
753
|
+
}
|
|
754
|
+
servers.push(entry);
|
|
755
|
+
}
|
|
756
|
+
const grant = {
|
|
757
|
+
version: MCP_GRANT_VERSION,
|
|
758
|
+
repo_name: repoName,
|
|
759
|
+
granted_at: now.toISOString(),
|
|
760
|
+
candidate_fingerprint: fresh.fingerprint,
|
|
761
|
+
servers,
|
|
762
|
+
};
|
|
763
|
+
const written = await (deps.writeGrant ?? writeMcpGrant)(grant, deps.grant);
|
|
764
|
+
if (!written.ok)
|
|
765
|
+
return { ok: false, error: written.error };
|
|
766
|
+
return { ok: true, grant, path: written.path };
|
|
767
|
+
}
|