@tpsdev-ai/flair 0.58.0 → 0.62.0
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 +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1030 -343
- package/dist/commands/agent.js +384 -45
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +601 -163
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +146 -53
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +27 -2
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1775 -338
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +103 -7
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +227 -64
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/OrgSkillAssignment.js +209 -0
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +120 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +6 -6
- package/docs/mcp-clients.md +10 -5
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +34 -28
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
package/dist/lib/mcp-enable.js
CHANGED
|
@@ -56,8 +56,6 @@
|
|
|
56
56
|
* - Sherlock: `accessTokenTtl` is explicitly 900 in the written config
|
|
57
57
|
* block, never left at the plugin's 1h default (see
|
|
58
58
|
* `buildMcpOAuthConfigBlock`).
|
|
59
|
-
* - Sherlock: the RS256 keypair comes from `crypto.generateKeyPairSync`
|
|
60
|
-
* (see `generateRsaSigningKeyPair`), never a PRNG shortcut.
|
|
61
59
|
* - Sherlock (the #741 lesson): self-verification is the exit criterion.
|
|
62
60
|
* On failure, the result names which step to re-run — never reports
|
|
63
61
|
* success on hope (see `EnableMcpResult.failedStep`). flair#756 extends
|
|
@@ -82,8 +80,8 @@
|
|
|
82
80
|
* ops paths" the design addendum names, not a new mechanism invented for
|
|
83
81
|
* this slice.
|
|
84
82
|
* - `FLAIR_MCP_OAUTH` (resources/mcp-oauth-flag.ts) is read from
|
|
85
|
-
* `process.env` ONLY — never YAML config — so it (and the OAuth secrets
|
|
86
|
-
* the
|
|
83
|
+
* `process.env` ONLY — never YAML config — so it (and the OAuth secrets —
|
|
84
|
+
* the IdP client secret) cannot be set via
|
|
87
85
|
* `set_configuration`. Those are delivered through the shape-aware
|
|
88
86
|
* secrets-provisioning step below (a 0600 staging file the operator
|
|
89
87
|
* applies via Fabric Studio's environment panel, or their own
|
|
@@ -93,7 +91,7 @@
|
|
|
93
91
|
* the flag-OFF byte-identical boot with the new config.yaml block inert.
|
|
94
92
|
* - `@harperfast/oauth`'s config field names (`mcp.issuer`, `mcp.resource`,
|
|
95
93
|
* `mcp.accessTokenTtl`, `mcp.dynamicClientRegistration.enabled`,
|
|
96
|
-
* `mcp.clientIdMetadataDocuments.allowedHosts
|
|
94
|
+
* `mcp.clientIdMetadataDocuments.allowedHosts`) are
|
|
97
95
|
* confirmed against the installed 2.2.0 package's source
|
|
98
96
|
* (dist/types.d.ts:38-229, dist/lib/mcp/{dcr,cimd,keyStore,token}.js).
|
|
99
97
|
* - The self-verification target, `${issuer}/.well-known/oauth-
|
|
@@ -139,12 +137,19 @@
|
|
|
139
137
|
* in `cimd.js`, so listing an extra host is not a meaningful risk
|
|
140
138
|
* expansion.
|
|
141
139
|
*/
|
|
140
|
+
import { isLoopbackUrl } from "../component-env.js";
|
|
142
141
|
import { probeSecretsCapability, pushSecrets, PROCESS_ENV_TIER } from "./secrets-push.js";
|
|
143
|
-
import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from "node:fs";
|
|
144
|
-
import {
|
|
145
|
-
import {
|
|
142
|
+
import { existsSync, lstatSync, mkdirSync, writeFileSync, chmodSync, readFileSync, realpathSync } from "node:fs";
|
|
143
|
+
import { hostname as osHostname } from "node:os";
|
|
144
|
+
import { join, dirname, resolve } from "node:path";
|
|
145
|
+
import { randomBytes } from "node:crypto";
|
|
146
146
|
import yaml from "js-yaml";
|
|
147
147
|
import { resolveHome } from "./home.js";
|
|
148
|
+
import { writeConfirmed } from "./instance-identity-row.js";
|
|
149
|
+
import { invalidAgentIdMessage, isValidAgentId } from "./agent-id-rule.js";
|
|
150
|
+
import { credentialMapsPrincipal, credentialPrincipalId } from "./credential-status-rule.js";
|
|
151
|
+
import { agentHomeEndpoint, resolveTargetInstanceId } from "./agent-home.js";
|
|
152
|
+
import { defaultReadProcessCmdline, defaultReadProcessCwd } from "./upgrade-exec-path.js";
|
|
148
153
|
// ─── CIMD constants ──────────────────────────────────────────────────────────
|
|
149
154
|
/** Default `clientIdMetadataDocuments.allowedHosts` allowlist — see the
|
|
150
155
|
* module header's "claude.ai CIMD/redirect-URI allowlist hosts" note for
|
|
@@ -154,134 +159,292 @@ export const DEFAULT_CIMD_ALLOWED_HOSTS = ["claude.ai", "claude.com"];
|
|
|
154
159
|
/** Required TTL per Sherlock's Model-2 requirement 1 — never the plugin's 1h default. */
|
|
155
160
|
export const REQUIRED_ACCESS_TOKEN_TTL = 900;
|
|
156
161
|
// ─── Local-origin detection (scenario addendum, binding) ───────────────────
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
* than proceed against an origin we can't even parse).
|
|
163
|
-
*/
|
|
162
|
+
function isLocalIpv4(a, b) {
|
|
163
|
+
return a === 0 || a === 10 || a === 127 ||
|
|
164
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
165
|
+
(a === 192 && b === 168) || (a === 169 && b === 254);
|
|
166
|
+
}
|
|
164
167
|
export function isLocalOrigin(url) {
|
|
165
168
|
let hostname;
|
|
166
169
|
try {
|
|
167
|
-
hostname = new URL(url).hostname.toLowerCase();
|
|
170
|
+
hostname = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
|
|
168
171
|
}
|
|
169
172
|
catch {
|
|
170
|
-
return
|
|
173
|
+
return false;
|
|
171
174
|
}
|
|
172
175
|
if (hostname === "localhost" || hostname.endsWith(".localhost"))
|
|
173
176
|
return true;
|
|
174
|
-
// WHATWG URL keeps IPv6 hosts bracketed in `.hostname` (e.g. "[::1]").
|
|
175
|
-
if (hostname === "::1" || hostname === "[::1]")
|
|
176
|
-
return true;
|
|
177
177
|
if (hostname.endsWith(".local"))
|
|
178
178
|
return true;
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
if (
|
|
184
|
-
return true; // loopback
|
|
185
|
-
if (a === 10)
|
|
186
|
-
return true; // RFC1918
|
|
187
|
-
if (a === 172 && b >= 16 && b <= 31)
|
|
188
|
-
return true; // RFC1918
|
|
189
|
-
if (a === 192 && b === 168)
|
|
190
|
-
return true; // RFC1918
|
|
191
|
-
if (a === 169 && b === 254)
|
|
192
|
-
return true; // link-local
|
|
193
|
-
if (a === 0)
|
|
179
|
+
if (hostname.startsWith("[")) {
|
|
180
|
+
if (hostname === "[::]" || hostname === "[::1]")
|
|
181
|
+
return true;
|
|
182
|
+
const first = parseInt(hostname.slice(1).split(":")[0] || "0", 16);
|
|
183
|
+
if ((first & 0xfe00) === 0xfc00 || (first & 0xffc0) === 0xfe80)
|
|
194
184
|
return true;
|
|
185
|
+
const mapped = hostname.match(/^\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\]$/);
|
|
186
|
+
if (mapped) {
|
|
187
|
+
const high = parseInt(mapped[1], 16);
|
|
188
|
+
return isLocalIpv4(high >>> 8, high & 0xff);
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
195
191
|
}
|
|
196
|
-
|
|
192
|
+
const ipv4 = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
193
|
+
return ipv4 !== null && isLocalIpv4(Number(ipv4[1]), Number(ipv4[2]));
|
|
197
194
|
}
|
|
198
|
-
/** Structural refusal check + the exact operator-facing message (scenario addendum). */
|
|
199
195
|
export function checkLocalOriginRefusal(url) {
|
|
196
|
+
try {
|
|
197
|
+
if (!new URL(url).hostname)
|
|
198
|
+
throw new Error("missing host");
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return { refused: true, reason: "invalid", message: "Issuer refused: invalid URL." };
|
|
202
|
+
}
|
|
200
203
|
if (isLocalOrigin(url))
|
|
201
|
-
return {
|
|
204
|
+
return {
|
|
205
|
+
refused: true, reason: "local",
|
|
206
|
+
message: "Issuer refused: local hostname or loopback, unspecified, reserved 0.0.0.0/8, private or link-local IP literal.",
|
|
207
|
+
};
|
|
202
208
|
return { refused: false };
|
|
203
209
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
* to pick the secrets-provisioning mechanism's DEFAULT — always overridable
|
|
207
|
-
* via `--secrets-mechanism`. */
|
|
208
|
-
export function isFabricOrigin(url) {
|
|
210
|
+
export function issuerOriginRefusal(issuer) {
|
|
211
|
+
let valid = false;
|
|
209
212
|
try {
|
|
210
|
-
|
|
213
|
+
if (/^https?:\/\/[^/?#\\\s]+\/?$/.test(issuer)) {
|
|
214
|
+
valid = issuer.replace(/\/$/, "") === new URL(issuer).origin;
|
|
215
|
+
}
|
|
211
216
|
}
|
|
212
217
|
catch {
|
|
213
|
-
|
|
218
|
+
valid = false;
|
|
214
219
|
}
|
|
220
|
+
if (valid)
|
|
221
|
+
return null;
|
|
222
|
+
return (`--issuer must be an absolute http(s) origin with no path (got: ${JSON.stringify(issuer)}); ` +
|
|
223
|
+
`set it to the instance's public origin, e.g. https://flair.example.com. Nothing was changed.`);
|
|
215
224
|
}
|
|
216
225
|
/**
|
|
217
|
-
*
|
|
218
|
-
* primary per the scenario addendum: a recognized Fabric origin defaults to
|
|
219
|
-
* `fabric-env-secrets` (Harper's encrypted env-secrets, 5.2-alpha as of this
|
|
220
|
-
* writing — see the module header on why this is a DOCUMENTED procedure, not
|
|
221
|
-
* an automated push: no confirmed ops-API operation for it exists in the
|
|
222
|
-
* installed 5.1.17 SDK). Anything else defaults to `env-file` — the
|
|
223
|
-
* documented, universally-supported fallback. Always overridable.
|
|
224
|
-
*/
|
|
225
|
-
/**
|
|
226
|
-
* ── The hostname no longer selects the mechanism (flair#1094) ───────────────
|
|
227
|
-
*
|
|
228
|
-
* This used to be `isFabricOrigin(url) ? "fabric-env-secrets" : "env-file"`, and
|
|
229
|
-
* that was wrong in BOTH directions on the day it was replaced:
|
|
226
|
+
* flair#2115 — the target policy for `flair principal link|unlink|links`.
|
|
230
227
|
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
* automated mechanism purely because of its name.
|
|
235
|
-
* - a self-hosted Harper 5.2 with the Pro env-secrets component is fully
|
|
236
|
-
* capable and was sent down the manual Studio path for not matching.
|
|
228
|
+
* These commands send the target instance's admin credential to its operations
|
|
229
|
+
* API. HTTPS is required, and an unparseable URL and the literal host classes
|
|
230
|
+
* `isLocalOrPrivateHost` lists are refused.
|
|
237
231
|
*
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
* process ship separately. `probeSecretsCapability` asks the target instead, and
|
|
241
|
-
* the answer decides at provisioning time.
|
|
242
|
-
*
|
|
243
|
-
* What remains here is the STAGING FILE's flavour of instructions, which is
|
|
244
|
-
* genuinely about where the operator will paste if we end up falling back.
|
|
245
|
-
* Fabric operators paste into Studio; everyone else edits a unit file. That is a
|
|
246
|
-
* UI fact about a human, not a claim about the server, so a hostname is a
|
|
247
|
-
* reasonable signal for it and a wrong guess costs only slightly-off prose.
|
|
232
|
+
* Refusals are only ADDED relative to `checkLocalOriginRefusal`: everything
|
|
233
|
+
* that check refuses, this one refuses too.
|
|
248
234
|
*/
|
|
249
|
-
export function
|
|
235
|
+
export function checkMappingTargetRefusal(url) {
|
|
236
|
+
let host;
|
|
237
|
+
let protocol;
|
|
238
|
+
try {
|
|
239
|
+
const parsed = new URL(url);
|
|
240
|
+
host = parsed.hostname;
|
|
241
|
+
protocol = parsed.protocol;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return { refused: true, message: mappingTargetRefusalMessage(url) };
|
|
245
|
+
}
|
|
246
|
+
if (protocol !== "https:" || host === "")
|
|
247
|
+
return { refused: true, message: mappingTargetRefusalMessage(url) };
|
|
248
|
+
if (isLocalOrPrivateHost(host))
|
|
249
|
+
return { refused: true, message: mappingTargetRefusalMessage(url) };
|
|
250
|
+
return { refused: false };
|
|
251
|
+
}
|
|
252
|
+
/** The one sentence a refused target gets, whichever way it failed that test. */
|
|
253
|
+
function mappingTargetRefusalMessage(url) {
|
|
254
|
+
return ("these commands send the target instance's admin credential to its operations API, so --instance must be an " +
|
|
255
|
+
"HTTPS URL whose host is not localhost, a .local name, or a loopback, unspecified, RFC1918, link-local or " +
|
|
256
|
+
`IPv6 unique-local address literal; '${url}' is refused. See the hosted-shape docs.`);
|
|
257
|
+
}
|
|
258
|
+
/** Is `hostname` (as `URL.hostname` gives it) localhost, a .local name, or a
|
|
259
|
+
* loopback, unspecified, RFC1918, link-local or IPv6 unique-local literal?
|
|
260
|
+
* IPv6 literals stay bracketed in `URL.hostname`; a trailing dot is the
|
|
261
|
+
* absolute form of the same name. */
|
|
262
|
+
function isLocalOrPrivateHost(hostname) {
|
|
263
|
+
const host = hostname.toLowerCase().replace(/\.+$/, "");
|
|
264
|
+
if (host === "")
|
|
265
|
+
return true;
|
|
266
|
+
if (host === "localhost" || host.endsWith(".localhost"))
|
|
267
|
+
return true;
|
|
268
|
+
if (host.endsWith(".local"))
|
|
269
|
+
return true;
|
|
270
|
+
if (host.startsWith("[") && host.endsWith("]"))
|
|
271
|
+
return isLocalOrPrivateIpv6(host.slice(1, -1));
|
|
272
|
+
const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
273
|
+
if (ipv4)
|
|
274
|
+
return isLocalOrPrivateIpv4(ipv4.slice(1).map((part) => Number(part)));
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
function isLocalOrPrivateIpv4(octets) {
|
|
278
|
+
const [a, b] = octets;
|
|
279
|
+
return (a === 0 ||
|
|
280
|
+
a === 10 ||
|
|
281
|
+
a === 127 ||
|
|
282
|
+
(a === 169 && b === 254) ||
|
|
283
|
+
(a === 172 && b >= 16 && b <= 31) ||
|
|
284
|
+
(a === 192 && b === 168));
|
|
285
|
+
}
|
|
286
|
+
function isLocalOrPrivateIpv6(literal) {
|
|
287
|
+
const addr = literal.toLowerCase();
|
|
288
|
+
// An IPv4-mapped address carries an IPv4 address in its low 32 bits; WHATWG
|
|
289
|
+
// URL normalises the dotted form to two hex groups ("::ffff:c0a8:1").
|
|
290
|
+
const mapped = addr.match(/^::ffff:([0-9a-f:.]+)$/);
|
|
291
|
+
if (mapped) {
|
|
292
|
+
const tail = mapped[1];
|
|
293
|
+
const dotted = tail.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
|
294
|
+
if (dotted)
|
|
295
|
+
return isLocalOrPrivateIpv4(dotted.slice(1).map((part) => Number(part)));
|
|
296
|
+
const groups = tail.split(":");
|
|
297
|
+
if (groups.length === 2) {
|
|
298
|
+
const hi = Number.parseInt(groups[0] || "0", 16);
|
|
299
|
+
const lo = Number.parseInt(groups[1] || "0", 16);
|
|
300
|
+
if (!Number.isNaN(hi) && !Number.isNaN(lo)) {
|
|
301
|
+
return isLocalOrPrivateIpv4([(hi >> 8) & 0xff, hi & 0xff, (lo >> 8) & 0xff, lo & 0xff]);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return true; // an IPv4-mapped form this cannot read is not a public origin
|
|
305
|
+
}
|
|
306
|
+
if (addr === "::" || addr === "::1")
|
|
307
|
+
return true; // unspecified, loopback
|
|
308
|
+
const first = Number.parseInt(addr.split(":")[0] || "0", 16);
|
|
309
|
+
if (Number.isNaN(first))
|
|
310
|
+
return true;
|
|
311
|
+
if ((first & 0xffc0) === 0xfe80)
|
|
312
|
+
return true; // fe80::/10 link-local
|
|
313
|
+
if ((first & 0xfe00) === 0xfc00)
|
|
314
|
+
return true; // fc00::/7 unique local
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
// ─── Fabric-shape detection (secrets-mechanism default) ────────────────────
|
|
318
|
+
export function isFabricOrigin(url) {
|
|
319
|
+
try {
|
|
320
|
+
return new URL(url).hostname.toLowerCase().endsWith(".harperfabric.com");
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
export function isFabricTarget(instanceUrl, fabric = false) {
|
|
327
|
+
return fabric === true || isFabricOrigin(instanceUrl);
|
|
328
|
+
}
|
|
329
|
+
export function fabricLoopbackRefusal(instanceUrl, fabric = false) {
|
|
330
|
+
if (fabric && isLoopbackUrl(instanceUrl))
|
|
331
|
+
return "--fabric cannot be used with a loopback or unspecified target. Remove --fabric.";
|
|
332
|
+
}
|
|
333
|
+
export function selectSecretsMechanism(instanceUrl, override, fabric = false) {
|
|
250
334
|
if (override)
|
|
251
335
|
return override;
|
|
252
|
-
return
|
|
253
|
-
}
|
|
254
|
-
/** RS256 signing keypair for `mcp.signingKeyPem` — `crypto.generateKeyPairSync`,
|
|
255
|
-
* never a PRNG shortcut (Sherlock's Model-2 requirement 2 implementation note). */
|
|
256
|
-
export function generateRsaSigningKeyPair() {
|
|
257
|
-
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
|
|
258
|
-
modulusLength: 2048,
|
|
259
|
-
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
260
|
-
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
261
|
-
});
|
|
262
|
-
return { publicKey, privateKey };
|
|
336
|
+
return isFabricTarget(instanceUrl, fabric) ? "fabric-env-secrets" : "env-file";
|
|
263
337
|
}
|
|
264
|
-
|
|
265
|
-
|
|
338
|
+
// ─── --cimd-allowed-hosts (flair#2113) ───────────────────────────────────────
|
|
339
|
+
//
|
|
340
|
+
// The component reads `mcp.clientIdMetadataDocuments.allowedHosts` from the
|
|
341
|
+
// `@harperfast/oauth` block of the component config.yaml. A whole-token `${VAR}`
|
|
342
|
+
// there can carry ONE host, but not a comma-separated list, and it cannot keep
|
|
343
|
+
// the default when unset. Measured on the installed @harperfast/oauth 2.5.0
|
|
344
|
+
// (dist/lib/config.js, `expandEnvVar` + `normalizeMcpSecurityConfig`): the
|
|
345
|
+
// variable's value becomes a one-entry list and is never split on commas; an
|
|
346
|
+
// unset variable leaves the literal placeholder as the only entry, so the
|
|
347
|
+
// claude.ai + claude.com default stops applying; and an empty value becomes
|
|
348
|
+
// `[]`, for which dist/lib/mcp/cimd.js skips its allowedHosts gate.
|
|
349
|
+
//
|
|
350
|
+
// So `enable` ensures a literal list in a config.yaml on THIS machine (the
|
|
351
|
+
// file it already edits for mcp.enabled), after the preflight match in
|
|
352
|
+
// `checkTargetRunsFromConfig`. It refuses a Fabric origin and, outside
|
|
353
|
+
// --dry-run, a failed match. --dry-run skips the match and never writes the list.
|
|
354
|
+
/** The config key the flag sets, as operator messages name it. */
|
|
355
|
+
export const CIMD_ALLOWED_HOSTS_CONFIG_KEY = "mcp.clientIdMetadataDocuments.allowedHosts";
|
|
356
|
+
/** A `--cimd-allowed-hosts` value that is not a list of lowercase bare hostnames. */
|
|
357
|
+
export class CimdAllowedHostsError extends Error {
|
|
358
|
+
constructor(message) {
|
|
359
|
+
super(message);
|
|
360
|
+
this.name = "CimdAllowedHostsError";
|
|
361
|
+
}
|
|
266
362
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
363
|
+
const HOSTNAME_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
364
|
+
/**
|
|
365
|
+
* Validate `--cimd-allowed-hosts` entries: lowercase bare hostnames only.
|
|
366
|
+
* Throws `CimdAllowedHostsError` for an empty list, or for the first bad entry
|
|
367
|
+
* (named, 1-based). Spaces around an entry are trimmed; nothing else is
|
|
368
|
+
* rewritten: an uppercase entry is refused, not lowercased.
|
|
369
|
+
*/
|
|
370
|
+
export function validateCimdAllowedHosts(entries) {
|
|
371
|
+
const flag = "--cimd-allowed-hosts";
|
|
372
|
+
if (entries.length === 0 || (entries.length === 1 && String(entries[0]).trim() === "")) {
|
|
373
|
+
throw new CimdAllowedHostsError(`${flag}: no hostnames given. Pass one or more lowercase hostnames, comma-separated (for example claude.ai,claude.com).`);
|
|
273
374
|
}
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
375
|
+
const hosts = [];
|
|
376
|
+
for (let i = 0; i < entries.length; i++) {
|
|
377
|
+
const host = String(entries[i]).trim();
|
|
378
|
+
const refuse = (why) => {
|
|
379
|
+
throw new CimdAllowedHostsError(`${flag} entry ${i + 1} ${why}`);
|
|
380
|
+
};
|
|
381
|
+
if (host === "")
|
|
382
|
+
refuse("is empty. Remove the extra comma, or pass a hostname.");
|
|
383
|
+
const shown = JSON.stringify(host);
|
|
384
|
+
if (host.includes("*"))
|
|
385
|
+
refuse(`(${shown}) is a wildcard. List each hostname exactly.`);
|
|
386
|
+
if (host.includes("/"))
|
|
387
|
+
refuse(`(${shown}) is a URL or path. Pass the bare hostname only.`);
|
|
388
|
+
if (host.startsWith("[") || host.split(":").length > 2)
|
|
389
|
+
refuse(`(${shown}) looks like an IPv6 address. Pass a hostname.`);
|
|
390
|
+
if (host.includes(":"))
|
|
391
|
+
refuse(`(${shown}) contains ":" (a port or scheme). Pass the bare hostname only.`);
|
|
392
|
+
if (host !== host.toLowerCase())
|
|
393
|
+
refuse(`(${shown}) has uppercase letters. Hostnames must be lowercase.`);
|
|
394
|
+
const labels = host.split(".");
|
|
395
|
+
if (host.length > 253 || !labels.every((label) => HOSTNAME_LABEL.test(label))) {
|
|
396
|
+
refuse(`(${shown}) is not a valid hostname: dot-separated labels of a-z, 0-9 and inner hyphens, ` +
|
|
397
|
+
`each 1-63 characters, 253 in all at most.`);
|
|
398
|
+
}
|
|
399
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1]))
|
|
400
|
+
refuse(`(${shown}) ends in a numeric label, as an IP address does. Pass a hostname.`);
|
|
401
|
+
if (hosts.includes(host))
|
|
402
|
+
refuse(`(${shown}) repeats an earlier entry.`);
|
|
403
|
+
hosts.push(host);
|
|
404
|
+
}
|
|
405
|
+
return hosts;
|
|
406
|
+
}
|
|
407
|
+
export function cimdAllowedHostsShapeRefusal(instanceUrl, fabric = false) {
|
|
408
|
+
if (!isFabricTarget(instanceUrl, fabric))
|
|
409
|
+
return null;
|
|
410
|
+
return (`--cimd-allowed-hosts is refused for a Fabric instance (${new URL(instanceUrl).hostname}): ` +
|
|
411
|
+
`the component reads ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} from the @harperfast/oauth block of the config.yaml ` +
|
|
412
|
+
`deployed with it, and this command does not write that file. ` +
|
|
413
|
+
`Set the key in the config.yaml you deploy, then redeploy. Nothing was changed.`);
|
|
280
414
|
}
|
|
281
|
-
/**
|
|
282
|
-
*
|
|
283
|
-
|
|
284
|
-
|
|
415
|
+
/**
|
|
416
|
+
* The CLI's reading of `--cimd-allowed-hosts`: `{}` when the flag is absent,
|
|
417
|
+
* `{ hosts }` when it is valid for this target, `{ error }` otherwise. An
|
|
418
|
+
* explicit empty value is an error, never "absent".
|
|
419
|
+
*/
|
|
420
|
+
export function cimdAllowedHostsFromFlag(raw, instanceUrl, fabric = false) {
|
|
421
|
+
if (raw === undefined)
|
|
422
|
+
return {};
|
|
423
|
+
let hosts;
|
|
424
|
+
try {
|
|
425
|
+
hosts = validateCimdAllowedHosts(String(raw).split(","));
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
return { error: err?.message ?? String(err) };
|
|
429
|
+
}
|
|
430
|
+
const refusal = cimdAllowedHostsShapeRefusal(instanceUrl, fabric);
|
|
431
|
+
return refusal ? { error: refusal } : { hosts };
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* The note a successful `enable` prints when the list this run confirmed
|
|
435
|
+
* leaves claude.ai out. `enable` ensures the requested list in config.yaml
|
|
436
|
+
* (it writes the list only when the file does not already hold that exact
|
|
437
|
+
* list) and reads it back; the argument is that read-back list.
|
|
438
|
+
* dist/lib/mcp/cimd.js treats a client_id URL whose host is not on a non-empty
|
|
439
|
+
* allowedHosts as an unknown client. Null when this run confirmed no list, or
|
|
440
|
+
* one with claude.ai.
|
|
441
|
+
*/
|
|
442
|
+
export function claudeAiExcludedNote(written) {
|
|
443
|
+
if (!written || written.includes("claude.ai"))
|
|
444
|
+
return null;
|
|
445
|
+
return (`claude.ai is not in the ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} list this run ensured and read back (${JSON.stringify(written)}), ` +
|
|
446
|
+
`so while the instance uses that list, a CIMD client_id URL on claude.ai is refused. ` +
|
|
447
|
+
`Re-run with claude.ai in --cimd-allowed-hosts to allow it.`);
|
|
285
448
|
}
|
|
286
449
|
/**
|
|
287
450
|
* The `@harperfast/oauth` config block, matching the installed 2.2.0
|
|
@@ -313,6 +476,12 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
313
476
|
[provider]: {
|
|
314
477
|
clientId: `\${${envPrefix}_CLIENT_ID}`,
|
|
315
478
|
clientSecret: `\${${envPrefix}_CLIENT_SECRET}`,
|
|
479
|
+
// Since @harperfast/oauth 2.7.0 a CONFIGURED provider (both
|
|
480
|
+
// credentials set) needs a redirectUri; 2.8.1 skips an UNCONFIGURED
|
|
481
|
+
// one before that check (HarperFast/oauth#259). Same whole-token
|
|
482
|
+
// reference shape as the credentials above — set to the instance's
|
|
483
|
+
// public origin plus /oauth; the component appends '/<provider>/callback'.
|
|
484
|
+
redirectUri: `\${${envPrefix}_REDIRECT_URI}`,
|
|
316
485
|
},
|
|
317
486
|
},
|
|
318
487
|
mcp: {
|
|
@@ -349,7 +518,8 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
349
518
|
// resolution still runs cimd.js's full SSRF/document-validation
|
|
350
519
|
// pipeline regardless of this list.
|
|
351
520
|
clientIdMetadataDocuments: { allowedHosts: cimdAllowedHosts },
|
|
352
|
-
signingKeyPem
|
|
521
|
+
// Without signingKeyPem, minting reuses a persisted key or generates
|
|
522
|
+
// and persists one if oauth.harper_oauth_mcp_keys is empty.
|
|
353
523
|
},
|
|
354
524
|
},
|
|
355
525
|
};
|
|
@@ -360,6 +530,18 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
360
530
|
* bundle stages FLAIR_MCP_OAUTH=true — see buildSecretsBundle for why it
|
|
361
531
|
* must be "true"), never as a literal in the config file. */
|
|
362
532
|
export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
|
|
533
|
+
/**
|
|
534
|
+
* The local component config.yaml `enable` edits: `explicitPath` alone when
|
|
535
|
+
* given, otherwise `./config.yaml`, then `~/.flair/config.yaml` — the first
|
|
536
|
+
* that exists. Shared by `updateLocalConfigMcpEnabled` and the flair#2113
|
|
537
|
+
* allowedHosts writer so both edit the same file.
|
|
538
|
+
*/
|
|
539
|
+
function resolveLocalConfigPath(explicitPath) {
|
|
540
|
+
const candidates = explicitPath
|
|
541
|
+
? [explicitPath]
|
|
542
|
+
: ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
|
|
543
|
+
return { configPath: candidates.find((p) => existsSync(p)) ?? null, candidates };
|
|
544
|
+
}
|
|
363
545
|
/**
|
|
364
546
|
* Set mcp.enabled in a local component config.yaml to the flair#1152 shape.
|
|
365
547
|
* Best-effort: returns `{ ok: false }` with a reason when the file can't be
|
|
@@ -371,20 +553,10 @@ export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
|
|
|
371
553
|
* to the reference). `enabled: false` writes literal `false` — decisively off
|
|
372
554
|
* regardless of environment.
|
|
373
555
|
*
|
|
374
|
-
*
|
|
375
|
-
* `~/.flair/config.yaml`.
|
|
556
|
+
* Uses `explicitPath` alone if given; otherwise `./config.yaml`, then `~/.flair/config.yaml`.
|
|
376
557
|
*/
|
|
377
558
|
export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
378
|
-
const candidates = explicitPath
|
|
379
|
-
? [explicitPath]
|
|
380
|
-
: ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
|
|
381
|
-
let configPath = null;
|
|
382
|
-
for (const p of candidates) {
|
|
383
|
-
if (existsSync(p)) {
|
|
384
|
-
configPath = p;
|
|
385
|
-
break;
|
|
386
|
-
}
|
|
387
|
-
}
|
|
559
|
+
const { configPath, candidates } = resolveLocalConfigPath(explicitPath);
|
|
388
560
|
// The value the file should carry for this call (flair#1152): the env
|
|
389
561
|
// reference when enabling, literal false when disabling.
|
|
390
562
|
const target = enabled ? MCP_ENABLED_ENV_REFERENCE : false;
|
|
@@ -393,7 +565,11 @@ export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
|
393
565
|
return {
|
|
394
566
|
ok: false,
|
|
395
567
|
detail: `local config.yaml not found (tried: ${candidates.join(", ")}). ` +
|
|
396
|
-
|
|
568
|
+
(enabled
|
|
569
|
+
? explicitPath
|
|
570
|
+
? `Place your component config.yaml at ${explicitPath}, then re-run with the same explicit path.`
|
|
571
|
+
: `Re-run \`flair mcp enable\` from the directory that holds your component config.yaml (or place it at ${candidates[1]}).`
|
|
572
|
+
: `Set mcp.enabled: ${targetLabel} in your component config.yaml manually, then restart.`),
|
|
397
573
|
};
|
|
398
574
|
}
|
|
399
575
|
let raw;
|
|
@@ -447,16 +623,322 @@ export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
|
447
623
|
}
|
|
448
624
|
return { ok: true, detail: `mcp.enabled set to ${targetLabel} in ${configPath}` };
|
|
449
625
|
}
|
|
626
|
+
const readConfigFile = (path) => readFileSync(path, "utf-8");
|
|
627
|
+
const writeConfigFile = (path, data) => writeFileSync(path, data, { encoding: "utf-8" });
|
|
628
|
+
/** Parse `path` and reach its `@harperfast/oauth` → `mcp` mapping. Every failure is a named `ok: false`. */
|
|
629
|
+
function loadOauthMcpBlock(path, readFile) {
|
|
630
|
+
let raw;
|
|
631
|
+
try {
|
|
632
|
+
raw = readFile(path);
|
|
633
|
+
}
|
|
634
|
+
catch (err) {
|
|
635
|
+
return { ok: false, detail: `cannot read ${path}: ${err?.message ?? err}` };
|
|
636
|
+
}
|
|
637
|
+
let doc;
|
|
638
|
+
try {
|
|
639
|
+
doc = yaml.load(raw);
|
|
640
|
+
}
|
|
641
|
+
catch (err) {
|
|
642
|
+
return { ok: false, detail: `cannot parse ${path} as YAML: ${err?.message ?? err}` };
|
|
643
|
+
}
|
|
644
|
+
const isMapping = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
645
|
+
const mcp = isMapping(doc) && isMapping(doc["@harperfast/oauth"]) ? doc["@harperfast/oauth"].mcp : undefined;
|
|
646
|
+
if (!isMapping(mcp))
|
|
647
|
+
return { ok: false, detail: `${path} has no @harperfast/oauth block with an mcp mapping` };
|
|
648
|
+
const cimd = mcp.clientIdMetadataDocuments;
|
|
649
|
+
if (cimd !== undefined && cimd !== null && !isMapping(cimd)) {
|
|
650
|
+
return { ok: false, detail: `${path}: mcp.clientIdMetadataDocuments is not a mapping` };
|
|
651
|
+
}
|
|
652
|
+
return { ok: true, detail: `${path} parsed`, raw, doc, mcp };
|
|
653
|
+
}
|
|
654
|
+
function sameHostList(value, hosts) {
|
|
655
|
+
return Array.isArray(value) && value.length === hosts.length && value.every((h, i) => h === hosts[i]);
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Read-only: which config.yaml would `updateLocalConfigCimdAllowedHosts` write,
|
|
659
|
+
* and what list does it carry now? Same file resolution as
|
|
660
|
+
* `updateLocalConfigMcpEnabled`. `enable` runs this before any step with a
|
|
661
|
+
* side effect, so a file that is missing, unreadable or not valid YAML, or that
|
|
662
|
+
* has no `@harperfast/oauth` → `mcp` mapping, refuses the flag up front. It
|
|
663
|
+
* does not check that the file can be written: a write failure fails the later
|
|
664
|
+
* `local-config-update` step.
|
|
665
|
+
*/
|
|
666
|
+
export function readLocalConfigCimdAllowedHosts(explicitPath, deps = {}) {
|
|
667
|
+
const { configPath: found, candidates } = resolveLocalConfigPath(explicitPath);
|
|
668
|
+
if (!found)
|
|
669
|
+
return { ok: false, detail: `no config.yaml found (tried: ${candidates.join(", ")})` };
|
|
670
|
+
const configPath = resolve(found);
|
|
671
|
+
const loaded = loadOauthMcpBlock(configPath, deps.readFile ?? readConfigFile);
|
|
672
|
+
if (!loaded.ok)
|
|
673
|
+
return { ok: false, path: configPath, detail: loaded.detail };
|
|
674
|
+
return {
|
|
675
|
+
ok: true,
|
|
676
|
+
path: configPath,
|
|
677
|
+
current: loaded.mcp.clientIdMetadataDocuments?.allowedHosts,
|
|
678
|
+
detail: `${configPath} carries ${CIMD_ALLOWED_HOSTS_CONFIG_KEY}: ${JSON.stringify(loaded.mcp.clientIdMetadataDocuments?.allowedHosts ?? null)}`,
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* The application directory a Harper `run` or `dev` command line names,
|
|
683
|
+
* resolved against the process's working directory; null when the command
|
|
684
|
+
* line has no `run`/`dev` token. With no directory argument Harper runs the
|
|
685
|
+
* application in its working directory (harper's bin/harper.js: `dev` falls
|
|
686
|
+
* through to `run`, whose folder argument is realpath'd from the cwd).
|
|
687
|
+
*/
|
|
688
|
+
export function harperAppDirFromCmdline(cmdline, cwd) {
|
|
689
|
+
const tokens = cmdline.split(/\0|\s+/).filter((t) => t.length > 0);
|
|
690
|
+
const at = tokens.findIndex((t) => t === "run" || t === "dev");
|
|
691
|
+
if (at === -1)
|
|
692
|
+
return null;
|
|
693
|
+
const arg = tokens[at + 1];
|
|
694
|
+
return resolve(cwd, arg && !arg.startsWith("-") ? arg : ".");
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* flair#2113 review: the preflight match between the target and `configPath`.
|
|
698
|
+
* All required:
|
|
699
|
+
* 1. the target's ops API `system_information` reports this machine's
|
|
700
|
+
* hostname and a Harper core process id;
|
|
701
|
+
* 2. that pid's working directory and command line can be read on this
|
|
702
|
+
* machine, and the command line names a `run`/`dev` application
|
|
703
|
+
* directory (`harperAppDirFromCmdline`);
|
|
704
|
+
* 3. `config.yaml` in that application directory and `configPath` resolve
|
|
705
|
+
* to the same file (`realpath`).
|
|
706
|
+
* A check that fails, or cannot be completed, gives `ok: false` with the
|
|
707
|
+
* reason.
|
|
708
|
+
*/
|
|
709
|
+
export async function checkTargetRunsFromConfig(instance, adminUser, adminPass, configPath, deps = {}) {
|
|
710
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
711
|
+
const readCwd = deps.readProcessCwd ?? defaultReadProcessCwd;
|
|
712
|
+
const readCmdline = deps.readProcessCmdline ?? defaultReadProcessCmdline;
|
|
713
|
+
const localHost = (deps.localHostname ?? osHostname)();
|
|
714
|
+
const opsUrl = resolveOpsUrl(instance);
|
|
715
|
+
let data;
|
|
716
|
+
try {
|
|
717
|
+
const res = await fetchImpl(opsUrl, {
|
|
718
|
+
method: "POST",
|
|
719
|
+
headers: { "Content-Type": "application/json", Authorization: basicAuthHeader(adminUser, adminPass) },
|
|
720
|
+
body: JSON.stringify({ operation: "system_information", attributes: ["system", "harperdb_processes"] }),
|
|
721
|
+
});
|
|
722
|
+
if (!res.ok) {
|
|
723
|
+
return { ok: false, detail: `the target's ops API at ${opsUrl} answered system_information with HTTP ${res.status}` };
|
|
724
|
+
}
|
|
725
|
+
data = await res.json();
|
|
726
|
+
}
|
|
727
|
+
catch (err) {
|
|
728
|
+
return { ok: false, detail: `could not ask the target's ops API at ${opsUrl} for system_information: ${err?.message ?? err}` };
|
|
729
|
+
}
|
|
730
|
+
const targetHost = data?.system?.hostname;
|
|
731
|
+
const pid = data?.harperdb_processes?.core?.[0]?.pid;
|
|
732
|
+
if (typeof targetHost !== "string" || targetHost === "" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
|
|
733
|
+
return { ok: false, detail: `the target's system_information did not report both its hostname and its Harper process id` };
|
|
734
|
+
}
|
|
735
|
+
if (targetHost.toLowerCase() !== localHost.toLowerCase()) {
|
|
736
|
+
return { ok: false, detail: `the target reports host ${JSON.stringify(targetHost)}, and this machine is ${JSON.stringify(localHost)}` };
|
|
737
|
+
}
|
|
738
|
+
const cwd = readCwd(pid);
|
|
739
|
+
if (!cwd) {
|
|
740
|
+
return { ok: false, detail: `the target reports pid ${pid}, and that pid's working directory could not be read on this machine` };
|
|
741
|
+
}
|
|
742
|
+
const cmdline = readCmdline(pid);
|
|
743
|
+
const appDir = cmdline ? harperAppDirFromCmdline(cmdline, cwd) : null;
|
|
744
|
+
if (!appDir) {
|
|
745
|
+
return {
|
|
746
|
+
ok: false,
|
|
747
|
+
detail: `the target reports pid ${pid}, which runs in ${cwd} on this machine, and its application directory could not be read from its command line`,
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
let targetConfig;
|
|
751
|
+
let editedConfig;
|
|
752
|
+
try {
|
|
753
|
+
targetConfig = realpathSync(join(appDir, "config.yaml"));
|
|
754
|
+
editedConfig = realpathSync(configPath);
|
|
755
|
+
}
|
|
756
|
+
catch (err) {
|
|
757
|
+
return { ok: false, detail: `the target reports pid ${pid}, whose command line on this machine names application directory ${appDir}, and a config.yaml could not be resolved: ${err?.message ?? err}` };
|
|
758
|
+
}
|
|
759
|
+
if (targetConfig !== editedConfig) {
|
|
760
|
+
return { ok: false, detail: `the target reports pid ${pid}, whose command line on this machine names application directory ${appDir}; its config.yaml is not ${editedConfig} by realpath` };
|
|
761
|
+
}
|
|
762
|
+
return {
|
|
763
|
+
ok: true,
|
|
764
|
+
detail: `preflight match: the target reports host ${targetHost} and pid ${pid}; that pid's command line on this machine names application directory ${appDir}, whose config.yaml is ${editedConfig} by realpath`,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Replace the value of `@harperfast/oauth` → `mcp` → `clientIdMetadataDocuments`
|
|
769
|
+
* → `allowedHosts` in `raw` with a block sequence of `hosts`, touching no line
|
|
770
|
+
* outside the list's own lines (comments between its items go with it).
|
|
771
|
+
* Returns null when the key is absent, appears more than once, or has a value
|
|
772
|
+
* this line scan does not handle (for example a flow sequence spanning lines);
|
|
773
|
+
* the caller then re-emits the parsed document instead. The caller also
|
|
774
|
+
* re-parses the result and compares it with the intended document before
|
|
775
|
+
* using it.
|
|
776
|
+
*/
|
|
777
|
+
function replaceAllowedHostsLines(raw, hosts) {
|
|
778
|
+
const path = ["@harperfast/oauth", "mcp", "clientIdMetadataDocuments", "allowedHosts"];
|
|
779
|
+
const eol = raw.includes("\r\n") ? "\r\n" : "\n";
|
|
780
|
+
const lines = raw.split(eol);
|
|
781
|
+
const skippable = (line) => /^\s*(#.*)?$/.test(line);
|
|
782
|
+
const indentOf = (line) => line.length - line.trimStart().length;
|
|
783
|
+
const keyLine = /^\s*(?:"([^"]*)"|'([^']*)'|([^\s#'"\-][^:#]*?))\s*:(?:\s+(.*))?$/;
|
|
784
|
+
const stack = [];
|
|
785
|
+
let at = -1;
|
|
786
|
+
let atIndent = 0;
|
|
787
|
+
let atRest = "";
|
|
788
|
+
for (let i = 0; i < lines.length; i++) {
|
|
789
|
+
const line = lines[i];
|
|
790
|
+
if (skippable(line))
|
|
791
|
+
continue;
|
|
792
|
+
const indent = indentOf(line);
|
|
793
|
+
while (stack.length > 0 && stack[stack.length - 1].indent >= indent)
|
|
794
|
+
stack.pop();
|
|
795
|
+
const m = keyLine.exec(line);
|
|
796
|
+
if (!m)
|
|
797
|
+
continue;
|
|
798
|
+
stack.push({ indent, key: m[1] ?? m[2] ?? m[3] });
|
|
799
|
+
if (stack.length === path.length && stack.every((s, k) => s.key === path[k])) {
|
|
800
|
+
if (at !== -1)
|
|
801
|
+
return null;
|
|
802
|
+
at = i;
|
|
803
|
+
atIndent = indent;
|
|
804
|
+
atRest = (m[4] ?? "").replace(/(^|\s+)#.*$/, "").trim();
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
if (at === -1)
|
|
808
|
+
return null;
|
|
809
|
+
let end = at;
|
|
810
|
+
if (atRest === "") {
|
|
811
|
+
for (let j = at + 1; j < lines.length; j++) {
|
|
812
|
+
const line = lines[j];
|
|
813
|
+
if (skippable(line))
|
|
814
|
+
continue;
|
|
815
|
+
const indent = indentOf(line);
|
|
816
|
+
if (indent > atIndent || (indent === atIndent && line.trimStart().startsWith("-"))) {
|
|
817
|
+
end = j;
|
|
818
|
+
continue;
|
|
819
|
+
}
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
else if (atRest.startsWith("[") && !atRest.endsWith("]")) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
const pad = " ".repeat(atIndent);
|
|
827
|
+
const block = [`${pad}allowedHosts:`, ...hosts.map((h) => `${pad} - ${JSON.stringify(h)}`)];
|
|
828
|
+
return [...lines.slice(0, at), ...block, ...lines.slice(end + 1)].join(eol);
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Set `mcp.clientIdMetadataDocuments.allowedHosts` in the local component
|
|
832
|
+
* config.yaml (same file resolution as `updateLocalConfigMcpEnabled`) to
|
|
833
|
+
* `hosts`, then read the file back. `ok: true` only when the read-back equals
|
|
834
|
+
* `hosts`; `readBack` is that read-back, never the intended value.
|
|
835
|
+
*
|
|
836
|
+
* The edit rewrites only the list's own lines when it can find them and the
|
|
837
|
+
* result parses to the intended document, so comments outside the list
|
|
838
|
+
* survive; otherwise it re-emits the parsed document, as
|
|
839
|
+
* `updateLocalConfigMcpEnabled` does, and says so in `detail`.
|
|
840
|
+
*/
|
|
841
|
+
export function updateLocalConfigCimdAllowedHosts(hosts, explicitPath, deps = {}) {
|
|
842
|
+
const readFile = deps.readFile ?? readConfigFile;
|
|
843
|
+
const writeFile = deps.writeFile ?? writeConfigFile;
|
|
844
|
+
let list;
|
|
845
|
+
try {
|
|
846
|
+
list = validateCimdAllowedHosts(hosts);
|
|
847
|
+
}
|
|
848
|
+
catch (err) {
|
|
849
|
+
return { ok: false, detail: err?.message ?? String(err) };
|
|
850
|
+
}
|
|
851
|
+
const { configPath: found, candidates } = resolveLocalConfigPath(explicitPath);
|
|
852
|
+
if (!found)
|
|
853
|
+
return { ok: false, detail: `no config.yaml found (tried: ${candidates.join(", ")})` };
|
|
854
|
+
const configPath = resolve(found);
|
|
855
|
+
const loaded = loadOauthMcpBlock(configPath, readFile);
|
|
856
|
+
if (!loaded.ok)
|
|
857
|
+
return { ok: false, path: configPath, detail: loaded.detail };
|
|
858
|
+
let how;
|
|
859
|
+
let wrote = false;
|
|
860
|
+
if (sameHostList(loaded.mcp.clientIdMetadataDocuments?.allowedHosts, list)) {
|
|
861
|
+
how = "the file already held this list, so the allowed-hosts write was skipped";
|
|
862
|
+
}
|
|
863
|
+
else {
|
|
864
|
+
const intended = structuredClone(loaded.doc);
|
|
865
|
+
const mcp = intended["@harperfast/oauth"].mcp;
|
|
866
|
+
mcp.clientIdMetadataDocuments = { ...(mcp.clientIdMetadataDocuments ?? {}), allowedHosts: [...list] };
|
|
867
|
+
const edited = replaceAllowedHostsLines(loaded.raw ?? "", list);
|
|
868
|
+
let text;
|
|
869
|
+
if (edited !== null && JSON.stringify(safeYamlLoad(edited)) === JSON.stringify(intended)) {
|
|
870
|
+
text = edited;
|
|
871
|
+
how = "only the list's own lines were rewritten";
|
|
872
|
+
}
|
|
873
|
+
else {
|
|
874
|
+
text = yaml.dump(intended, { lineWidth: -1, noCompatMode: true });
|
|
875
|
+
how = "the file was re-emitted from its parsed form, so its comments were not kept";
|
|
876
|
+
}
|
|
877
|
+
try {
|
|
878
|
+
writeFile(configPath, text);
|
|
879
|
+
}
|
|
880
|
+
catch (err) {
|
|
881
|
+
return { ok: false, path: configPath, detail: `cannot write ${configPath}: ${err?.message ?? err}` };
|
|
882
|
+
}
|
|
883
|
+
wrote = true;
|
|
884
|
+
}
|
|
885
|
+
const back = loadOauthMcpBlock(configPath, readFile);
|
|
886
|
+
if (!back.ok) {
|
|
887
|
+
return {
|
|
888
|
+
ok: false,
|
|
889
|
+
path: configPath,
|
|
890
|
+
detail: `${wrote ? `wrote ${configPath} but ` : ""}could not read it back: ${back.detail}`,
|
|
891
|
+
};
|
|
892
|
+
}
|
|
893
|
+
const readBack = back.mcp.clientIdMetadataDocuments?.allowedHosts;
|
|
894
|
+
if (!sameHostList(readBack, list)) {
|
|
895
|
+
return {
|
|
896
|
+
ok: false,
|
|
897
|
+
path: configPath,
|
|
898
|
+
detail: `${configPath} reads back ${CIMD_ALLOWED_HOSTS_CONFIG_KEY}: ${JSON.stringify(readBack ?? null)}, not ${JSON.stringify(list)}`,
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
return {
|
|
902
|
+
ok: true,
|
|
903
|
+
path: configPath,
|
|
904
|
+
readBack: [...readBack],
|
|
905
|
+
detail: `${CIMD_ALLOWED_HOSTS_CONFIG_KEY} in ${configPath} reads back as ${JSON.stringify(readBack)} (${how})`,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
function safeYamlLoad(text) {
|
|
909
|
+
try {
|
|
910
|
+
return yaml.load(text);
|
|
911
|
+
}
|
|
912
|
+
catch {
|
|
913
|
+
return undefined;
|
|
914
|
+
}
|
|
915
|
+
}
|
|
450
916
|
/** The exact callback URL to hand the operator when they create the IdP
|
|
451
917
|
* OAuth app ("with the exact GitHub callback URL printed"). */
|
|
452
918
|
export function idpCallbackUrl(issuer, idpProvider) {
|
|
453
919
|
return `${issuer.replace(/\/+$/, "")}/oauth/${idpProvider}/callback`;
|
|
454
920
|
}
|
|
921
|
+
export class IdpRedirectOriginError extends Error {
|
|
922
|
+
constructor(envPrefix) {
|
|
923
|
+
super(`Cannot stage ${envPrefix}_CLIENT_ID and ${envPrefix}_CLIENT_SECRET: ${envPrefix}_REDIRECT_URI requires a known HTTP(S) issuer origin.`);
|
|
924
|
+
this.name = "IdpRedirectOriginError";
|
|
925
|
+
}
|
|
926
|
+
}
|
|
455
927
|
/** The full set of env vars the restarted instance needs live. Contains
|
|
456
928
|
* secret VALUES — this is the one place they exist as a JS object; callers
|
|
457
929
|
* must never fold this into a CLI-printed / `EnableMcpResult` field. */
|
|
458
930
|
export function buildSecretsBundle(params) {
|
|
459
931
|
const envPrefix = `OAUTH_${params.idpProvider.toUpperCase()}`;
|
|
932
|
+
let origin;
|
|
933
|
+
try {
|
|
934
|
+
const url = new URL(params.issuer);
|
|
935
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
936
|
+
throw new IdpRedirectOriginError(envPrefix);
|
|
937
|
+
origin = url.origin;
|
|
938
|
+
}
|
|
939
|
+
catch {
|
|
940
|
+
throw new IdpRedirectOriginError(envPrefix);
|
|
941
|
+
}
|
|
460
942
|
return {
|
|
461
943
|
// "true" is the ONLY value both readers of this flag accept (flair#1152,
|
|
462
944
|
// measured against oauth 2.5.0): flair's strict mcpOAuthEnabled() takes
|
|
@@ -467,12 +949,12 @@ export function buildSecretsBundle(params) {
|
|
|
467
949
|
// 401s, no AS is advertised). Keep this "true".
|
|
468
950
|
FLAIR_MCP_OAUTH: "true",
|
|
469
951
|
FLAIR_MCP_ISSUER: params.issuer.replace(/\/+$/, ""),
|
|
470
|
-
FLAIR_MCP_SIGNING_KEY_PEM: params.signingKeyPem,
|
|
471
952
|
[`${envPrefix}_CLIENT_ID`]: params.idpClientId,
|
|
472
953
|
[`${envPrefix}_CLIENT_SECRET`]: params.idpClientSecret,
|
|
954
|
+
[`${envPrefix}_REDIRECT_URI`]: `${origin}/oauth`,
|
|
473
955
|
};
|
|
474
956
|
}
|
|
475
|
-
|
|
957
|
+
function stagingFilePath(prefix, issuer) {
|
|
476
958
|
let host = "instance";
|
|
477
959
|
try {
|
|
478
960
|
host = new URL(issuer).hostname;
|
|
@@ -481,28 +963,45 @@ export function defaultSecretsStagingPath(issuer) {
|
|
|
481
963
|
/* fall through to the generic name */
|
|
482
964
|
}
|
|
483
965
|
const safe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
|
|
484
|
-
return join(resolveHome(), ".flair",
|
|
966
|
+
return join(resolveHome(), ".flair", `${prefix}-${safe}.env`);
|
|
967
|
+
}
|
|
968
|
+
export function defaultSecretsStagingPath(issuer) {
|
|
969
|
+
return stagingFilePath("mcp-enable-secrets", issuer);
|
|
970
|
+
}
|
|
971
|
+
/** The staging file `--refresh-flag` uses when the caller names none.
|
|
972
|
+
*
|
|
973
|
+
* DELIBERATELY a different filename from `defaultSecretsStagingPath`'s. The two
|
|
974
|
+
* commands stage different bundles — `enable` the full IdP credentials bundle,
|
|
975
|
+
* refresh the single `FLAIR_MCP_OAUTH` variable — and while they shared a path a
|
|
976
|
+
* refresh could truncate a credentials bundle a previous `mcp enable` had staged
|
|
977
|
+
* and not yet applied (flair#2283). */
|
|
978
|
+
export function defaultRefreshSecretsStagingPath(issuer) {
|
|
979
|
+
return stagingFilePath("mcp-refresh-secrets", issuer);
|
|
485
980
|
}
|
|
486
981
|
/** Write the secrets bundle to a 0600 staging file, `KEY=VALUE` per line.
|
|
487
982
|
* This file legitimately carries secret material (like `grant`'s 0600 key
|
|
488
983
|
* files) — the "never print secret values" rule is about stdout/returned
|
|
489
|
-
* result objects, not this deliberately-created, permission-locked file.
|
|
490
|
-
|
|
984
|
+
* result objects, not this deliberately-created, permission-locked file.
|
|
985
|
+
*
|
|
986
|
+
* `exclusive` opens with `O_CREAT|O_EXCL` (flag `wx`): the write FAILS rather
|
|
987
|
+
* than truncate a file that is already there. The refresh fallback uses it so a
|
|
988
|
+
* pre-existing file at the target path — including the full IdP credentials
|
|
989
|
+
* bundle an operator may have staged there — can never be erased (flair#2283). */
|
|
990
|
+
export function writeSecretsStagingFile(path, bundle, opts = {}) {
|
|
491
991
|
mkdirSync(dirname(path), { recursive: true });
|
|
492
992
|
const body = Object.entries(bundle).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
|
|
493
|
-
writeFileSync(path, body, { mode: 0o600 });
|
|
993
|
+
writeFileSync(path, body, { mode: 0o600, flag: opts.exclusive ? "wx" : "w" });
|
|
494
994
|
chmodSync(path, 0o600);
|
|
495
995
|
}
|
|
496
996
|
/** Provision secrets per the shape-aware mechanism, staging the bundle to a
|
|
497
997
|
* 0600 file and returning ONLY names/paths/instructions — never values. */
|
|
498
998
|
export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
499
|
-
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism);
|
|
999
|
+
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism, opts.fabric);
|
|
500
1000
|
const path = opts.stagingPath ?? defaultSecretsStagingPath(instanceUrl);
|
|
501
1001
|
writeSecretsStagingFile(path, bundle);
|
|
502
1002
|
const varNames = Object.keys(bundle);
|
|
503
1003
|
const instructions = mechanism === "fabric-env-secrets"
|
|
504
|
-
? `
|
|
505
|
-
`Apply the ${varNames.length} vars staged at ${path} via Fabric Studio → Cluster Settings → Environment, then re-run with --confirm-secrets-applied.`
|
|
1004
|
+
? `Apply the ${varNames.length} vars staged at ${path} via Fabric Studio → Cluster Settings → Environment, then re-run with --confirm-secrets-applied.`
|
|
506
1005
|
: `Apply the ${varNames.length} vars staged at ${path} to the target instance's process environment (systemd/launchd unit, or your process manager), then re-run with --confirm-secrets-applied.`;
|
|
507
1006
|
return { mechanism, path, varNames, instructions };
|
|
508
1007
|
}
|
|
@@ -529,40 +1028,124 @@ export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
|
529
1028
|
* one rather than being handed a 404 about something else.
|
|
530
1029
|
*/
|
|
531
1030
|
export const HOSTED_OPS_PORT = 9925;
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
if (typeof target === "number")
|
|
536
|
-
return `http://127.0.0.1:${target}/`;
|
|
537
|
-
// A string target is the SERVED origin. Its own port serves the REST surface,
|
|
538
|
-
// not the ops API, so reuse the host and apply the hosted ops port.
|
|
1031
|
+
/** The served origin's host at HOSTED_OPS_PORT, or null when the origin does
|
|
1032
|
+
* not parse. A bare host name is read as https. */
|
|
1033
|
+
function hostedOpsUrl(servedOrigin) {
|
|
539
1034
|
try {
|
|
540
|
-
const u = new URL(
|
|
1035
|
+
const u = new URL(servedOrigin.includes("://") ? servedOrigin : `https://${servedOrigin}`);
|
|
541
1036
|
u.port = String(HOSTED_OPS_PORT);
|
|
542
1037
|
u.pathname = "/";
|
|
543
1038
|
u.search = "";
|
|
544
|
-
return u
|
|
1039
|
+
return u;
|
|
545
1040
|
}
|
|
546
1041
|
catch {
|
|
547
|
-
|
|
548
|
-
// let the caller's error path name the remedy.
|
|
549
|
-
return `${target.replace(/\/+$/, "")}/`;
|
|
1042
|
+
return null;
|
|
550
1043
|
}
|
|
551
1044
|
}
|
|
1045
|
+
export function resolveOpsUrl(target, explicitOpsUrl) {
|
|
1046
|
+
if (explicitOpsUrl)
|
|
1047
|
+
return `${explicitOpsUrl.replace(/\/+$/, "")}/`;
|
|
1048
|
+
if (typeof target === "number")
|
|
1049
|
+
return `http://127.0.0.1:${target}/`;
|
|
1050
|
+
// A string target is the SERVED origin. Its own port serves the REST surface,
|
|
1051
|
+
// not the ops API, so reuse the host and apply the hosted ops port.
|
|
1052
|
+
// Unparseable — preserve the old behaviour rather than inventing a URL, and
|
|
1053
|
+
// let the caller's error path name the remedy.
|
|
1054
|
+
return hostedOpsUrl(target)?.toString() ?? `${target.replace(/\/+$/, "")}/`;
|
|
1055
|
+
}
|
|
552
1056
|
function opsBaseUrl(opsPortOrUrl) {
|
|
553
1057
|
return resolveOpsUrl(opsPortOrUrl);
|
|
554
1058
|
}
|
|
555
1059
|
function basicAuthHeader(adminUser, adminPass) {
|
|
556
1060
|
return `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
|
|
557
1061
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
1062
|
+
const IDENTITY_MAPPING_TARGET_FORMS = `Accepted, exactly one of: opsPortOrUrl as a port number (1-65535) on 127.0.0.1, or as the ops API's own ` +
|
|
1063
|
+
`canonical http:// or https:// origin, optionally followed by /, with no credentials, non-root path, query or fragment, used with its own host and port; or ` +
|
|
1064
|
+
`hostedOrigin as the same canonical http:// or https:// origin form, whose host is used at port ${HOSTED_OPS_PORT}. ` +
|
|
1065
|
+
`The string must exactly equal its parsed URL origin or that origin followed by /. No request was sent.`;
|
|
1066
|
+
/** Show only the parsed protocol, hostname and port of a refused target. The
|
|
1067
|
+
* display is built without interpolating the raw input, and excludes its
|
|
1068
|
+
* userinfo, path, query and fragment. Parsed components can match input text.
|
|
1069
|
+
* Use the placeholder for a non-string, a parse error or an empty hostname. */
|
|
1070
|
+
function showOpsTarget(value) {
|
|
1071
|
+
if (typeof value !== "string")
|
|
1072
|
+
return "<unparseable value>";
|
|
1073
|
+
try {
|
|
1074
|
+
const u = new URL(value);
|
|
1075
|
+
if (!u.hostname)
|
|
1076
|
+
return "<unparseable value>";
|
|
1077
|
+
return `${u.protocol}//${u.hostname}${u.port ? `:${u.port}` : ""}`;
|
|
1078
|
+
}
|
|
1079
|
+
catch {
|
|
1080
|
+
return "<unparseable value>";
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
/** A URL string is accepted only when parsing leaves its origin spelling
|
|
1084
|
+
* unchanged (apart from an optional `/`). This also rejects empty ? and #. */
|
|
1085
|
+
function canonicalHttpOrigin(value) {
|
|
1086
|
+
if (typeof value !== "string")
|
|
1087
|
+
return null;
|
|
1088
|
+
try {
|
|
1089
|
+
const u = new URL(value);
|
|
1090
|
+
if ((u.protocol === "http:" || u.protocol === "https:") &&
|
|
1091
|
+
!u.username && !u.password &&
|
|
1092
|
+
(value === u.origin || value === `${u.origin}/`))
|
|
1093
|
+
return u;
|
|
1094
|
+
}
|
|
1095
|
+
catch {
|
|
1096
|
+
// A malformed URL is not an ops target.
|
|
1097
|
+
}
|
|
1098
|
+
return null;
|
|
1099
|
+
}
|
|
1100
|
+
export function targetOriginRefusal(instance) {
|
|
1101
|
+
if (canonicalHttpOrigin(instance))
|
|
1102
|
+
return;
|
|
1103
|
+
const origin = showOpsTarget(instance);
|
|
1104
|
+
return "Target must be a canonical http:// or https:// origin, optionally followed by /." +
|
|
1105
|
+
(canonicalHttpOrigin(origin) ? ` Use ${origin}.` : "");
|
|
1106
|
+
}
|
|
1107
|
+
/** Resolve the ops target, or throw naming the field, its safe display and the
|
|
1108
|
+
* accepted forms. One implementation, so every identity-mapping command sends
|
|
1109
|
+
* its ops calls to the same address (flair#2115). */
|
|
1110
|
+
function identityMappingOpsUrl(target) {
|
|
1111
|
+
const { opsPortOrUrl, hostedOrigin } = target;
|
|
1112
|
+
const refuse = (what) => {
|
|
1113
|
+
throw new Error(`Identity mapping: ${what}. ${IDENTITY_MAPPING_TARGET_FORMS}`);
|
|
1114
|
+
};
|
|
1115
|
+
if (opsPortOrUrl !== undefined && hostedOrigin !== undefined) {
|
|
1116
|
+
return refuse(`got both opsPortOrUrl ${showOpsTarget(opsPortOrUrl)} and hostedOrigin ${showOpsTarget(hostedOrigin)}`);
|
|
1117
|
+
}
|
|
1118
|
+
if (hostedOrigin !== undefined) {
|
|
1119
|
+
const u = canonicalHttpOrigin(hostedOrigin);
|
|
1120
|
+
if (!u) {
|
|
1121
|
+
return refuse(`cannot read hostedOrigin ${showOpsTarget(hostedOrigin)} as a served origin`);
|
|
1122
|
+
}
|
|
1123
|
+
return { url: resolveOpsUrl(u.origin), hosted: true };
|
|
1124
|
+
}
|
|
1125
|
+
if (opsPortOrUrl === undefined)
|
|
1126
|
+
return refuse("got neither opsPortOrUrl nor hostedOrigin");
|
|
1127
|
+
if (typeof opsPortOrUrl === "number" && Number.isInteger(opsPortOrUrl) && opsPortOrUrl >= 1 && opsPortOrUrl <= 65535) {
|
|
1128
|
+
return { url: resolveOpsUrl(opsPortOrUrl), hosted: false };
|
|
1129
|
+
}
|
|
1130
|
+
if (typeof opsPortOrUrl === "string") {
|
|
1131
|
+
const u = canonicalHttpOrigin(opsPortOrUrl);
|
|
1132
|
+
if (u) {
|
|
1133
|
+
return { url: `${u.origin}/`, hosted: false };
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
return refuse(`cannot tell which ops API opsPortOrUrl ${showOpsTarget(opsPortOrUrl)} names`);
|
|
565
1137
|
}
|
|
1138
|
+
/** The linking layer's Credential tests are the SAME ones the resolver applies
|
|
1139
|
+
* (src/lib/credential-status-rule.ts, imported above): a row maps a principal
|
|
1140
|
+
* only when its `status` is exactly "active" and it names a principal
|
|
1141
|
+
* (`credentialMapsPrincipal`), and a row that names no principal
|
|
1142
|
+
* (`credentialPrincipalId` is null) is skipped on read. The resolver refuses a
|
|
1143
|
+
* subject when at least one row matches it but none maps a principal (with no
|
|
1144
|
+
* matching row at all it may JIT-provision), and resolves the subject through
|
|
1145
|
+
* the active, principal-bearing row this layer writes, even when a
|
|
1146
|
+
* principal-less row remains beside it. The linking layer MUST use the same
|
|
1147
|
+
* tests — a credential the linker considers inactive but the resolver would
|
|
1148
|
+
* still serve is exactly the invisible-duplicate hole #1317 is about. */
|
|
566
1149
|
/**
|
|
567
1150
|
* Map the operator's IdP subject to their principal via `Credential(kind:
|
|
568
1151
|
* "idp")` — the SAME credential surface resources/mcp-handler.ts's
|
|
@@ -570,9 +1153,14 @@ function isResolvableCredential(cred) {
|
|
|
570
1153
|
*
|
|
571
1154
|
* ## The uniqueness constraint (flair#1317, K&S ruling 2026-08-21)
|
|
572
1155
|
*
|
|
573
|
-
* **
|
|
574
|
-
*
|
|
575
|
-
*
|
|
1156
|
+
* **The ruling: at most one ACTIVE, principal-bearing `Credential(kind:"idp",
|
|
1157
|
+
* idpSubject:<sub>)`, regardless of `idpProvider`.** This function's
|
|
1158
|
+
* post-write read verifies one such row at the time of that read, on every
|
|
1159
|
+
* write it makes (`flair mcp enable`, `flair principal link`); it does not
|
|
1160
|
+
* hold the invariant for other writers. The MCP and XAA JIT provisioners also write a
|
|
1161
|
+
* mapping, when their own lookup finds no matching row, and do not run this
|
|
1162
|
+
* check. A principal-less row maps nothing and is skipped, so it may remain
|
|
1163
|
+
* active beside the mapping.
|
|
576
1164
|
*
|
|
577
1165
|
* It used to dedup on `(kind, idpProvider, idpSubject)` while the resolver read
|
|
578
1166
|
* `(kind, idpSubject)`. A re-link under a different provider name therefore
|
|
@@ -585,17 +1173,20 @@ function isResolvableCredential(cred) {
|
|
|
585
1173
|
* stays on the row as audit/diagnostic metadata, but it does not participate in
|
|
586
1174
|
* uniqueness. So:
|
|
587
1175
|
*
|
|
588
|
-
* - same provider, existing active credential → RE-POINT
|
|
589
|
-
*
|
|
590
|
-
*
|
|
1176
|
+
* - same provider, existing active, principal-bearing credential → RE-POINT
|
|
1177
|
+
* it (`credentialReused`);
|
|
1178
|
+
* - any OTHER active, principal-bearing credential for the subject →
|
|
1179
|
+
* SUPERSEDE it: terminal `status: "revoked"`, never a soft flag a later
|
|
1180
|
+
* path could flip back
|
|
591
1181
|
* (revoked rows are never reused here — a re-link after a revoke mints a
|
|
592
1182
|
* fresh credential);
|
|
593
1183
|
* - the re-point/insert and every revocation go out as ONE ops-API `upsert`
|
|
594
|
-
* batch, so there is no observable window with two active
|
|
595
|
-
* zero. If the batch fails, nothing is
|
|
1184
|
+
* batch, so there is no observable window with two active,
|
|
1185
|
+
* principal-bearing credentials or zero. If the batch fails, nothing is
|
|
1186
|
+
* claimed and the call throws;
|
|
596
1187
|
* - after the write the invariant is RE-READ and asserted. A store that
|
|
597
|
-
* somehow holds ≠1 active credential for the subject is a
|
|
598
|
-
* silent nondeterministic mapping.
|
|
1188
|
+
* somehow holds ≠1 active, principal-bearing credential for the subject is a
|
|
1189
|
+
* hard error, not a silent nondeterministic mapping.
|
|
599
1190
|
*
|
|
600
1191
|
* The principal Agent is created only if missing.
|
|
601
1192
|
*
|
|
@@ -608,22 +1199,24 @@ function isResolvableCredential(cred) {
|
|
|
608
1199
|
* so the operator is told, not so the event is hidden.
|
|
609
1200
|
*/
|
|
610
1201
|
export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
1202
|
+
const target = identityMappingOpsUrl(params);
|
|
1203
|
+
const opsUrl = target.url;
|
|
611
1204
|
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
612
|
-
const
|
|
613
|
-
const
|
|
1205
|
+
const clock = deps.now ?? (() => new Date().toISOString());
|
|
1206
|
+
const now = clock();
|
|
614
1207
|
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1208
|
+
// flair#2359 — the ONE shared agent-ID rule, before any read or write. The
|
|
1209
|
+
// principal Agent below is inserted through the operations API, so the Agent
|
|
1210
|
+
// resource's own guard never runs on it.
|
|
1211
|
+
if (!isValidAgentId(params.principal)) {
|
|
1212
|
+
throw new Error(`Identity mapping: ${invalidAgentIdMessage(params.principal)}`);
|
|
1213
|
+
}
|
|
615
1214
|
// Ensure the principal Agent exists.
|
|
1215
|
+
const agentQuery = mappingReadQuery("Agent", { id: params.principal });
|
|
616
1216
|
const findRes = await fetchImpl(opsUrl, {
|
|
617
1217
|
method: "POST",
|
|
618
|
-
headers:
|
|
619
|
-
body: JSON.stringify(
|
|
620
|
-
operation: "search_by_value",
|
|
621
|
-
database: "flair",
|
|
622
|
-
table: "Agent",
|
|
623
|
-
search_attribute: "id",
|
|
624
|
-
search_value: params.principal,
|
|
625
|
-
get_attributes: ["id"],
|
|
626
|
-
}),
|
|
1218
|
+
headers: opsHeaders(authHeader),
|
|
1219
|
+
body: JSON.stringify(agentQuery),
|
|
627
1220
|
});
|
|
628
1221
|
if (!findRes.ok) {
|
|
629
1222
|
const text = await findRes.text().catch(() => "");
|
|
@@ -633,17 +1226,34 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
633
1226
|
// identity is absent — and saying "failed to look up principal 'x'" sends
|
|
634
1227
|
// the reader to look at principals, which is where an evening goes.
|
|
635
1228
|
//
|
|
636
|
-
//
|
|
637
|
-
//
|
|
638
|
-
//
|
|
1229
|
+
// For `hostedOrigin`, retain the served-origin diagnosis and explain that
|
|
1230
|
+
// `enable` derived the address: it has no option to point its ops calls
|
|
1231
|
+
// elsewhere (flair#2116). A 404 at a caller-named opsPortOrUrl does not
|
|
1232
|
+
// establish which service answered, so give that path a neutral hint.
|
|
639
1233
|
const hint = findRes.status === 404
|
|
640
|
-
?
|
|
1234
|
+
? target.hosted
|
|
1235
|
+
? ` — a 404 here usually means ${opsUrl} is the served origin rather than the ops API (the REST component owns "/" and answers 404). The ops API is a DIFFERENT port (conventionally ${HOSTED_OPS_PORT} on hosted instances) and is not derivable from the served port. \`flair mcp enable\` derives this address from the instance URL (--instance or FLAIR_URL: same host, port ${HOSTED_OPS_PORT}) and has no option to override it, so the target's operations API has to answer at ${opsUrl}.`
|
|
1236
|
+
: ` — opsPortOrUrl names this address; verify that the ops API answers requests at ${opsUrl}.`
|
|
641
1237
|
: "";
|
|
642
1238
|
throw new Error(`Identity mapping: the ops API call to ${opsUrl} failed (HTTP ${findRes.status})${hint}${text ? `: ${text}` : ""}`);
|
|
643
1239
|
}
|
|
644
|
-
|
|
1240
|
+
// flair#2115 — the principal is created only after a valid empty answer.
|
|
1241
|
+
const foundAgents = await opsRecordList(findRes, opsUrl, agentQuery);
|
|
1242
|
+
if (foundAgents.length === 0 && params.principalMustExist) {
|
|
1243
|
+
throw new Error(principalMissingMessage(params.principal));
|
|
1244
|
+
}
|
|
645
1245
|
let principalCreated = false;
|
|
646
|
-
|
|
1246
|
+
const findCredentialsForSubject = () => readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject);
|
|
1247
|
+
const subjectCreds = await findCredentialsForSubject();
|
|
1248
|
+
const activeCreds = subjectCreds.filter(credentialMapsPrincipal);
|
|
1249
|
+
// flair#2222 — retain Agent presence and the compared principal-bearing IdP fields.
|
|
1250
|
+
const preflight = mappingPreflight(params.principal, params.idpSubject, foundAgents.length > 0, subjectCreds);
|
|
1251
|
+
if (foundAgents.length === 0) {
|
|
1252
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight);
|
|
1253
|
+
// flair#2433 — the new principal Agent's home is THIS instance's federation
|
|
1254
|
+
// id, resolved through the one shared rule. A create stamps it; a body value
|
|
1255
|
+
// is never the source.
|
|
1256
|
+
const principalHome = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, params.adminUser, params.adminPass, fetchImpl));
|
|
647
1257
|
const insertRes = await fetchImpl(opsUrl, {
|
|
648
1258
|
method: "POST",
|
|
649
1259
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -659,8 +1269,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
659
1269
|
kind: params.principalKind,
|
|
660
1270
|
type: params.principalKind,
|
|
661
1271
|
status: "active",
|
|
1272
|
+
publicKey: `idp:${params.idpProvider}:${params.idpSubject}`,
|
|
662
1273
|
admin: false,
|
|
663
1274
|
defaultTrustTier: "endorsed",
|
|
1275
|
+
originatorInstanceId: principalHome,
|
|
664
1276
|
createdAt: now,
|
|
665
1277
|
updatedAt: now,
|
|
666
1278
|
},
|
|
@@ -672,31 +1284,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
672
1284
|
throw new Error(`Identity mapping: failed to create principal '${params.principal}' (HTTP ${insertRes.status}): ${text}`);
|
|
673
1285
|
}
|
|
674
1286
|
principalCreated = true;
|
|
1287
|
+
preflight.principalPresent = true;
|
|
675
1288
|
}
|
|
676
|
-
// ── flair#1317: look SUBJECT-WIDE, not (provider, subject) ─────────────────
|
|
677
|
-
// The resolver's key is (kind, idpSubject); anything narrower here leaves
|
|
678
|
-
// credentials that dedup cannot see but resolution can.
|
|
679
|
-
const findCredentialsForSubject = async () => {
|
|
680
|
-
const res = await fetchImpl(opsUrl, {
|
|
681
|
-
method: "POST",
|
|
682
|
-
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
683
|
-
body: JSON.stringify({
|
|
684
|
-
operation: "search_by_conditions",
|
|
685
|
-
database: "flair",
|
|
686
|
-
table: "Credential",
|
|
687
|
-
operator: "and",
|
|
688
|
-
conditions: [
|
|
689
|
-
{ search_attribute: "kind", search_type: "equals", search_value: "idp" },
|
|
690
|
-
{ search_attribute: "idpSubject", search_type: "equals", search_value: params.idpSubject },
|
|
691
|
-
],
|
|
692
|
-
get_attributes: ["id", "principalId", "idpProvider", "idpSubject", "status", "label", "createdAt"],
|
|
693
|
-
}),
|
|
694
|
-
});
|
|
695
|
-
const body = res.ok ? await res.json().catch(() => []) : [];
|
|
696
|
-
return Array.isArray(body) ? body : [];
|
|
697
|
-
};
|
|
698
|
-
const subjectCreds = await findCredentialsForSubject();
|
|
699
|
-
const activeCreds = subjectCreds.filter(isResolvableCredential);
|
|
700
1289
|
// Survivor: an ACTIVE same-provider credential is re-pointed (the idempotent
|
|
701
1290
|
// re-run and the documented same-provider link). A revoked one is never
|
|
702
1291
|
// resurrected — a re-link after a revoke mints a fresh credential.
|
|
@@ -710,6 +1299,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
710
1299
|
// ops-API operation is the strongest atomicity this surface can express, and
|
|
711
1300
|
// ordering the survivor first means even a partially-applied batch can never
|
|
712
1301
|
// leave the subject with ZERO resolvable credentials (the fail-open denial).
|
|
1302
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight, principalCreated);
|
|
1303
|
+
// The mapping's times are read immediately before sending the mapping
|
|
1304
|
+
// upsert, not at the start of the run.
|
|
1305
|
+
const writtenAt = clock();
|
|
713
1306
|
const upsertRes = await fetchImpl(opsUrl, {
|
|
714
1307
|
method: "POST",
|
|
715
1308
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -726,8 +1319,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
726
1319
|
status: "active",
|
|
727
1320
|
idpProvider: params.idpProvider,
|
|
728
1321
|
idpSubject: params.idpSubject,
|
|
729
|
-
createdAt: reused ?
|
|
730
|
-
lastUsedAt:
|
|
1322
|
+
createdAt: typeof reused?.createdAt === "string" ? reused.createdAt : writtenAt,
|
|
1323
|
+
lastUsedAt: writtenAt,
|
|
731
1324
|
},
|
|
732
1325
|
// Retained, not deleted: the revocation stays legible in storage and in
|
|
733
1326
|
// Harper's table audit log (which records the full record image of
|
|
@@ -742,8 +1335,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
742
1335
|
status: "revoked",
|
|
743
1336
|
idpProvider: c.idpProvider,
|
|
744
1337
|
idpSubject: params.idpSubject,
|
|
745
|
-
createdAt: c.createdAt,
|
|
746
|
-
updatedAt:
|
|
1338
|
+
createdAt: typeof c.createdAt === "string" ? c.createdAt : writtenAt,
|
|
1339
|
+
updatedAt: writtenAt,
|
|
747
1340
|
})),
|
|
748
1341
|
],
|
|
749
1342
|
}),
|
|
@@ -757,14 +1350,9 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
757
1350
|
// ≠1 active credential means the resolver's answer for this subject is
|
|
758
1351
|
// order-dependent, so this fails LOUDLY rather than returning a mapping the
|
|
759
1352
|
// operator would reasonably believe is deterministic.
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
throw new Error(`Identity mapping: the uniqueness invariant does not hold after the write — subject '${params.idpSubject}' ` +
|
|
764
|
-
`has ${afterCreds.length} active Credential(kind:idp) row(s) [${seen}], expected exactly 1 (${credentialId}). ` +
|
|
765
|
-
`Runtime resolution for this subject would be iteration-order-dependent (flair#1317). ` +
|
|
766
|
-
`Inspect the Credential table for kind:"idp" idpSubject:"${params.idpSubject}" and revoke the rows that should not resolve.`);
|
|
767
|
-
}
|
|
1353
|
+
await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, {
|
|
1354
|
+
id: credentialId, principalId: params.principal, idpProvider: params.idpProvider, status: "active",
|
|
1355
|
+
});
|
|
768
1356
|
return {
|
|
769
1357
|
principalCreated,
|
|
770
1358
|
credentialId,
|
|
@@ -773,6 +1361,349 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
773
1361
|
supersededCredentialIds: superseded.map((c) => String(c.id)),
|
|
774
1362
|
};
|
|
775
1363
|
}
|
|
1364
|
+
/** The admin Basic header every ops call on this surface carries. */
|
|
1365
|
+
function opsHeaders(authHeader) {
|
|
1366
|
+
return { "Content-Type": "application/json", Authorization: authHeader };
|
|
1367
|
+
}
|
|
1368
|
+
function mappingReadQuery(table, equals) {
|
|
1369
|
+
const fields = table === "Agent" ? ["id"] :
|
|
1370
|
+
["id", "kind", "principalId", "idpProvider", "idpSubject", "status", "label", "createdAt"];
|
|
1371
|
+
if (table === "Agent") {
|
|
1372
|
+
return { operation: "search_by_value", database: "flair", table,
|
|
1373
|
+
search_attribute: "id", search_value: equals.id, get_attributes: fields };
|
|
1374
|
+
}
|
|
1375
|
+
return { operation: "search_by_conditions", database: "flair", table, operator: "and",
|
|
1376
|
+
conditions: Object.entries(equals).map(([search_attribute, search_value]) => ({ search_attribute, search_type: "equals", search_value })), get_attributes: fields };
|
|
1377
|
+
}
|
|
1378
|
+
async function opsReadRows(fetchImpl, opsUrl, authHeader, query, written, refuseAmbiguous = false) {
|
|
1379
|
+
const res = await fetchImpl(opsUrl, { method: "POST", headers: opsHeaders(authHeader), body: JSON.stringify(query) });
|
|
1380
|
+
if (!res.ok) {
|
|
1381
|
+
const text = await res.text().catch(() => "");
|
|
1382
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} failed (HTTP ${res.status})${text ? `: ${text}` : ""}`);
|
|
1383
|
+
}
|
|
1384
|
+
return opsRecordList(res, opsUrl, query, written, refuseAmbiguous);
|
|
1385
|
+
}
|
|
1386
|
+
async function opsRecordList(res, opsUrl, query, written, refuseAmbiguous = false) {
|
|
1387
|
+
const parsed = await res.json().catch(() => null);
|
|
1388
|
+
if (!Array.isArray(parsed)) {
|
|
1389
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} did not answer with a record list; ` +
|
|
1390
|
+
`verify that the target answers operations API requests there.`);
|
|
1391
|
+
}
|
|
1392
|
+
const predicate = query.operation === "search_by_value"
|
|
1393
|
+
? [[query.search_attribute, query.search_value]]
|
|
1394
|
+
: query.conditions.map(c => [c.search_attribute, c.search_value]);
|
|
1395
|
+
const ids = new Set();
|
|
1396
|
+
const rows = [];
|
|
1397
|
+
for (const [index, row] of parsed.entries()) {
|
|
1398
|
+
const refuse = (reason) => {
|
|
1399
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} answered with a malformed ${query.table} record (entry ${index}): ${reason}.`);
|
|
1400
|
+
};
|
|
1401
|
+
if (row === null || typeof row !== "object" || Array.isArray(row))
|
|
1402
|
+
refuse("invalid-row-shape");
|
|
1403
|
+
if (!isNonEmptyString(row.id))
|
|
1404
|
+
refuse("missing-or-invalid-id");
|
|
1405
|
+
for (const [field, value] of predicate) {
|
|
1406
|
+
if (!query.get_attributes.includes(field))
|
|
1407
|
+
refuse(`predicate-attribute-not-requested:${field}`);
|
|
1408
|
+
if (!Object.hasOwn(row, field) || row[field] !== value)
|
|
1409
|
+
refuse(`query-mismatch:${field}`);
|
|
1410
|
+
}
|
|
1411
|
+
if (ids.has(row.id))
|
|
1412
|
+
refuse("duplicate-row-id");
|
|
1413
|
+
ids.add(row.id);
|
|
1414
|
+
if (query.table === "Credential" && credentialPrincipalId(row) === null)
|
|
1415
|
+
continue;
|
|
1416
|
+
if (query.table === "Credential" &&
|
|
1417
|
+
(typeof row.idpProvider !== "string" ||
|
|
1418
|
+
typeof row.idpSubject !== "string" ||
|
|
1419
|
+
(row.label != null && typeof row.label !== "string") ||
|
|
1420
|
+
(row.status != null && typeof row.status !== "string"))) {
|
|
1421
|
+
refuse("missing-or-invalid-credential-field");
|
|
1422
|
+
}
|
|
1423
|
+
rows.push(row);
|
|
1424
|
+
}
|
|
1425
|
+
if (refuseAmbiguous && query.table === "Credential" && predicate.some(([field]) => field === "idpSubject")) {
|
|
1426
|
+
const principals = [...new Set(rows.filter(credentialMapsPrincipal).map(row => row.principalId))];
|
|
1427
|
+
if (principals.length > 1) {
|
|
1428
|
+
throw new Error(`Identity mapping: ambiguous-prior-principals: ${principals.join(", ")} — refusing the subject read. Run flair mcp enable to heal this subject mapping.`);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
if (written) {
|
|
1432
|
+
const active = rows.filter(credentialMapsPrincipal);
|
|
1433
|
+
if (active.length !== 1 || Object.entries(written).some(([field, value]) => active[0][field] !== value)) {
|
|
1434
|
+
const subject = predicate.find(([field]) => field === "idpSubject")?.[1];
|
|
1435
|
+
const seen = active.map(c => `${c.id} → ${c.principalId} (provider '${c.idpProvider}')`).join("; ") || "none";
|
|
1436
|
+
throw new Error(`Identity mapping: post-write-mismatch — the uniqueness invariant does not hold after the write (flair#1317) — subject '${subject}' ` +
|
|
1437
|
+
`has ${active.length} resolvable (principal-bearing) active Credential(kind:idp) row(s) [${seen}], expected exactly 1 (${written.id}) ` +
|
|
1438
|
+
`for principal '${written.principalId}', provider '${written.idpProvider}', status 'active'. ` +
|
|
1439
|
+
`Principal-less legacy rows are skipped and may remain active. ` +
|
|
1440
|
+
`Inspect the Credential table for kind:"idp" idpSubject:"${subject}" and revoke the rows that should not resolve.`);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return rows;
|
|
1444
|
+
}
|
|
1445
|
+
function isNonEmptyString(value) {
|
|
1446
|
+
return typeof value === "string" && value !== "";
|
|
1447
|
+
}
|
|
1448
|
+
async function readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, idpSubject, written, refuseAmbiguous = false) {
|
|
1449
|
+
return opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Credential", { kind: "idp", idpSubject }), written, refuseAmbiguous);
|
|
1450
|
+
}
|
|
1451
|
+
async function readIdpCredentialsForPrincipal(fetchImpl, opsUrl, authHeader, principal) {
|
|
1452
|
+
return opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Credential", { kind: "idp", principalId: principal }));
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Refuse unless the principal exists, by name.
|
|
1456
|
+
*
|
|
1457
|
+
* A read that FAILED propagates: an unreadable Agent table is not an absent
|
|
1458
|
+
* principal, and this check stands in front of a mapping write (flair#2115).
|
|
1459
|
+
* The id is compared, not just the non-emptiness of the answer.
|
|
1460
|
+
*/
|
|
1461
|
+
async function assertPrincipalExists(fetchImpl, opsUrl, authHeader, principal) {
|
|
1462
|
+
const rows = await opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Agent", { id: principal }));
|
|
1463
|
+
if (rows.length === 0)
|
|
1464
|
+
throw new Error(principalMissingMessage(principal));
|
|
1465
|
+
}
|
|
1466
|
+
/** The one refusal a missing principal gets, wherever it is checked. */
|
|
1467
|
+
function principalMissingMessage(principal) {
|
|
1468
|
+
return (`No principal '${principal}' — nothing was written. Create the principal on the TARGET instance ` +
|
|
1469
|
+
`(run \`flair mcp enable\` against it: it creates the principal it maps), then re-run.`);
|
|
1470
|
+
}
|
|
1471
|
+
/** Canonicalize id, kind, principalId, idpProvider, idpSubject, status, label and createdAt. */
|
|
1472
|
+
function canonicalSubjectRows(rows) {
|
|
1473
|
+
return JSON.stringify(rows
|
|
1474
|
+
.map((r) => ({
|
|
1475
|
+
id: String(r?.id),
|
|
1476
|
+
kind: r?.kind ?? null,
|
|
1477
|
+
principalId: r?.principalId ?? null,
|
|
1478
|
+
idpProvider: r?.idpProvider ?? null,
|
|
1479
|
+
idpSubject: r?.idpSubject ?? null,
|
|
1480
|
+
status: r?.status ?? null,
|
|
1481
|
+
label: r?.label ?? null,
|
|
1482
|
+
createdAt: r?.createdAt ?? null,
|
|
1483
|
+
}))
|
|
1484
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
|
|
1485
|
+
}
|
|
1486
|
+
function mappingPreflight(principal, idpSubject, principalPresent, subjectRows) {
|
|
1487
|
+
return { principal, idpSubject, principalPresent, subjectRows: canonicalSubjectRows(subjectRows) };
|
|
1488
|
+
}
|
|
1489
|
+
/** Valid comparison differences refuse here; invalid changed rows can fail earlier validation
|
|
1490
|
+
* with missing-or-invalid-credential-field. Both fail closed. */
|
|
1491
|
+
function mappingChangedMessage(principal, idpSubject, principalCreated = false) {
|
|
1492
|
+
return (`Identity mapping: mapping-changed-underneath — the Agent presence or compared IdP mapping fields for principal '${principal}' ` +
|
|
1493
|
+
`and IdP subject '${idpSubject}' changed on the target between this command's validation and its write. ` +
|
|
1494
|
+
(principalCreated ? `Agent '${principal}' was created; no rollback was attempted. No Credential write was made. ` : `Nothing was written. `) +
|
|
1495
|
+
`Re-run the command.`);
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Re-read the state a preflight validated and refuse if it moved.
|
|
1499
|
+
*
|
|
1500
|
+
* A failed read propagates: an unreadable table is not an unchanged one, and
|
|
1501
|
+
* this stands in front of a write. Called immediately before each write in
|
|
1502
|
+
* `provisionIdpIdentityMapping`, `linkPrincipalMapping` and
|
|
1503
|
+
* `unlinkPrincipalMapping`.
|
|
1504
|
+
*/
|
|
1505
|
+
async function assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight, principalCreated = false) {
|
|
1506
|
+
const agents = await opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Agent", { id: preflight.principal }));
|
|
1507
|
+
if ((agents.length > 0) !== preflight.principalPresent) {
|
|
1508
|
+
throw new Error(mappingChangedMessage(preflight.principal, preflight.idpSubject, principalCreated));
|
|
1509
|
+
}
|
|
1510
|
+
const rows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, preflight.idpSubject);
|
|
1511
|
+
if (canonicalSubjectRows(rows) !== preflight.subjectRows) {
|
|
1512
|
+
throw new Error(mappingChangedMessage(preflight.principal, preflight.idpSubject, principalCreated));
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* flair#2115 — `flair principal link|unlink|links` carry the target instance's
|
|
1517
|
+
* admin credential to its operations API, so the target they accept is narrower
|
|
1518
|
+
* than `checkLocalOriginRefusal`'s claude.ai-oriented one: a `hostedOrigin`
|
|
1519
|
+
* that `checkMappingTargetRefusal` refuses is refused. The numeric
|
|
1520
|
+
* `opsPortOrUrl` form names the caller's own address and is left alone.
|
|
1521
|
+
*
|
|
1522
|
+
* Called before the first request, so a refused target never sees one.
|
|
1523
|
+
*/
|
|
1524
|
+
function assertMappingTarget(target) {
|
|
1525
|
+
const { hostedOrigin } = target;
|
|
1526
|
+
if (hostedOrigin === undefined)
|
|
1527
|
+
return;
|
|
1528
|
+
const check = checkMappingTargetRefusal(String(hostedOrigin));
|
|
1529
|
+
if (check.refused)
|
|
1530
|
+
throw new Error(check.message);
|
|
1531
|
+
}
|
|
1532
|
+
/** The exactly-one target fields, rebuilt so they can be spread into a fresh
|
|
1533
|
+
* literal (a union value cannot be spread into one). */
|
|
1534
|
+
function mappingTargetFields(target) {
|
|
1535
|
+
const t = target;
|
|
1536
|
+
return t.hostedOrigin !== undefined
|
|
1537
|
+
? { hostedOrigin: String(t.hostedOrigin) }
|
|
1538
|
+
: { opsPortOrUrl: t.opsPortOrUrl };
|
|
1539
|
+
}
|
|
1540
|
+
/**
|
|
1541
|
+
* `flair principal link` — map one IdP subject to a principal that already
|
|
1542
|
+
* exists, through `provisionIdpIdentityMapping` (the `mcp enable` step).
|
|
1543
|
+
*
|
|
1544
|
+
* - the subject already mapped to THIS principal (no active row names another):
|
|
1545
|
+
* reported, exit 0, NO write;
|
|
1546
|
+
* - the subject mapped to a DIFFERENT principal: refused by name unless
|
|
1547
|
+
* `replace` is set; with `replace`, the write re-points it and the result
|
|
1548
|
+
* names the principal it left;
|
|
1549
|
+
* - a missing principal is refused by name with nothing written;
|
|
1550
|
+
* - a failed read is refused: it never counts as "no mapping";
|
|
1551
|
+
* - a target `checkMappingTargetRefusal` refuses is refused before any request.
|
|
1552
|
+
*/
|
|
1553
|
+
export async function linkPrincipalMapping(params, deps = {}) {
|
|
1554
|
+
assertMappingTarget(params);
|
|
1555
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1556
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1557
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1558
|
+
// Refuse a missing requested principal before either mapping branch.
|
|
1559
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1560
|
+
const subjectRows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, undefined, true);
|
|
1561
|
+
const active = subjectRows.filter(credentialMapsPrincipal);
|
|
1562
|
+
const elsewhere = active.filter((c) => c?.principalId !== params.principal);
|
|
1563
|
+
if (elsewhere.length > 0 && !params.replace) {
|
|
1564
|
+
const current = [...new Set(elsewhere.map((c) => String(c?.principalId)))].join(", ");
|
|
1565
|
+
throw new Error(`IdP subject '${params.idpSubject}' is already mapped to principal '${current}', not '${params.principal}' — ` +
|
|
1566
|
+
`nothing was written. Pass --replace to move it.`);
|
|
1567
|
+
}
|
|
1568
|
+
if (active.length > 0 && elsewhere.length === 0) {
|
|
1569
|
+
const provider = String(active[0]?.idpProvider ?? params.idpProvider);
|
|
1570
|
+
return {
|
|
1571
|
+
action: "already-linked",
|
|
1572
|
+
principal: params.principal,
|
|
1573
|
+
idpProvider: provider,
|
|
1574
|
+
idpSubject: params.idpSubject,
|
|
1575
|
+
supersededCredentialIds: [],
|
|
1576
|
+
lines: [
|
|
1577
|
+
`Already linked: IdP subject '${params.idpSubject}' (provider '${provider}') → principal '${params.principal}'. No change.`,
|
|
1578
|
+
],
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
const previousPrincipal = elsewhere.length > 0 ? String(elsewhere[0]?.principalId) : undefined;
|
|
1582
|
+
// flair#2222 — the write is the shared provisioner's; re-validate the state
|
|
1583
|
+
// this preflight acted on so a concurrent change refuses here, not after the
|
|
1584
|
+
// provisioner has already re-read and moved on.
|
|
1585
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, mappingPreflight(params.principal, params.idpSubject, true, subjectRows));
|
|
1586
|
+
const mapping = await provisionIdpIdentityMapping({
|
|
1587
|
+
...mappingTargetFields(params),
|
|
1588
|
+
adminUser: params.adminUser,
|
|
1589
|
+
adminPass: params.adminPass,
|
|
1590
|
+
principal: params.principal,
|
|
1591
|
+
principalKind: "human",
|
|
1592
|
+
idpProvider: params.idpProvider,
|
|
1593
|
+
idpSubject: params.idpSubject,
|
|
1594
|
+
principalMustExist: true,
|
|
1595
|
+
}, deps);
|
|
1596
|
+
const outcome = mapping.credentialReused ? "re-pointed" : "created";
|
|
1597
|
+
const line = previousPrincipal !== undefined
|
|
1598
|
+
? `Re-linked: IdP subject '${params.idpSubject}' (provider '${params.idpProvider}') was mapped to principal ` +
|
|
1599
|
+
`'${previousPrincipal}'; now mapped to '${params.principal}' — Credential(kind:idp) ${outcome} (${mapping.credentialId}).` +
|
|
1600
|
+
supersededCredentialNote(mapping)
|
|
1601
|
+
: `Linked: IdP subject '${params.idpSubject}' (provider '${params.idpProvider}') → principal '${params.principal}' ` +
|
|
1602
|
+
`— Credential(kind:idp) ${outcome} (${mapping.credentialId}).` + supersededCredentialNote(mapping);
|
|
1603
|
+
return {
|
|
1604
|
+
action: previousPrincipal !== undefined ? "replaced" : "linked",
|
|
1605
|
+
principal: params.principal,
|
|
1606
|
+
idpProvider: params.idpProvider,
|
|
1607
|
+
idpSubject: params.idpSubject,
|
|
1608
|
+
previousPrincipal,
|
|
1609
|
+
credentialId: mapping.credentialId,
|
|
1610
|
+
credentialReused: mapping.credentialReused,
|
|
1611
|
+
supersededCredentialIds: mapping.supersededCredentialIds,
|
|
1612
|
+
lines: [line],
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
/**
|
|
1616
|
+
* `flair principal unlink` — revoke the subject's mapping to this principal.
|
|
1617
|
+
* A subject not mapped to that principal or carrying a different provider
|
|
1618
|
+
* name is refused before writing.
|
|
1619
|
+
*/
|
|
1620
|
+
export async function unlinkPrincipalMapping(params, deps = {}) {
|
|
1621
|
+
assertMappingTarget(params);
|
|
1622
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1623
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1624
|
+
const now = (deps.now ?? (() => new Date().toISOString()))();
|
|
1625
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1626
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1627
|
+
const subjectRows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, undefined, true);
|
|
1628
|
+
const active = subjectRows.filter(credentialMapsPrincipal);
|
|
1629
|
+
const mine = active.filter((c) => c?.principalId === params.principal);
|
|
1630
|
+
if (mine.length === 0) {
|
|
1631
|
+
const elsewhere = [...new Set(active.map((c) => String(c?.principalId)))].join(", ");
|
|
1632
|
+
throw new Error(`IdP subject '${params.idpSubject}' is not mapped to principal '${params.principal}' — nothing was written.` +
|
|
1633
|
+
(elsewhere ? ` It is mapped to: ${elsewhere}.` : ` It has no active Credential(kind:idp) mapping.`));
|
|
1634
|
+
}
|
|
1635
|
+
const providers = [...new Set(mine.map((c) => String(c?.idpProvider)))];
|
|
1636
|
+
if (providers.length !== 1 || providers[0] !== params.idpProvider) {
|
|
1637
|
+
throw new Error(`IdP subject '${params.idpSubject}' is mapped to principal '${params.principal}' under provider ` +
|
|
1638
|
+
`'${providers.join(", ")}', not '${params.idpProvider}' — nothing was written. Re-run with ` +
|
|
1639
|
+
`--idp-provider ${providers[0]}.`);
|
|
1640
|
+
}
|
|
1641
|
+
// flair#2222 — re-validate the state this preflight acted on before revoking.
|
|
1642
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, mappingPreflight(params.principal, params.idpSubject, true, subjectRows));
|
|
1643
|
+
const ids = mine.map((c) => String(c?.id));
|
|
1644
|
+
const unconfirmedMessage = (unconfirmed) => `Identity mapping: revocation unconfirmed for Credential IDs: ${unconfirmed.join(", ")}`;
|
|
1645
|
+
const res = await fetchImpl(opsUrl, {
|
|
1646
|
+
method: "POST",
|
|
1647
|
+
headers: opsHeaders(authHeader),
|
|
1648
|
+
body: JSON.stringify({
|
|
1649
|
+
operation: "update",
|
|
1650
|
+
database: "flair",
|
|
1651
|
+
table: "Credential",
|
|
1652
|
+
records: ids.map((id) => ({ id, status: "revoked", updatedAt: now })),
|
|
1653
|
+
}),
|
|
1654
|
+
}).catch((err) => {
|
|
1655
|
+
throw new Error(`${unconfirmedMessage(ids)} — ${err instanceof Error ? err.message : String(err)}`);
|
|
1656
|
+
});
|
|
1657
|
+
if (!res.ok) {
|
|
1658
|
+
const text = await res.text().catch(() => "");
|
|
1659
|
+
throw new Error(`${unconfirmedMessage(ids)} (HTTP ${res.status})${text ? `: ${text}` : ""}`);
|
|
1660
|
+
}
|
|
1661
|
+
const result = await res.json().catch(() => null);
|
|
1662
|
+
const unconfirmed = ids.filter(id => !writeConfirmed(result, "update_hashes", id));
|
|
1663
|
+
if (unconfirmed.length > 0)
|
|
1664
|
+
throw new Error(unconfirmedMessage(unconfirmed));
|
|
1665
|
+
const remaining = (await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject)
|
|
1666
|
+
.catch((err) => {
|
|
1667
|
+
throw new Error(`${unconfirmedMessage(ids)} — ${err instanceof Error ? err.message : String(err)}`);
|
|
1668
|
+
})).filter(credentialMapsPrincipal);
|
|
1669
|
+
if (remaining.length > 0) {
|
|
1670
|
+
throw new Error(`${unconfirmedMessage(remaining.map(c => c.id))} — subject '${params.idpSubject}' still has resolvable mappings.`);
|
|
1671
|
+
}
|
|
1672
|
+
return {
|
|
1673
|
+
principal: params.principal,
|
|
1674
|
+
idpSubject: params.idpSubject,
|
|
1675
|
+
revokedCredentialIds: ids,
|
|
1676
|
+
lines: [
|
|
1677
|
+
`Unlinked: IdP subject '${params.idpSubject}' is no longer mapped to principal '${params.principal}' — ` +
|
|
1678
|
+
`Credential(kind:idp) revoked (${ids.join(", ")}).`,
|
|
1679
|
+
],
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* `flair principal links` — the principal's current (active) IdP mappings.
|
|
1684
|
+
* A missing principal is refused by name and a failed read is refused too: an
|
|
1685
|
+
* empty list is reported only after a valid read with no active mapping.
|
|
1686
|
+
*/
|
|
1687
|
+
export async function listPrincipalMappings(params, deps = {}) {
|
|
1688
|
+
assertMappingTarget(params);
|
|
1689
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1690
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1691
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1692
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1693
|
+
const active = (await readIdpCredentialsForPrincipal(fetchImpl, opsUrl, authHeader, params.principal)).filter(credentialMapsPrincipal);
|
|
1694
|
+
const mappings = active.map((c) => ({
|
|
1695
|
+
credentialId: String(c?.id),
|
|
1696
|
+
idpProvider: String(c?.idpProvider),
|
|
1697
|
+
idpSubject: String(c?.idpSubject),
|
|
1698
|
+
}));
|
|
1699
|
+
return {
|
|
1700
|
+
principal: params.principal,
|
|
1701
|
+
mappings,
|
|
1702
|
+
lines: mappings.length === 0
|
|
1703
|
+
? [`No IdP mappings for principal '${params.principal}'.`]
|
|
1704
|
+
: mappings.map((m) => `IdP subject '${m.idpSubject}' (provider '${m.idpProvider}') → principal '${params.principal}' (${m.credentialId})`),
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
776
1707
|
// ─── Restart only ────────────────────────────────────────────────────────────
|
|
777
1708
|
/** `restart` only — used by `disableMcp` (flag off + restart, no config
|
|
778
1709
|
* rewrite: the `@harperfast/oauth` config block is left in place; it is
|
|
@@ -792,67 +1723,255 @@ export async function triggerRemoteRestart(opsPortOrUrl, adminUser, adminPass, d
|
|
|
792
1723
|
throw new Error(`restart failed (HTTP ${restartRes.status}): ${text}`);
|
|
793
1724
|
}
|
|
794
1725
|
}
|
|
795
|
-
/**
|
|
796
|
-
*
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
* unreachable/malformed/mismatched response, OR a response that doesn't
|
|
800
|
-
* advertise CIMD support, is `ok: false` with a specific `detail`.
|
|
801
|
-
*
|
|
802
|
-
* flair#756: since CIMD is the only supported client-registration path now,
|
|
803
|
-
* "the /mcp OAuth surface is properly enabled" means "and a CIMD client can
|
|
804
|
-
* actually use it" — this single check is reused by `enable`'s own
|
|
805
|
-
* self-verify step, `grant`/`revoke`'s workflow gate (src/cli.ts), and
|
|
806
|
-
* `flair mcp status`, so all four commands agree on what "enabled" means.
|
|
807
|
-
*/
|
|
808
|
-
export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
1726
|
+
/** Fetch and parse the metadata document at an origin without assuming its
|
|
1727
|
+
* `issuer` equals that origin. A target can serve a public proxy issuer. */
|
|
1728
|
+
async function fetchOAuthMetadata(origin, deps = {}) {
|
|
1729
|
+
const url = `${origin.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`;
|
|
809
1730
|
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
810
|
-
const normalizedIssuer = issuer.replace(/\/+$/, "");
|
|
811
|
-
const url = `${normalizedIssuer}/.well-known/oauth-authorization-server`;
|
|
812
1731
|
let res;
|
|
813
1732
|
try {
|
|
814
|
-
res = await fetchImpl(url, {
|
|
1733
|
+
res = await fetchImpl(url, {
|
|
1734
|
+
signal: AbortSignal.timeout(15_000),
|
|
1735
|
+
...(deps.redirect ? { redirect: deps.redirect } : {}),
|
|
1736
|
+
});
|
|
815
1737
|
}
|
|
816
1738
|
catch (err) {
|
|
817
|
-
return { ok: false, detail: `could not reach ${url}: ${err?.message ?? err}` };
|
|
1739
|
+
return { ok: false, unreachable: true, detail: `could not reach ${url}: ${err?.message ?? err}` };
|
|
1740
|
+
}
|
|
1741
|
+
if (deps.redirect === "manual" && (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400))) {
|
|
1742
|
+
return { ok: false, status: res.status, detail: "--instance answered with a redirect; point --instance at the instance itself." };
|
|
818
1743
|
}
|
|
819
1744
|
if (!res.ok) {
|
|
1745
|
+
return { ok: false, status: res.status, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
|
|
1746
|
+
}
|
|
1747
|
+
try {
|
|
1748
|
+
return { ok: true, url, status: res.status, body: await res.json() };
|
|
1749
|
+
}
|
|
1750
|
+
catch {
|
|
1751
|
+
return { ok: false, status: res.status, detail: `${url} did not return JSON` };
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
/** The MCP authorization server's token endpoint for `issuer` — the one
|
|
1755
|
+
* derivation of "the MCP token endpoint of this instance", shared by target
|
|
1756
|
+
* binding (`verifyTargetIssuer`) and public self-verification
|
|
1757
|
+
* (`selfVerifyMcpMetadata`) so both checks derive the expected token endpoint
|
|
1758
|
+
* from the same function. */
|
|
1759
|
+
function mcpTokenEndpoint(issuer) {
|
|
1760
|
+
return `${issuer.replace(/\/+$/, "")}/oauth/mcp/token`;
|
|
1761
|
+
}
|
|
1762
|
+
/** Which authorization server a `token_endpoint` STRING names, given an `issuer`
|
|
1763
|
+
* the caller already knows: flair's own OAuth 2.1 AS answers
|
|
1764
|
+
* `<issuer>/OAuthToken` (resources/oauth-discovery.ts); the `@harperfast/oauth`
|
|
1765
|
+
* plugin answers `<issuer>/oauth/mcp/token`. Anything else is neither. This is a
|
|
1766
|
+
* string comparison only — it does NOT observe which process answered, and it is
|
|
1767
|
+
* meaningful only when `issuer` is a value the caller knows independently of the
|
|
1768
|
+
* document. One implementation, so the self-verify, the discriminator below and
|
|
1769
|
+
* `flair doctor`/`flair deploy` share the endpoint comparison. */
|
|
1770
|
+
export function mcpAuthServerOwner(issuer, tokenEndpoint) {
|
|
1771
|
+
const normalized = issuer.replace(/\/+$/, "");
|
|
1772
|
+
if (tokenEndpoint === `${normalized}/OAuthToken`)
|
|
1773
|
+
return "flair-own";
|
|
1774
|
+
if (tokenEndpoint === mcpTokenEndpoint(normalized))
|
|
1775
|
+
return "plugin";
|
|
1776
|
+
return "other";
|
|
1777
|
+
}
|
|
1778
|
+
async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
1779
|
+
const target = await fetchOAuthMetadata(instance, { ...deps, redirect: "manual" });
|
|
1780
|
+
const remedy = `Check the OAuth authorization-server metadata served by --instance (${instance}), make sure the target's FLAIR_MCP_ISSUER is ${issuer}, then re-run \`flair mcp enable\`.`;
|
|
1781
|
+
if (target.ok === false)
|
|
1782
|
+
return { ok: false, detail: `Cannot confirm the target's configured issuer: ${target.detail} ${remedy}` };
|
|
1783
|
+
if (target.body?.issuer !== issuer) {
|
|
1784
|
+
const actual = target.body?.issuer;
|
|
1785
|
+
const found = typeof actual === "string" ? `names issuer=${JSON.stringify(actual)}` : `has no string issuer (got ${JSON.stringify(actual)})`;
|
|
1786
|
+
return { ok: false, detail: `The target's own metadata at ${target.url} ${found}; expected ${issuer}. ${remedy}` };
|
|
1787
|
+
}
|
|
1788
|
+
if (target.body?.token_endpoint !== mcpTokenEndpoint(issuer)) {
|
|
820
1789
|
return {
|
|
821
1790
|
ok: false,
|
|
822
|
-
detail:
|
|
1791
|
+
detail: `The target's metadata at ${target.url} has token_endpoint=${JSON.stringify(target.body?.token_endpoint)}, not the MCP authorization server's token endpoint. Check FLAIR_MCP_OAUTH and the @harperfast/oauth component on the target, then re-run \`flair mcp enable\`.`,
|
|
823
1792
|
};
|
|
824
1793
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
1794
|
+
return { ok: true, detail: `Issuer ${issuer} matched the target's own OAuth authorization-server metadata at ${target.url}` };
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* Read `origin`'s discovery document and classify it against the issuer(s) the
|
|
1798
|
+
* caller knows independently of the document.
|
|
1799
|
+
*
|
|
1800
|
+
* caller-known issuer + `/oauth/mcp/token` -> `plugin-live`
|
|
1801
|
+
* caller-known issuer + `/OAuthToken` -> `plugin-absent`
|
|
1802
|
+
* any other document -> `unrecognized`
|
|
1803
|
+
* request failed / non-2xx / non-JSON -> `unreachable`
|
|
1804
|
+
*
|
|
1805
|
+
* This is a string comparison against a caller-known issuer, not an observation
|
|
1806
|
+
* of which process answered. A document whose own `issuer` is not one of the
|
|
1807
|
+
* caller-known candidates (including one that names no issuer) is compared
|
|
1808
|
+
* against nothing and is `unrecognized` — the document is never the trust anchor.
|
|
1809
|
+
*
|
|
1810
|
+
* A failed read is never reported as a state of the surface: `unreachable`
|
|
1811
|
+
* carries `status` only when a response actually came back.
|
|
1812
|
+
*/
|
|
1813
|
+
export async function discriminateMcpOAuthDiscovery(origin, deps = {}) {
|
|
1814
|
+
const normalized = origin.replace(/\/+$/, "");
|
|
1815
|
+
const read = await fetchOAuthMetadata(normalized, deps);
|
|
1816
|
+
if (read.ok === false) {
|
|
1817
|
+
return {
|
|
1818
|
+
state: "unreachable",
|
|
1819
|
+
origin: normalized,
|
|
1820
|
+
url: `${normalized}/.well-known/oauth-authorization-server`,
|
|
1821
|
+
status: read.status,
|
|
1822
|
+
detail: read.detail,
|
|
1823
|
+
};
|
|
828
1824
|
}
|
|
829
|
-
|
|
830
|
-
|
|
1825
|
+
const body = read.body;
|
|
1826
|
+
const tokenEndpoint = body?.token_endpoint;
|
|
1827
|
+
// The issuer(s) THIS caller knows without trusting the document: the origins
|
|
1828
|
+
// passed in (configured FLAIR_PUBLIC_URL / FLAIR_MCP_ISSUER, or the origin the
|
|
1829
|
+
// caller verifies) plus the address actually probed. The document's own
|
|
1830
|
+
// `issuer` is NOT one of them — a positive classification must be bound to an
|
|
1831
|
+
// issuer the caller knows independently (flair#2283). flair can publish
|
|
1832
|
+
// FLAIR_PUBLIC_URL as its issuer while a probe reaches it over loopback, so the
|
|
1833
|
+
// probed address alone is not the issuer.
|
|
1834
|
+
const candidates = [
|
|
1835
|
+
...new Set([...(deps.expectedIssuers ?? []), normalized]
|
|
1836
|
+
.map((issuer) => issuer.trim().replace(/\/+$/, ""))
|
|
1837
|
+
.filter((issuer) => issuer !== "")),
|
|
1838
|
+
];
|
|
1839
|
+
const docIssuer = typeof body?.issuer === "string" && body.issuer.trim() !== ""
|
|
1840
|
+
? body.issuer.trim().replace(/\/+$/, "")
|
|
1841
|
+
: undefined;
|
|
1842
|
+
// The document counts only when its own `issuer` EQUALS a candidate the caller
|
|
1843
|
+
// already knows. A document that names some OTHER issuer — or none — is
|
|
1844
|
+
// compared against nothing and cannot be positively classified.
|
|
1845
|
+
const bound = docIssuer !== undefined && candidates.includes(docIssuer) ? docIssuer : undefined;
|
|
1846
|
+
const owner = bound ? mcpAuthServerOwner(bound, tokenEndpoint) : "other";
|
|
1847
|
+
const common = {
|
|
1848
|
+
origin: normalized,
|
|
1849
|
+
url: read.url,
|
|
1850
|
+
status: read.status,
|
|
1851
|
+
issuer: typeof body?.issuer === "string" ? body.issuer : undefined,
|
|
1852
|
+
tokenEndpoint: typeof tokenEndpoint === "string" ? tokenEndpoint : undefined,
|
|
1853
|
+
body,
|
|
1854
|
+
};
|
|
1855
|
+
if (owner === "plugin") {
|
|
1856
|
+
return {
|
|
1857
|
+
...common,
|
|
1858
|
+
state: "plugin-live",
|
|
1859
|
+
detail: `${read.url} advertises token_endpoint=${JSON.stringify(tokenEndpoint)}, the MCP token endpoint of the caller-known issuer ${JSON.stringify(bound)}`,
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
if (owner === "flair-own") {
|
|
1863
|
+
return {
|
|
1864
|
+
...common,
|
|
1865
|
+
state: "plugin-absent",
|
|
1866
|
+
detail: `${read.url} advertises token_endpoint=${JSON.stringify(tokenEndpoint)}, flair's own authorization server for the caller-known issuer ${JSON.stringify(bound)}`,
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
const named = docIssuer === undefined
|
|
1870
|
+
? "the document names no issuer"
|
|
1871
|
+
: candidates.includes(docIssuer)
|
|
1872
|
+
? `the document names issuer=${JSON.stringify(body?.issuer)}, whose token endpoint ${JSON.stringify(tokenEndpoint)} is neither authorization server`
|
|
1873
|
+
: `the document names issuer=${JSON.stringify(body?.issuer)}, which is not an issuer this caller knows (known: ${candidates.map((c) => JSON.stringify(c)).join(", ")})`;
|
|
1874
|
+
return {
|
|
1875
|
+
...common,
|
|
1876
|
+
state: "unrecognized",
|
|
1877
|
+
detail: `${read.url} answered with an unrecognized discovery document — ${named}`,
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
/** The detail `flair mcp enable`'s self-verify prints for a `plugin-absent` observation. */
|
|
1881
|
+
function mcpAbsentDetail(url, tokenEndpoint) {
|
|
1882
|
+
return (`${url} advertises flair's own token endpoint (token_endpoint=${tokenEndpoint}). ` +
|
|
1883
|
+
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
1884
|
+
`component declared in its config.yaml?`);
|
|
1885
|
+
}
|
|
1886
|
+
/**
|
|
1887
|
+
* The operator-facing report for a discovery observation, shared by `flair
|
|
1888
|
+
* doctor` and `flair deploy` so both word it identically.
|
|
1889
|
+
*
|
|
1890
|
+
* `mcpConfigured` is the locally inferred `FLAIR_MCP_OAUTH` the caller can see.
|
|
1891
|
+
* A `plugin-absent` observation is a document whose `issuer` equals a caller-known
|
|
1892
|
+
* candidate (a configured public URL / MCP issuer, or the verified origin) while
|
|
1893
|
+
* advertising flair's own `<issuer>/OAuthToken`; true yields a named failure with a
|
|
1894
|
+
* remedy, false yields an informational line. An `unreachable` or `unrecognized`
|
|
1895
|
+
* observation — including a document whose issuer is no candidate — is never a pass,
|
|
1896
|
+
* and never an error: it says the surface could not be confirmed.
|
|
1897
|
+
*/
|
|
1898
|
+
export function reportMcpOAuthDiscovery(observation, mcpConfigured) {
|
|
1899
|
+
switch (observation.state) {
|
|
1900
|
+
case "plugin-live":
|
|
1901
|
+
return {
|
|
1902
|
+
severity: "ok",
|
|
1903
|
+
pass: true,
|
|
1904
|
+
lines: [`MCP OAuth discovery: the metadata advertises the expected token endpoint (${observation.url}).`],
|
|
1905
|
+
};
|
|
1906
|
+
case "plugin-absent":
|
|
1907
|
+
if (!mcpConfigured) {
|
|
1908
|
+
return {
|
|
1909
|
+
severity: "info",
|
|
1910
|
+
pass: false,
|
|
1911
|
+
lines: [
|
|
1912
|
+
`MCP OAuth discovery: local configuration does not imply MCP OAuth is enabled; ${observation.url} advertises flair's own token endpoint.`,
|
|
1913
|
+
],
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1916
|
+
return {
|
|
1917
|
+
severity: "error",
|
|
1918
|
+
pass: false,
|
|
1919
|
+
lines: [
|
|
1920
|
+
`MCP OAuth discovery: local configuration implies FLAIR_MCP_OAUTH is enabled, but the document advertises flair's own token endpoint — ${observation.detail}.`,
|
|
1921
|
+
`Fix: set FLAIR_MCP_OAUTH=true in the instance environment and confirm the '@harperfast/oauth' component is declared in its config.yaml, then restart (see \`flair mcp status\`).`,
|
|
1922
|
+
],
|
|
1923
|
+
};
|
|
1924
|
+
case "unreachable":
|
|
1925
|
+
case "unrecognized":
|
|
1926
|
+
return {
|
|
1927
|
+
severity: "warn",
|
|
1928
|
+
pass: false,
|
|
1929
|
+
lines: [`MCP OAuth discovery: the MCP authorization server could not be confirmed — ${observation.detail}.`],
|
|
1930
|
+
};
|
|
831
1931
|
}
|
|
832
|
-
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Hit the OAuth metadata endpoint from the operator's machine against the
|
|
1935
|
+
* PUBLIC origin — the verification that matters is the one claude.ai's
|
|
1936
|
+
* perspective sees (scenario addendum). Never reports success on hope: any
|
|
1937
|
+
* unreachable/malformed/mismatched response, OR a response that doesn't
|
|
1938
|
+
* advertise CIMD support, is `ok: false` with a specific `detail`.
|
|
1939
|
+
*
|
|
1940
|
+
* flair#756: since CIMD is the only supported client-registration path now,
|
|
1941
|
+
* this checks the public metadata's issuer, MCP token endpoint, and CIMD
|
|
1942
|
+
* advertisement; it does not exercise the token route or `/mcp`. The check
|
|
1943
|
+
* is reused by `enable`'s self-verify step, `grant`/`revoke`'s workflow gate
|
|
1944
|
+
* (src/commands/mcp.ts), and `flair mcp status`, so all four commands use the same
|
|
1945
|
+
* public metadata criterion.
|
|
1946
|
+
*/
|
|
1947
|
+
export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
1948
|
+
const normalizedIssuer = issuer.replace(/\/+$/, "");
|
|
1949
|
+
// ── The discriminator runs BEFORE the shape check (flair#1094, flair#2283) ──
|
|
833
1950
|
//
|
|
834
|
-
//
|
|
835
|
-
//
|
|
836
|
-
// which it is not by default — so the shape check fired first and returned
|
|
837
|
-
// "the metadata shape is unexpected", which is true, useless, and points at
|
|
838
|
-
// shapes when the cause is an unset environment variable.
|
|
1951
|
+
// A document bound to a caller-known issuer advertising `<issuer>/OAuthToken`
|
|
1952
|
+
// is named before checking registration_endpoint, even when DCR is off.
|
|
839
1953
|
//
|
|
840
|
-
//
|
|
841
|
-
//
|
|
842
|
-
//
|
|
843
|
-
|
|
844
|
-
if (
|
|
1954
|
+
// This used to be an inline token_endpoint comparison here. flair#2283 lifted
|
|
1955
|
+
// it into `discriminateMcpOAuthDiscovery` so `flair doctor` and `flair deploy`
|
|
1956
|
+
// run the SAME function instead of re-deriving the comparison.
|
|
1957
|
+
const observation = await discriminateMcpOAuthDiscovery(normalizedIssuer, { ...deps, expectedIssuers: [normalizedIssuer] });
|
|
1958
|
+
if (observation.state === "unreachable") {
|
|
1959
|
+
// `status` is absent when no response came back.
|
|
1960
|
+
return observation.status === undefined
|
|
1961
|
+
? { ok: false, unreachable: true, detail: observation.detail }
|
|
1962
|
+
: { ok: false, detail: observation.detail };
|
|
1963
|
+
}
|
|
1964
|
+
if (observation.state === "plugin-absent") {
|
|
845
1965
|
return {
|
|
846
1966
|
ok: false,
|
|
847
|
-
issuer:
|
|
848
|
-
registrationEndpoint: body?.registration_endpoint,
|
|
849
|
-
tokenEndpoint:
|
|
850
|
-
detail:
|
|
851
|
-
`(token_endpoint=${body.token_endpoint}) — the /mcp surface is NOT enabled on that instance. ` +
|
|
852
|
-
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
853
|
-
`component declared in its config.yaml?`,
|
|
1967
|
+
issuer: observation.issuer,
|
|
1968
|
+
registrationEndpoint: observation.body?.registration_endpoint,
|
|
1969
|
+
tokenEndpoint: observation.tokenEndpoint,
|
|
1970
|
+
detail: mcpAbsentDetail(observation.url, observation.tokenEndpoint),
|
|
854
1971
|
};
|
|
855
1972
|
}
|
|
1973
|
+
const url = observation.url;
|
|
1974
|
+
const body = observation.body;
|
|
856
1975
|
// ── registration_endpoint is OPTIONAL and must not be required (Kern, #1101) ─
|
|
857
1976
|
//
|
|
858
1977
|
// Requiring it made self-verify fail on a CORRECTLY enabled instance — the
|
|
@@ -886,25 +2005,6 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
886
2005
|
detail: `${url} responded but the metadata shape is unexpected (issuer/token_endpoint) — got issuer=${JSON.stringify(body?.issuer)}`,
|
|
887
2006
|
};
|
|
888
2007
|
}
|
|
889
|
-
// flair#1000: this path is now served by flair ITSELF when FLAIR_MCP_OAUTH is
|
|
890
|
-
// off, so a 200 no longer proves the plugin answered. flair's own document
|
|
891
|
-
// (resources/oauth-discovery.ts) is identifiable by its token endpoint —
|
|
892
|
-
// `<issuer>/OAuthToken`, where the plugin's is `<issuer>/oauth/mcp/token`.
|
|
893
|
-
// Name the real cause here: before this existed the operator got a 404 whose
|
|
894
|
-
// message already asked the right question, and falling through to the CIMD
|
|
895
|
-
// branch would send them to a plugin knob that is not the problem.
|
|
896
|
-
if (body.token_endpoint === `${normalizedIssuer}/OAuthToken`) {
|
|
897
|
-
return {
|
|
898
|
-
ok: false,
|
|
899
|
-
issuer: body.issuer,
|
|
900
|
-
registrationEndpoint: body.registration_endpoint,
|
|
901
|
-
tokenEndpoint: body.token_endpoint,
|
|
902
|
-
detail: `${url} answered with flair's OWN OAuth 2.1 authorization server, not the MCP one ` +
|
|
903
|
-
`(token_endpoint=${body.token_endpoint}) — the /mcp surface is NOT enabled on that instance. ` +
|
|
904
|
-
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
905
|
-
`component declared in its config.yaml?`,
|
|
906
|
-
};
|
|
907
|
-
}
|
|
908
2008
|
// flair#756: confirm CIMD is actually advertised (node_modules/@harperfast/
|
|
909
2009
|
// oauth/dist/lib/mcp/wellKnown.js:129-165's buildAuthorizationServerMetadata:
|
|
910
2010
|
// `client_id_metadata_document_supported` is set only when
|
|
@@ -924,6 +2024,22 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
924
2024
|
detail: `${url} answered but does not advertise CIMD support (client_id_metadata_document_supported / "none" in token_endpoint_auth_methods_supported) — is clientIdMetadataDocuments.enabled explicitly false?`,
|
|
925
2025
|
};
|
|
926
2026
|
}
|
|
2027
|
+
// flair#2190: the public document must name the MCP authorization server's
|
|
2028
|
+
// token endpoint exactly — the same derivation target binding requires
|
|
2029
|
+
// (mcpTokenEndpoint). The flair's-own-server and CIMD checks above run
|
|
2030
|
+
// first, so those cases keep their specific remedies.
|
|
2031
|
+
if (body.token_endpoint !== mcpTokenEndpoint(normalizedIssuer)) {
|
|
2032
|
+
return {
|
|
2033
|
+
ok: false,
|
|
2034
|
+
issuer: body.issuer,
|
|
2035
|
+
registrationEndpoint: body.registration_endpoint,
|
|
2036
|
+
tokenEndpoint: body.token_endpoint,
|
|
2037
|
+
cimdSupported: true,
|
|
2038
|
+
detail: `Found token_endpoint=${JSON.stringify(body.token_endpoint)} in ${url}, not the MCP authorization server's ` +
|
|
2039
|
+
`expected token_endpoint=${mcpTokenEndpoint(normalizedIssuer)}. This metadata cannot verify the MCP endpoint. ` +
|
|
2040
|
+
`Check the public OAuth authorization-server metadata or proxy for ${normalizedIssuer}, then re-run \`flair mcp enable\`.`,
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
927
2043
|
return {
|
|
928
2044
|
ok: true,
|
|
929
2045
|
issuer: body.issuer,
|
|
@@ -1020,6 +2136,20 @@ export async function captureBootDiscriminator(opsPortOrUrl, adminUser, adminPas
|
|
|
1020
2136
|
}
|
|
1021
2137
|
return { pid };
|
|
1022
2138
|
}
|
|
2139
|
+
/**
|
|
2140
|
+
* flair#1317/#2115 — the note a mapping reports when it revoked a prior
|
|
2141
|
+
* credential for the subject. Returned with a leading space so it appends to a
|
|
2142
|
+
* line, and empty when nothing was superseded. One implementation, so `flair
|
|
2143
|
+
* principal link` prints it exactly as `flair mcp enable` does.
|
|
2144
|
+
*/
|
|
2145
|
+
function supersededCredentialNote(mapping) {
|
|
2146
|
+
return mapping.credentialSuperseded
|
|
2147
|
+
? ` SUPERSEDED: ${mapping.supersededCredentialIds.length} prior Credential(kind:idp) row(s) for this subject ` +
|
|
2148
|
+
`were REVOKED, not de-duplicated — ${mapping.supersededCredentialIds.join(", ")}. ` +
|
|
2149
|
+
`The revoked rows no longer resolve. Future calls for this subject use the surviving mapping. ` +
|
|
2150
|
+
`Exactly one resolvable (principal-bearing) active credential remains per (kind, idpSubject). Principal-less legacy rows are skipped and may remain active.`
|
|
2151
|
+
: "";
|
|
2152
|
+
}
|
|
1023
2153
|
/**
|
|
1024
2154
|
* Full `flair mcp enable` orchestration. No `process.exit`, no console
|
|
1025
2155
|
* output — directly unit-testable with a mocked fetch and temp dirs, same
|
|
@@ -1028,9 +2158,8 @@ export async function captureBootDiscriminator(opsPortOrUrl, adminUser, adminPas
|
|
|
1028
2158
|
* hope).
|
|
1029
2159
|
*
|
|
1030
2160
|
* flair#756: no DCR step anywhere in this flow — CIMD needs no
|
|
1031
|
-
* pre-registration
|
|
1032
|
-
*
|
|
1033
|
-
* `apply-config-and-restart`.
|
|
2161
|
+
* pre-registration. The target's MCP metadata issuer is
|
|
2162
|
+
* checked before the public issuer metadata can count as completion.
|
|
1034
2163
|
*/
|
|
1035
2164
|
export async function enableMcp(params, deps = {}) {
|
|
1036
2165
|
const steps = [];
|
|
@@ -1046,34 +2175,111 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1046
2175
|
//
|
|
1047
2176
|
// Initialised to the first step rather than left undefined so a throw before
|
|
1048
2177
|
// any assignment cannot be attributed to an arbitrary fallback name.
|
|
1049
|
-
let currentStep = "
|
|
2178
|
+
let currentStep = "target-shape-check";
|
|
1050
2179
|
const dryRun = Boolean(params.dryRun);
|
|
1051
2180
|
const push = (ok, detail) => steps.push({ step: currentStep, ok, detail });
|
|
2181
|
+
const targetRefusal = targetOriginRefusal(params.instance) ?? fabricLoopbackRefusal(params.instance, params.fabric);
|
|
2182
|
+
if (targetRefusal) {
|
|
2183
|
+
currentStep = "target-shape-check";
|
|
2184
|
+
push(false, targetRefusal);
|
|
2185
|
+
return { ok: false, dryRun, refused: { message: targetRefusal }, steps, failedStep: "target-shape-check" };
|
|
2186
|
+
}
|
|
1052
2187
|
// ── Local-origin refusal (scenario addendum, binding) ─────────────────────
|
|
1053
2188
|
currentStep = "local-origin-check";
|
|
1054
|
-
const
|
|
2189
|
+
const rawIssuer = params.issuer ?? params.instance;
|
|
2190
|
+
const issuer = rawIssuer.replace(/\/$/, "");
|
|
2191
|
+
const localCheck = checkLocalOriginRefusal(issuer);
|
|
1055
2192
|
if (localCheck.refused) {
|
|
1056
2193
|
push(false, localCheck.message);
|
|
1057
|
-
return { ok: false, dryRun, refused: { message: localCheck.message }, steps, failedStep: "local-origin-check" };
|
|
2194
|
+
return { ok: false, dryRun, refused: { reason: localCheck.reason, message: localCheck.message }, steps, failedStep: "local-origin-check" };
|
|
1058
2195
|
}
|
|
1059
|
-
push(true, `${
|
|
1060
|
-
const issuer = (params.issuer ?? params.instance).replace(/\/+$/, "");
|
|
2196
|
+
push(true, `${issuer}: URL parsed; hostname/IP-literal check passed (no DNS lookup)`);
|
|
1061
2197
|
const idpProvider = params.idpProvider ?? "github";
|
|
1062
2198
|
const principal = params.principal ?? "self";
|
|
1063
2199
|
const principalKind = params.principalKind ?? "human";
|
|
2200
|
+
// flair#2359 — the resolved principal becomes the id of the Agent row the
|
|
2201
|
+
// identity-mapping step writes, so it must satisfy the shared agent-ID rule
|
|
2202
|
+
// before the dry run reports success and before any secrets are staged or
|
|
2203
|
+
// pushed.
|
|
2204
|
+
if (!isValidAgentId(principal)) {
|
|
2205
|
+
currentStep = "principal-id-check";
|
|
2206
|
+
const message = `principal: ${invalidAgentIdMessage(principal)} Nothing was changed.`;
|
|
2207
|
+
push(false, message);
|
|
2208
|
+
return { ok: false, dryRun, refused: { reason: "invalid", message }, steps, failedStep: "principal-id-check" };
|
|
2209
|
+
}
|
|
2210
|
+
const fabricTarget = isFabricTarget(params.instance, params.fabric);
|
|
1064
2211
|
try {
|
|
1065
|
-
// ──
|
|
1066
|
-
currentStep = "
|
|
1067
|
-
const
|
|
1068
|
-
|
|
2212
|
+
// ── Issuer origin (flair#2194) ────────────────────────────────────────────
|
|
2213
|
+
currentStep = "issuer-origin-check";
|
|
2214
|
+
const issuerIssue = issuerOriginRefusal(rawIssuer);
|
|
2215
|
+
if (issuerIssue) {
|
|
2216
|
+
push(false, issuerIssue);
|
|
2217
|
+
return { ok: false, dryRun, refused: { message: issuerIssue }, steps, failedStep: "issuer-origin-check" };
|
|
2218
|
+
}
|
|
2219
|
+
push(true, `issuer ${issuer} is an absolute http(s) origin`);
|
|
2220
|
+
if (!dryRun && !fabricTarget && !isLoopbackUrl(params.instance)) {
|
|
2221
|
+
currentStep = "target-shape-check";
|
|
2222
|
+
const message = `${params.instance} is not a loopback URL or a *.harperfabric.com target. ` +
|
|
2223
|
+
`For Harper Fabric behind a custom domain, use --fabric. Nothing was changed.`;
|
|
2224
|
+
push(false, message);
|
|
2225
|
+
return { ok: false, dryRun, refused: { message }, steps, failedStep: "target-shape-check" };
|
|
2226
|
+
}
|
|
2227
|
+
// ── --cimd-allowed-hosts (flair#2113) ─────────────────────────────────────
|
|
2228
|
+
let cimdAllowedHosts;
|
|
2229
|
+
if (params.cimdAllowedHosts !== undefined) {
|
|
2230
|
+
currentStep = "cimd-allowed-hosts";
|
|
2231
|
+
const refuse = (message) => {
|
|
2232
|
+
push(false, message);
|
|
2233
|
+
return { ok: false, dryRun, refused: { message }, steps, failedStep: "cimd-allowed-hosts" };
|
|
2234
|
+
};
|
|
2235
|
+
try {
|
|
2236
|
+
cimdAllowedHosts = validateCimdAllowedHosts(params.cimdAllowedHosts);
|
|
2237
|
+
}
|
|
2238
|
+
catch (err) {
|
|
2239
|
+
return refuse(err?.message ?? String(err));
|
|
2240
|
+
}
|
|
2241
|
+
const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance, params.fabric);
|
|
2242
|
+
if (shapeRefusal)
|
|
2243
|
+
return refuse(shapeRefusal);
|
|
2244
|
+
const current = readLocalConfigCimdAllowedHosts(params.localConfigPath);
|
|
2245
|
+
if (!current.ok) {
|
|
2246
|
+
return refuse(`--cimd-allowed-hosts cannot be applied: ${current.detail}. Run this command on the instance's host, from the ` +
|
|
2247
|
+
`directory that holds the config.yaml it runs from, or edit ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} there by hand. ` +
|
|
2248
|
+
`Nothing was changed.`);
|
|
2249
|
+
}
|
|
2250
|
+
const change = `${CIMD_ALLOWED_HOSTS_CONFIG_KEY} in ${current.path}: ${JSON.stringify(current.current ?? null)} -> ` +
|
|
2251
|
+
`${JSON.stringify(cimdAllowedHosts)}`;
|
|
2252
|
+
if (dryRun) {
|
|
2253
|
+
push(true, `${change} (--dry-run: the target was not checked, and the list was not written)`);
|
|
2254
|
+
}
|
|
2255
|
+
else {
|
|
2256
|
+
const target = await checkTargetRunsFromConfig(params.instance, params.adminUser, params.adminPass, current.path, {
|
|
2257
|
+
fetchImpl: deps.fetchImpl,
|
|
2258
|
+
readProcessCwd: deps.readProcessCwd,
|
|
2259
|
+
readProcessCmdline: deps.readProcessCmdline,
|
|
2260
|
+
localHostname: deps.localHostname,
|
|
2261
|
+
});
|
|
2262
|
+
if (!target.ok) {
|
|
2263
|
+
return refuse(`--cimd-allowed-hosts refused: ${target.detail}. Edit ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} by hand in the ` +
|
|
2264
|
+
`config.yaml the target runs from, on its host, then restart it. Nothing was changed.`);
|
|
2265
|
+
}
|
|
2266
|
+
push(true, `${change} (the local-config-update step, before the restart, writes it unless the file already holds that exact list, ` +
|
|
2267
|
+
`then reads it back; a run that stops before that step does not write it); ${target.detail}`);
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
1069
2270
|
// ── @harperfast/oauth config (flair#1136: shipped in config.yaml) ──────
|
|
1070
|
-
// The block ships uncommented with mcp.enabled:
|
|
2271
|
+
// The block ships uncommented with mcp.enabled: ${FLAIR_MCP_OAUTH}
|
|
2272
|
+
// (flair#1152), so the environment turns it on. This step writes nothing;
|
|
2273
|
+
// it reports the block config.yaml ships (flair#2116: it used to print
|
|
2274
|
+
// false), and a --cimd-allowed-hosts value only as requested, never as shipped.
|
|
1071
2275
|
// set_configuration is removed — the block lives in the component's own
|
|
1072
2276
|
// config.yaml, not in harperdb-config.yaml where Fabric would wipe it.
|
|
1073
|
-
const cimdAllowedHosts = params.cimdAllowedHosts ?? DEFAULT_CIMD_ALLOWED_HOSTS;
|
|
1074
2277
|
currentStep = "config-block";
|
|
1075
|
-
push(true, `@harperfast/oauth config ships in config.yaml (mcp.enabled
|
|
1076
|
-
`dynamicClientRegistration.enabled=false, clientIdMetadataDocuments.allowedHosts=${JSON.stringify(
|
|
2278
|
+
push(true, `@harperfast/oauth config ships in config.yaml; this step writes nothing (mcp.enabled=${MCP_ENABLED_ENV_REFERENCE}, read from the instance environment; ` +
|
|
2279
|
+
`dynamicClientRegistration.enabled=false, clientIdMetadataDocuments.allowedHosts=${JSON.stringify(DEFAULT_CIMD_ALLOWED_HOSTS)})` +
|
|
2280
|
+
(cimdAllowedHosts
|
|
2281
|
+
? `; --cimd-allowed-hosts ${JSON.stringify(cimdAllowedHosts)} was requested; the cimd-allowed-hosts step above says whether and when this run writes it`
|
|
2282
|
+
: ""));
|
|
1077
2283
|
// ── IdP OAuth-app credential intake ───────────────────────────────────────
|
|
1078
2284
|
currentStep = "idp-credentials";
|
|
1079
2285
|
const callbackUrl = idpCallbackUrl(issuer, idpProvider);
|
|
@@ -1088,9 +2294,8 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1088
2294
|
}
|
|
1089
2295
|
push(true, `${idpProvider} OAuth app credentials present; callback URL: ${callbackUrl}`);
|
|
1090
2296
|
if (dryRun) {
|
|
1091
|
-
// Dry-run stops here
|
|
1092
|
-
// remote
|
|
1093
|
-
// without --dry-run either.
|
|
2297
|
+
// Dry-run stops here. Under --dry-run nothing above wrote a file or made
|
|
2298
|
+
// a remote call, and nothing below this line runs.
|
|
1094
2299
|
return {
|
|
1095
2300
|
ok: true,
|
|
1096
2301
|
dryRun: true,
|
|
@@ -1098,29 +2303,30 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1098
2303
|
issuer,
|
|
1099
2304
|
resource: `${issuer}/mcp`,
|
|
1100
2305
|
callbackUrl,
|
|
1101
|
-
signingKeyFilePath: keyResult.path,
|
|
1102
2306
|
};
|
|
1103
2307
|
}
|
|
1104
2308
|
// ── Secrets provisioning (shape-aware, never silent) ──────────────────────
|
|
1105
|
-
|
|
2309
|
+
currentStep = "secrets-provisioning";
|
|
1106
2310
|
const bundle = buildSecretsBundle({
|
|
1107
2311
|
issuer,
|
|
1108
|
-
signingKeyPem,
|
|
1109
2312
|
idpProvider,
|
|
1110
2313
|
idpClientId: params.idpClientId,
|
|
1111
2314
|
idpClientSecret: params.idpClientSecret,
|
|
1112
2315
|
});
|
|
1113
|
-
|
|
2316
|
+
if (bundle.FLAIR_MCP_ISSUER !== issuer) {
|
|
2317
|
+
throw new Error(`the FLAIR_MCP_ISSUER being pushed does not equal the issuer checked (${issuer})`);
|
|
2318
|
+
}
|
|
1114
2319
|
// Stage first, unconditionally. If the push works the file is a no-op the
|
|
1115
2320
|
// operator never opens; if anything about the push is uncertain they still
|
|
1116
2321
|
// have the thing that always works, without a re-run. Staging costs a 0600
|
|
1117
2322
|
// write; not staging costs an operator stranded mid-enable.
|
|
1118
2323
|
const secretsResult = provisionSecrets(params.instance, bundle, {
|
|
1119
2324
|
mechanism: params.secretsMechanism,
|
|
2325
|
+
fabric: params.fabric,
|
|
1120
2326
|
stagingPath: params.secretsStagingPath,
|
|
1121
2327
|
});
|
|
1122
2328
|
// Ask the TARGET whether it can take these, rather than inferring from its
|
|
1123
|
-
// hostname or its version
|
|
2329
|
+
// hostname or its version.
|
|
1124
2330
|
// An explicit --secrets-mechanism is an operator override and is honoured
|
|
1125
2331
|
// without a probe: they have said what they want.
|
|
1126
2332
|
let secretsPushed = false;
|
|
@@ -1153,7 +2359,9 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1153
2359
|
// ── Identity mapping (Credential kind:idp) ────────────────────────────────
|
|
1154
2360
|
currentStep = "identity-mapping";
|
|
1155
2361
|
const mapping = await provisionIdpIdentityMapping({
|
|
1156
|
-
|
|
2362
|
+
// The instance URL is the served origin: ask for its host at the hosted
|
|
2363
|
+
// ops port, the address resolveOpsUrl gives the other steps (flair#2102).
|
|
2364
|
+
hostedOrigin: params.instance,
|
|
1157
2365
|
adminUser: params.adminUser,
|
|
1158
2366
|
adminPass: params.adminPass,
|
|
1159
2367
|
principal,
|
|
@@ -1170,51 +2378,93 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1170
2378
|
// credential (one active credential per subject is the invariant). That is
|
|
1171
2379
|
// a credential dying, so it is stated as such, by id: an operator must
|
|
1172
2380
|
// never discover it later from something that stopped working.
|
|
1173
|
-
const supersedeNote = mapping
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
`They no longer resolve, and anything relying on them stops working. ` +
|
|
1177
|
-
`Exactly one active credential per (kind, idpSubject) is the invariant that keeps resolution deterministic.`
|
|
1178
|
-
: "";
|
|
1179
|
-
push(true, `connector identity: sub '${params.idpSubject}' (provider '${idpProvider}') resolves to Agent '${principal}' — ` +
|
|
1180
|
-
`every /mcp call reads and writes AS '${principal}'. ` +
|
|
2381
|
+
const supersedeNote = supersededCredentialNote(mapping);
|
|
2382
|
+
push(true, `connector identity: mapped sub '${params.idpSubject}' (provider '${idpProvider}') to Agent '${principal}'; ` +
|
|
2383
|
+
`see docs/access-control.md for how /mcp tool calls use it. ` +
|
|
1181
2384
|
`principal ${mapping.principalCreated ? "created" : "already existed"}; ` +
|
|
1182
2385
|
`Credential(kind:idp) ${mapping.credentialReused ? "re-pointed" : "created"} (${mapping.credentialId}).` +
|
|
1183
2386
|
`${supersedeNote} ` +
|
|
1184
2387
|
`If your CLI signs as a DIFFERENT agent id, the connector sees that agent's DISTINCT memory scope (by design) — ` +
|
|
1185
2388
|
`re-run with --principal <your-agent-id> to link them. ` +
|
|
1186
2389
|
`Diagnostic: the bootstrap tool's agentId/scope fields always say who the server resolved you to.`);
|
|
1187
|
-
// ── Gate:
|
|
2390
|
+
// ── Gate: require confirmation that the secrets are live before continuing
|
|
1188
2391
|
let confirmed = Boolean(params.confirmSecretsApplied);
|
|
1189
2392
|
if (!confirmed && deps.confirmPrompt) {
|
|
1190
|
-
confirmed = await deps.confirmPrompt(
|
|
2393
|
+
confirmed = await deps.confirmPrompt(secretsPushed
|
|
2394
|
+
? fabricTarget
|
|
2395
|
+
? `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you restarted the Fabric instance to load them?`
|
|
2396
|
+
: `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you loaded them into the instance's process environment?`
|
|
2397
|
+
: `Have you applied the ${secretsResult.varNames.length} vars staged at ${secretsResult.path} to ${params.instance}'s environment?`);
|
|
1191
2398
|
}
|
|
1192
2399
|
if (!confirmed) {
|
|
1193
|
-
push(false,
|
|
2400
|
+
push(false, secretsPushed
|
|
2401
|
+
? `not confirmed: the secrets were pushed to ${params.instance} and read back; ${fabricTarget ? "restart the Fabric instance" : "load them into the instance's process environment"}, then re-run \`flair mcp enable\` with --confirm-secrets-applied.`
|
|
2402
|
+
: `not applied: pass --confirm-secrets-applied once the staged secrets are live on ${params.instance}, then re-run \`flair mcp enable\` (earlier steps are idempotent and will reuse what's already provisioned).`);
|
|
1194
2403
|
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path };
|
|
1195
2404
|
}
|
|
1196
2405
|
// ── flair#1136: config delivery is now SHIPPED in config.yaml ────────────
|
|
1197
|
-
// The @harperfast/oauth block ships uncommented with mcp.enabled:
|
|
1198
|
-
// (
|
|
1199
|
-
// harperdb-config.yaml on every container restart, so writing
|
|
1200
|
-
// there was always a race against the next deploy. Instead:
|
|
2406
|
+
// The @harperfast/oauth block ships uncommented with mcp.enabled:
|
|
2407
|
+
// ${FLAIR_MCP_OAUTH} (flair#1152). set_configuration is REMOVED — Fabric
|
|
2408
|
+
// regenerates harperdb-config.yaml on every container restart, so writing
|
|
2409
|
+
// the block there was always a race against the next deploy. Instead:
|
|
1201
2410
|
//
|
|
1202
|
-
// - Standalone-local:
|
|
1203
|
-
// restart, self-verify.
|
|
1204
|
-
// - Fabric:
|
|
1205
|
-
//
|
|
1206
|
-
// success with /mcp still dark.
|
|
1207
|
-
|
|
1208
|
-
if (isFabric) {
|
|
2411
|
+
// - Standalone-local: set mcp.enabled to the env reference in the local
|
|
2412
|
+
// config.yaml (updateLocalConfigMcpEnabled), restart, self-verify.
|
|
2413
|
+
// - Fabric: `enable` does not restart the instance; the operator applies
|
|
2414
|
+
// the environment and restarts. Report the requirement LOUDLY — never
|
|
2415
|
+
// report success with /mcp still dark.
|
|
2416
|
+
if (fabricTarget) {
|
|
1209
2417
|
// ── Fabric: operator-deploy requirement ──────────────────────────────
|
|
1210
2418
|
currentStep = "fabric-operator-deploy";
|
|
1211
|
-
const
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
2419
|
+
const host = new URL(params.instance).hostname;
|
|
2420
|
+
// flair#2116: this step used to fail unconditionally, so a re-run after
|
|
2421
|
+
// the operator's restart ended here with the same instructions, forever.
|
|
2422
|
+
currentStep = "issuer-target-binding";
|
|
2423
|
+
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
2424
|
+
if (!binding.ok) {
|
|
2425
|
+
push(false, binding.detail);
|
|
2426
|
+
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "issuer-target-binding", issuer, resource: `${issuer}/mcp`, secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path, callbackUrl };
|
|
2427
|
+
}
|
|
2428
|
+
currentStep = "fabric-operator-deploy";
|
|
2429
|
+
// The target's metadata names the issuer. Now check the public origin.
|
|
2430
|
+
const live = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
|
|
2431
|
+
if (live.ok) {
|
|
2432
|
+
push(true, `Fabric deployment (${host}): ${binding.detail}; the /mcp OAuth surface already passes self-verify on ${issuer}. ` +
|
|
2433
|
+
`If this run changed a secret value (a new IdP client secret, for example), restart the instance so its process picks the new value up.`);
|
|
2434
|
+
currentStep = "self-verify";
|
|
2435
|
+
push(true, live.detail);
|
|
2436
|
+
const resource = `${issuer}/mcp`;
|
|
2437
|
+
return {
|
|
2438
|
+
ok: true,
|
|
2439
|
+
dryRun: false,
|
|
2440
|
+
steps,
|
|
2441
|
+
issuer,
|
|
2442
|
+
resource,
|
|
2443
|
+
pasteBlock: buildClaudePasteBlock(resource),
|
|
2444
|
+
secretsMechanism: secretsResult.mechanism,
|
|
2445
|
+
secretsPath: secretsResult.path,
|
|
2446
|
+
callbackUrl,
|
|
2447
|
+
};
|
|
2448
|
+
}
|
|
2449
|
+
// A request that failed read nothing: it shows neither that the
|
|
2450
|
+
// environment is wrong nor that a restart is needed, so it gets checks
|
|
2451
|
+
// to run instead of the activation instructions (flair#2116).
|
|
2452
|
+
const msg = live.unreachable
|
|
2453
|
+
? [
|
|
2454
|
+
`Fabric deployment detected (${host}); the public issuer could not be reached (${live.detail}).`,
|
|
2455
|
+
`A failed request does not show that the environment is wrong or that a restart is needed.`,
|
|
2456
|
+
`Check first that the host in that URL resolves in DNS, that this machine can reach it over HTTPS, and that the instance is running in Fabric.`,
|
|
2457
|
+
`Then re-run \`flair mcp enable\` with the same options plus --confirm-secrets-applied: this step checks ${issuer} again, passes once self-verify does, and says what to apply if the surface answers but is not active.`,
|
|
2458
|
+
].join(" ")
|
|
2459
|
+
: [
|
|
2460
|
+
`Fabric deployment detected (${host}); self-verify on ${issuer} has not passed yet (${live.detail}).`,
|
|
2461
|
+
`The @harperfast/oauth block ships in config.yaml with mcp.enabled: \${FLAIR_MCP_OAUTH} (env-referenced, flair#1152) — no config edit is needed.`,
|
|
2462
|
+
secretsPushed
|
|
2463
|
+
? `To activate: the secrets were pushed to the instance above (FLAIR_MCP_OAUTH=true among them); restart the instance.`
|
|
2464
|
+
: `To activate: apply the staged secrets (FLAIR_MCP_OAUTH=true among them) to the instance's environment (Fabric env), then restart the instance.`,
|
|
2465
|
+
`Deploys can no longer revert the choice — it lives in the environment, not the packed file.`,
|
|
2466
|
+
`Then re-run \`flair mcp enable\` with the same options plus --confirm-secrets-applied: this step checks ${issuer} again and passes once self-verify does.`,
|
|
2467
|
+
].join(" ");
|
|
1218
2468
|
push(false, msg);
|
|
1219
2469
|
return {
|
|
1220
2470
|
ok: false,
|
|
@@ -1225,14 +2475,58 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1225
2475
|
resource: `${issuer}/mcp`,
|
|
1226
2476
|
secretsMechanism: secretsResult.mechanism,
|
|
1227
2477
|
secretsPath: secretsResult.path,
|
|
1228
|
-
signingKeyFilePath: keyResult.path,
|
|
1229
2478
|
callbackUrl,
|
|
1230
2479
|
};
|
|
1231
2480
|
}
|
|
1232
2481
|
// ── Standalone (non-Fabric): update local config + restart ────────────
|
|
1233
2482
|
currentStep = "local-config-update";
|
|
1234
2483
|
const localConfigResult = updateLocalConfigMcpEnabled(true, params.localConfigPath);
|
|
1235
|
-
|
|
2484
|
+
if (!localConfigResult.ok) {
|
|
2485
|
+
// flair#2193: stop BEFORE the restart. The mcp.enabled update was not
|
|
2486
|
+
// confirmed (the file may have changed), and the metadata checks below
|
|
2487
|
+
// could still pass and report success.
|
|
2488
|
+
const retry = params.localConfigPath
|
|
2489
|
+
? "retry the call with the same explicit path"
|
|
2490
|
+
: "re-run `flair mcp enable`";
|
|
2491
|
+
push(false, `${localConfigResult.detail} This command did not restart the instance. Fix the cause above, then ${retry}.`);
|
|
2492
|
+
return {
|
|
2493
|
+
ok: false,
|
|
2494
|
+
dryRun,
|
|
2495
|
+
steps,
|
|
2496
|
+
failedStep: "local-config-update",
|
|
2497
|
+
issuer,
|
|
2498
|
+
resource: `${issuer}/mcp`,
|
|
2499
|
+
secretsMechanism: secretsResult.mechanism,
|
|
2500
|
+
secretsPath: secretsResult.path,
|
|
2501
|
+
callbackUrl,
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
push(true, localConfigResult.detail);
|
|
2505
|
+
// flair#2113: ensure --cimd-allowed-hosts (written unless the file already
|
|
2506
|
+
// holds that exact list) and read it back. A failure here stops the flow
|
|
2507
|
+
// before the restart.
|
|
2508
|
+
let writtenCimd;
|
|
2509
|
+
if (cimdAllowedHosts) {
|
|
2510
|
+
const written = updateLocalConfigCimdAllowedHosts(cimdAllowedHosts, params.localConfigPath);
|
|
2511
|
+
if (!written.ok || !written.readBack || !written.path) {
|
|
2512
|
+
push(false, `--cimd-allowed-hosts change could not be confirmed: ${written.detail}. The config.yaml may have changed, ` +
|
|
2513
|
+
`and this command did not restart the instance. ` +
|
|
2514
|
+
`Fix that, or set ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} by hand, then re-run \`flair mcp enable\`.`);
|
|
2515
|
+
return {
|
|
2516
|
+
ok: false,
|
|
2517
|
+
dryRun,
|
|
2518
|
+
steps,
|
|
2519
|
+
failedStep: "local-config-update",
|
|
2520
|
+
issuer,
|
|
2521
|
+
resource: `${issuer}/mcp`,
|
|
2522
|
+
secretsMechanism: secretsResult.mechanism,
|
|
2523
|
+
secretsPath: secretsResult.path,
|
|
2524
|
+
callbackUrl,
|
|
2525
|
+
};
|
|
2526
|
+
}
|
|
2527
|
+
writtenCimd = { hosts: written.readBack, path: written.path };
|
|
2528
|
+
push(true, written.detail);
|
|
2529
|
+
}
|
|
1236
2530
|
// ── Restart ───────────────────────────────────────────────────────────
|
|
1237
2531
|
currentStep = "restart";
|
|
1238
2532
|
const preDiscriminator = await captureBootDiscriminator(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
|
|
@@ -1246,8 +2540,13 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1246
2540
|
pollMs: deps.waitForOpsApiPollMs,
|
|
1247
2541
|
});
|
|
1248
2542
|
push(true, `process restarted: pid changed ${preDiscriminator.pid} -> ${postDiscriminator.pid}`);
|
|
1249
|
-
// ──
|
|
2543
|
+
// ── Match the target's issuer, then self-verify the public origin ────────
|
|
1250
2544
|
currentStep = "self-verify";
|
|
2545
|
+
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
2546
|
+
if (!binding.ok) {
|
|
2547
|
+
push(false, binding.detail);
|
|
2548
|
+
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "self-verify", issuer, resource: `${issuer}/mcp`, secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path, callbackUrl, cimdAllowedHosts: writtenCimd?.hosts, cimdAllowedHostsConfigPath: writtenCimd?.path };
|
|
2549
|
+
}
|
|
1251
2550
|
const verify = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
|
|
1252
2551
|
if (!verify.ok) {
|
|
1253
2552
|
push(false, `${verify.detail} — re-run \`flair mcp status\` to check current state, or \`flair mcp enable\` to retry.`);
|
|
@@ -1258,9 +2557,11 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1258
2557
|
failedStep: "self-verify",
|
|
1259
2558
|
issuer,
|
|
1260
2559
|
resource: `${issuer}/mcp`,
|
|
2560
|
+
cimdAllowedHosts: writtenCimd?.hosts,
|
|
2561
|
+
cimdAllowedHostsConfigPath: writtenCimd?.path,
|
|
1261
2562
|
};
|
|
1262
2563
|
}
|
|
1263
|
-
push(true, verify.detail);
|
|
2564
|
+
push(true, `${binding.detail}; ${verify.detail}`);
|
|
1264
2565
|
const resource = `${issuer}/mcp`;
|
|
1265
2566
|
return {
|
|
1266
2567
|
ok: true,
|
|
@@ -1271,8 +2572,9 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1271
2572
|
pasteBlock: buildClaudePasteBlock(resource),
|
|
1272
2573
|
secretsMechanism: secretsResult.mechanism,
|
|
1273
2574
|
secretsPath: secretsResult.path,
|
|
1274
|
-
signingKeyFilePath: keyResult.path,
|
|
1275
2575
|
callbackUrl,
|
|
2576
|
+
cimdAllowedHosts: writtenCimd?.hosts,
|
|
2577
|
+
cimdAllowedHostsConfigPath: writtenCimd?.path,
|
|
1276
2578
|
};
|
|
1277
2579
|
}
|
|
1278
2580
|
catch (err) {
|
|
@@ -1287,8 +2589,8 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1287
2589
|
// Two results for one step, and the ✓ instructs several minutes of manual
|
|
1288
2590
|
// work in a web UI that the ✗ makes pointless. Read in order, you do the
|
|
1289
2591
|
// work first.
|
|
1290
|
-
// No
|
|
1291
|
-
//
|
|
2592
|
+
// No fallback step NAME: currentStep is initialised to the first step, so
|
|
2593
|
+
// there is no undefined case to invent a name for. A fallback here
|
|
1292
2594
|
// would attribute a throw to a step chosen for being a plausible default —
|
|
1293
2595
|
// the same misattribution this handler exists to prevent, one layer down.
|
|
1294
2596
|
push(false, `unexpected error: ${err?.message ?? err}`);
|
|
@@ -1324,15 +2626,150 @@ export async function disableMcp(params, deps = {}) {
|
|
|
1324
2626
|
catch (err) {
|
|
1325
2627
|
return { ok: false, detail: `restart failed: ${err?.message ?? err}` };
|
|
1326
2628
|
}
|
|
1327
|
-
return { ok: true, detail: `
|
|
2629
|
+
return { ok: true, detail: `restart requested for ${params.instance}` };
|
|
2630
|
+
}
|
|
2631
|
+
/**
|
|
2632
|
+
* flair#2283 — the one-shot migration for an instance that still holds the old
|
|
2633
|
+
* staged value (`FLAIR_MCP_OAUTH=1`, recorded by `buildSecretsBundle` before
|
|
2634
|
+
* flair#1284 changed the staged value to `true`). Flair's own reader accepts
|
|
2635
|
+
* `1`, but the `@harperfast/oauth` component does not enable its MCP AS for `1`.
|
|
2636
|
+
*
|
|
2637
|
+
* Attempts an encrypted `FLAIR_MCP_OAUTH=true` push and checks the processEnv marker.
|
|
2638
|
+
* After a confirmed push and PID-verified restart, checks target and public
|
|
2639
|
+
* discovery against the requested issuer and its MCP token endpoint.
|
|
2640
|
+
* A failed probe, local encryption failure, refused or unconfirmed push, or
|
|
2641
|
+
* unconfirmed read-back attempts a 0600 fallback and returns `{ ok: false }`
|
|
2642
|
+
* before discovery checks; the CLI exits non-zero. Refresh has
|
|
2643
|
+
* a separate default filename; `--secrets-path` can select `mcp enable`'s path.
|
|
2644
|
+
* An occupied explicit path is refused before probing, including in dry run; an occupied default path
|
|
2645
|
+
* is refused when fallback is needed. The fallback writer opens exclusively.
|
|
2646
|
+
* Does not run IdP intake, apply CIMD changes or read or write IdP secret values.
|
|
2647
|
+
*/
|
|
2648
|
+
export async function refreshMcpOAuthFlag(params, deps = {}) {
|
|
2649
|
+
const steps = [];
|
|
2650
|
+
const dryRun = Boolean(params.dryRun);
|
|
2651
|
+
let currentStep = "target-shape-check";
|
|
2652
|
+
const push = (ok, detail) => steps.push({ step: currentStep, ok, detail });
|
|
2653
|
+
// Set only after the fallback writer returns successfully.
|
|
2654
|
+
let stagedFallbackPath;
|
|
2655
|
+
const targetRefusal = targetOriginRefusal(params.instance) ?? fabricLoopbackRefusal(params.instance, params.fabric);
|
|
2656
|
+
if (targetRefusal) {
|
|
2657
|
+
push(false, targetRefusal);
|
|
2658
|
+
return { ok: false, dryRun, refused: { message: targetRefusal }, steps, failedStep: "target-shape-check" };
|
|
2659
|
+
}
|
|
2660
|
+
push(true, `${params.instance}: target shape accepted`);
|
|
2661
|
+
const issuer = (params.issuer ?? params.instance).replace(/\/+$/, "");
|
|
2662
|
+
const stagedPath = params.secretsStagingPath ?? defaultRefreshSecretsStagingPath(params.instance);
|
|
2663
|
+
// The one-var fallback is written EXCLUSIVELY. An occupied path — the target's
|
|
2664
|
+
// OWN default INCLUDED — is refused by name, never truncated, because it may be
|
|
2665
|
+
// the full IdP credentials bundle a prior `mcp enable --secrets-path` staged
|
|
2666
|
+
// there (flair#2283). Returns the refusal message instead of writing in that
|
|
2667
|
+
// case; `stagedFallbackPath` is set only when a file was really created.
|
|
2668
|
+
const occupiedMessage = (path) => `refusing to write the one-var bundle over the existing file at ${path}; remove it or name a path that does not exist`;
|
|
2669
|
+
// Returns the refusal message when the target path is already occupied, or null
|
|
2670
|
+
// when the file was really created; `stagedFallbackPath` is set only in the latter
|
|
2671
|
+
// case (flair#2283).
|
|
2672
|
+
const writeFallback = () => {
|
|
2673
|
+
try {
|
|
2674
|
+
writeSecretsStagingFile(stagedPath, { FLAIR_MCP_OAUTH: "true" }, { exclusive: true });
|
|
2675
|
+
stagedFallbackPath = stagedPath;
|
|
2676
|
+
return null;
|
|
2677
|
+
}
|
|
2678
|
+
catch (err) {
|
|
2679
|
+
if (err?.code === "EEXIST")
|
|
2680
|
+
return occupiedMessage(stagedPath);
|
|
2681
|
+
throw err;
|
|
2682
|
+
}
|
|
2683
|
+
};
|
|
2684
|
+
try {
|
|
2685
|
+
currentStep = "secrets-provisioning";
|
|
2686
|
+
// An EXPLICIT staging path is the operator's own target. Refuse an occupied one
|
|
2687
|
+
// BEFORE probing, so no request is made and the file is left byte-identical
|
|
2688
|
+
// (flair#2283).
|
|
2689
|
+
if (params.secretsStagingPath && lstatSync(params.secretsStagingPath, { throwIfNoEntry: false })) {
|
|
2690
|
+
const message = occupiedMessage(params.secretsStagingPath);
|
|
2691
|
+
push(false, message);
|
|
2692
|
+
return { ok: false, dryRun, steps, refused: { message }, failedStep: "secrets-provisioning" };
|
|
2693
|
+
}
|
|
2694
|
+
if (dryRun) {
|
|
2695
|
+
push(true, `--dry-run: would attempt an encrypted FLAIR_MCP_OAUTH=true update to ${params.instance}, check the secret row's processEnv marker, restart and check discovery metadata; nothing was changed.`);
|
|
2696
|
+
return { ok: true, dryRun: true, steps };
|
|
2697
|
+
}
|
|
2698
|
+
// Attempt fallback creation when the update could not be pushed or confirmed.
|
|
2699
|
+
const cap = await probeSecretsCapability(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), { fetchImpl: deps.fetchImpl });
|
|
2700
|
+
if (!cap.available || !cap.publicKeyPem) {
|
|
2701
|
+
const refusal = writeFallback();
|
|
2702
|
+
if (refusal) {
|
|
2703
|
+
push(false, refusal);
|
|
2704
|
+
return { ok: false, dryRun, steps, refused: { message: refusal }, failedStep: "secrets-provisioning" };
|
|
2705
|
+
}
|
|
2706
|
+
push(false, `cannot set FLAIR_MCP_OAUTH over the ops API: ${cap.reason}. The one-var bundle is staged at ${stagedPath} (0600); apply it to ${params.instance}'s process environment and restart.`);
|
|
2707
|
+
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsPath: stagedFallbackPath };
|
|
2708
|
+
}
|
|
2709
|
+
const pushed = await pushSecrets(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), { FLAIR_MCP_OAUTH: "true" }, cap.publicKeyPem, { fetchImpl: deps.fetchImpl, sealImpl: deps.sealImpl });
|
|
2710
|
+
if (!pushed.allOk) {
|
|
2711
|
+
const failedResults = pushed.results.filter((r) => !r.ok);
|
|
2712
|
+
const failed = failedResults.map((r) => `${r.name} (${r.detail})`).join("; ");
|
|
2713
|
+
const lead = failedResults.every((r) => r.kind === "local-failure")
|
|
2714
|
+
? "FLAIR_MCP_OAUTH=true local encryption failure: nothing was sent, nothing stored by this attempt"
|
|
2715
|
+
: failedResults.some((r) => r.kind === "push-unconfirmed")
|
|
2716
|
+
? "FLAIR_MCP_OAUTH=true push outcome could not be confirmed (it may have been stored)"
|
|
2717
|
+
: failedResults.every((r) => r.kind === "confirm")
|
|
2718
|
+
? "FLAIR_MCP_OAUTH=true received a successful push response, but its storage with processEnv=true could not be confirmed"
|
|
2719
|
+
: "FLAIR_MCP_OAUTH=true push was refused by the target";
|
|
2720
|
+
const refusal = writeFallback()?.replace(/^/, `${lead}: ${failed}. `);
|
|
2721
|
+
if (refusal) {
|
|
2722
|
+
push(false, refusal);
|
|
2723
|
+
return { ok: false, dryRun, steps, refused: { message: refusal }, failedStep: "secrets-provisioning" };
|
|
2724
|
+
}
|
|
2725
|
+
push(false, `${lead}: ${failed}. The one-var bundle is staged at ${stagedPath} (0600); apply it and restart.`);
|
|
2726
|
+
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsPath: stagedFallbackPath };
|
|
2727
|
+
}
|
|
2728
|
+
push(true, `FLAIR_MCP_OAUTH=true pushed to the target as an enc:v1 env-secret (tier ${PROCESS_ENV_TIER}); the value was sealed locally.`);
|
|
2729
|
+
// Restart for the env-secrets decryptor to load the updated secret.
|
|
2730
|
+
currentStep = "restart";
|
|
2731
|
+
const pre = await captureBootDiscriminator(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
|
|
2732
|
+
await triggerRemoteRestart(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
|
|
2733
|
+
push(true, `restart triggered against ${params.instance}`);
|
|
2734
|
+
currentStep = "verify-restart";
|
|
2735
|
+
const post = await waitForOpsApi(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), pre.pid, { fetchImpl: deps.fetchImpl, timeoutMs: deps.waitForOpsApiTimeoutMs, pollMs: deps.waitForOpsApiPollMs });
|
|
2736
|
+
push(true, `process restarted: pid changed ${pre.pid} -> ${post.pid}`);
|
|
2737
|
+
// Bind the verification to the target: the target's OWN document must
|
|
2738
|
+
// advertise the issuer we are about to verify, and its token endpoint must
|
|
2739
|
+
// be the MCP one. Without this, a matching document elsewhere could let a
|
|
2740
|
+
// broken target report ok (flair#2283).
|
|
2741
|
+
currentStep = "issuer-target-binding";
|
|
2742
|
+
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
2743
|
+
if (!binding.ok) {
|
|
2744
|
+
push(false, binding.detail);
|
|
2745
|
+
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "issuer-target-binding" };
|
|
2746
|
+
}
|
|
2747
|
+
push(true, binding.detail);
|
|
2748
|
+
// The PUBLIC document read at `issuer` must name the SAME verified issuer and
|
|
2749
|
+
// its token endpoint, else refuse by name. The discriminator is bound to the
|
|
2750
|
+
// issuer this caller verified — `issuer` — so a document naming any other
|
|
2751
|
+
// issuer is not a positive result (flair#2283).
|
|
2752
|
+
currentStep = "self-verify";
|
|
2753
|
+
const observation = await discriminateMcpOAuthDiscovery(issuer, { fetchImpl: deps.fetchImpl, expectedIssuers: [issuer] });
|
|
2754
|
+
if (observation.state !== "plugin-live") {
|
|
2755
|
+
push(false, `refused: the public document at ${issuer} did not confirm the MCP authorization server for the verified issuer ${issuer} — ${observation.detail}`);
|
|
2756
|
+
return { ok: false, dryRun, steps, failedStep: "self-verify" };
|
|
2757
|
+
}
|
|
2758
|
+
push(true, observation.detail);
|
|
2759
|
+
return { ok: true, dryRun: false, steps };
|
|
2760
|
+
}
|
|
2761
|
+
catch (err) {
|
|
2762
|
+
push(false, `unexpected error: ${err?.message ?? err}`);
|
|
2763
|
+
return { ok: false, dryRun, steps, failedStep: currentStep, secretsPath: stagedFallbackPath };
|
|
2764
|
+
}
|
|
1328
2765
|
}
|
|
1329
2766
|
/**
|
|
1330
|
-
*
|
|
1331
|
-
* metadata endpoint `enable`'s self-verify step checks.
|
|
1332
|
-
*
|
|
1333
|
-
*
|
|
1334
|
-
*
|
|
1335
|
-
* the
|
|
2767
|
+
* Reports a live public-metadata check (not a stale local marker): hits the
|
|
2768
|
+
* same well-known metadata endpoint `enable`'s self-verify step checks. An expected issuer,
|
|
2769
|
+
* exact MCP token endpoint, CIMD advertisement and, when present, a string
|
|
2770
|
+
* `registration_endpoint` verify the public metadata;
|
|
2771
|
+
* they do not prove that the token route or `/mcp` is usable. `status` reports
|
|
2772
|
+
* the live metadata check's result rather than guessing from local files.
|
|
1336
2773
|
*/
|
|
1337
2774
|
export async function mcpStatus(params, deps = {}) {
|
|
1338
2775
|
const verify = await selfVerifyMcpMetadata(params.instance, { fetchImpl: deps.fetchImpl });
|