@tpsdev-ai/flair 0.59.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 +4 -4
- package/SECURITY.md +36 -0
- package/config.yaml +12 -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 +991 -248
- package/dist/commands/agent.js +224 -43
- 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 +592 -146
- 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 +97 -35
- 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 +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -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 +24 -0
- 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 +1168 -326
- 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 +76 -12
- 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 +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- 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 +110 -39
- 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/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 +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- 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 +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- 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 +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- 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/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 +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- 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 +20 -11
- 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 +4 -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 +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- 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 +5 -5
- package/docs/mcp-clients.md +5 -2
- 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 +12 -6
- 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 +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
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,13 +137,18 @@
|
|
|
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, realpathSync } from "node:fs";
|
|
142
|
+
import { existsSync, lstatSync, mkdirSync, writeFileSync, chmodSync, readFileSync, realpathSync } from "node:fs";
|
|
144
143
|
import { hostname as osHostname } from "node:os";
|
|
145
144
|
import { join, dirname, resolve } from "node:path";
|
|
146
|
-
import {
|
|
145
|
+
import { randomBytes } from "node:crypto";
|
|
147
146
|
import yaml from "js-yaml";
|
|
148
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";
|
|
149
152
|
import { defaultReadProcessCmdline, defaultReadProcessCwd } from "./upgrade-exec-path.js";
|
|
150
153
|
// ─── CIMD constants ──────────────────────────────────────────────────────────
|
|
151
154
|
/** Default `clientIdMetadataDocuments.allowedHosts` allowlist — see the
|
|
@@ -156,102 +159,181 @@ export const DEFAULT_CIMD_ALLOWED_HOSTS = ["claude.ai", "claude.com"];
|
|
|
156
159
|
/** Required TTL per Sherlock's Model-2 requirement 1 — never the plugin's 1h default. */
|
|
157
160
|
export const REQUIRED_ACCESS_TOKEN_TTL = 900;
|
|
158
161
|
// ─── Local-origin detection (scenario addendum, binding) ───────────────────
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
* than proceed against an origin we can't even parse).
|
|
165
|
-
*/
|
|
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
|
+
}
|
|
166
167
|
export function isLocalOrigin(url) {
|
|
167
168
|
let hostname;
|
|
168
169
|
try {
|
|
169
|
-
hostname = new URL(url).hostname.toLowerCase();
|
|
170
|
+
hostname = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
|
|
170
171
|
}
|
|
171
172
|
catch {
|
|
172
|
-
return
|
|
173
|
+
return false;
|
|
173
174
|
}
|
|
174
175
|
if (hostname === "localhost" || hostname.endsWith(".localhost"))
|
|
175
176
|
return true;
|
|
176
|
-
// WHATWG URL keeps IPv6 hosts bracketed in `.hostname` (e.g. "[::1]").
|
|
177
|
-
if (hostname === "::1" || hostname === "[::1]")
|
|
178
|
-
return true;
|
|
179
177
|
if (hostname.endsWith(".local"))
|
|
180
178
|
return true;
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
if (
|
|
186
|
-
return true; // loopback
|
|
187
|
-
if (a === 10)
|
|
188
|
-
return true; // RFC1918
|
|
189
|
-
if (a === 172 && b >= 16 && b <= 31)
|
|
190
|
-
return true; // RFC1918
|
|
191
|
-
if (a === 192 && b === 168)
|
|
192
|
-
return true; // RFC1918
|
|
193
|
-
if (a === 169 && b === 254)
|
|
194
|
-
return true; // link-local
|
|
195
|
-
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)
|
|
196
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;
|
|
197
191
|
}
|
|
198
|
-
|
|
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]));
|
|
199
194
|
}
|
|
200
|
-
/** Structural refusal check + the exact operator-facing message (scenario addendum). */
|
|
201
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
|
+
}
|
|
202
203
|
if (isLocalOrigin(url))
|
|
203
|
-
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
|
+
};
|
|
204
208
|
return { refused: false };
|
|
205
209
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
* to pick the secrets-provisioning mechanism's DEFAULT — always overridable
|
|
209
|
-
* via `--secrets-mechanism`. */
|
|
210
|
-
export function isFabricOrigin(url) {
|
|
210
|
+
export function issuerOriginRefusal(issuer) {
|
|
211
|
+
let valid = false;
|
|
211
212
|
try {
|
|
212
|
-
|
|
213
|
+
if (/^https?:\/\/[^/?#\\\s]+\/?$/.test(issuer)) {
|
|
214
|
+
valid = issuer.replace(/\/$/, "") === new URL(issuer).origin;
|
|
215
|
+
}
|
|
213
216
|
}
|
|
214
217
|
catch {
|
|
215
|
-
|
|
218
|
+
valid = false;
|
|
216
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.`);
|
|
217
224
|
}
|
|
218
225
|
/**
|
|
219
|
-
*
|
|
220
|
-
* primary per the scenario addendum: a recognized Fabric origin defaults to
|
|
221
|
-
* `fabric-env-secrets` (Harper's encrypted env-secrets, 5.2-alpha as of this
|
|
222
|
-
* writing — see the module header on why this is a DOCUMENTED procedure, not
|
|
223
|
-
* an automated push: no confirmed ops-API operation for it exists in the
|
|
224
|
-
* installed 5.1.17 SDK). Anything else defaults to `env-file` — the
|
|
225
|
-
* documented, universally-supported fallback. Always overridable.
|
|
226
|
-
*/
|
|
227
|
-
/**
|
|
228
|
-
* ── The hostname no longer selects the mechanism (flair#1094) ───────────────
|
|
226
|
+
* flair#2115 — the target policy for `flair principal link|unlink|links`.
|
|
229
227
|
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
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.
|
|
232
231
|
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
235
|
-
* not found", identical to an invented operation — and was selected for the
|
|
236
|
-
* automated mechanism purely because of its name.
|
|
237
|
-
* - a self-hosted Harper 5.2 with the Pro env-secrets component is fully
|
|
238
|
-
* capable and was sent down the manual Studio path for not matching.
|
|
239
|
-
*
|
|
240
|
-
* A hostname is not a capability, and neither is a version — the write
|
|
241
|
-
* operations and the Pro decryptor that makes a `processEnv` secret reach the
|
|
242
|
-
* process ship separately. `probeSecretsCapability` asks the target instead, and
|
|
243
|
-
* the answer decides at provisioning time.
|
|
244
|
-
*
|
|
245
|
-
* What remains here is the STAGING FILE's flavour of instructions, which is
|
|
246
|
-
* genuinely about where the operator will paste if we end up falling back.
|
|
247
|
-
* Fabric operators paste into Studio; everyone else edits a unit file. That is a
|
|
248
|
-
* UI fact about a human, not a claim about the server, so a hostname is a
|
|
249
|
-
* 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.
|
|
250
234
|
*/
|
|
251
|
-
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) {
|
|
252
334
|
if (override)
|
|
253
335
|
return override;
|
|
254
|
-
return
|
|
336
|
+
return isFabricTarget(instanceUrl, fabric) ? "fabric-env-secrets" : "env-file";
|
|
255
337
|
}
|
|
256
338
|
// ─── --cimd-allowed-hosts (flair#2113) ───────────────────────────────────────
|
|
257
339
|
//
|
|
@@ -322,13 +404,8 @@ export function validateCimdAllowedHosts(entries) {
|
|
|
322
404
|
}
|
|
323
405
|
return hosts;
|
|
324
406
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
* only on its non-Fabric branch, and this uses the same `isFabricOrigin` test
|
|
328
|
-
* that picks that branch.
|
|
329
|
-
*/
|
|
330
|
-
export function cimdAllowedHostsShapeRefusal(instanceUrl) {
|
|
331
|
-
if (!isFabricOrigin(instanceUrl))
|
|
407
|
+
export function cimdAllowedHostsShapeRefusal(instanceUrl, fabric = false) {
|
|
408
|
+
if (!isFabricTarget(instanceUrl, fabric))
|
|
332
409
|
return null;
|
|
333
410
|
return (`--cimd-allowed-hosts is refused for a Fabric instance (${new URL(instanceUrl).hostname}): ` +
|
|
334
411
|
`the component reads ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} from the @harperfast/oauth block of the config.yaml ` +
|
|
@@ -340,7 +417,7 @@ export function cimdAllowedHostsShapeRefusal(instanceUrl) {
|
|
|
340
417
|
* `{ hosts }` when it is valid for this target, `{ error }` otherwise. An
|
|
341
418
|
* explicit empty value is an error, never "absent".
|
|
342
419
|
*/
|
|
343
|
-
export function cimdAllowedHostsFromFlag(raw, instanceUrl) {
|
|
420
|
+
export function cimdAllowedHostsFromFlag(raw, instanceUrl, fabric = false) {
|
|
344
421
|
if (raw === undefined)
|
|
345
422
|
return {};
|
|
346
423
|
let hosts;
|
|
@@ -350,7 +427,7 @@ export function cimdAllowedHostsFromFlag(raw, instanceUrl) {
|
|
|
350
427
|
catch (err) {
|
|
351
428
|
return { error: err?.message ?? String(err) };
|
|
352
429
|
}
|
|
353
|
-
const refusal = cimdAllowedHostsShapeRefusal(instanceUrl);
|
|
430
|
+
const refusal = cimdAllowedHostsShapeRefusal(instanceUrl, fabric);
|
|
354
431
|
return refusal ? { error: refusal } : { hosts };
|
|
355
432
|
}
|
|
356
433
|
/**
|
|
@@ -369,38 +446,6 @@ export function claudeAiExcludedNote(written) {
|
|
|
369
446
|
`so while the instance uses that list, a CIMD client_id URL on claude.ai is refused. ` +
|
|
370
447
|
`Re-run with claude.ai in --cimd-allowed-hosts to allow it.`);
|
|
371
448
|
}
|
|
372
|
-
/** RS256 signing keypair for `mcp.signingKeyPem` — `crypto.generateKeyPairSync`,
|
|
373
|
-
* never a PRNG shortcut (Sherlock's Model-2 requirement 2 implementation note). */
|
|
374
|
-
export function generateRsaSigningKeyPair() {
|
|
375
|
-
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
|
|
376
|
-
modulusLength: 2048,
|
|
377
|
-
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
378
|
-
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
379
|
-
});
|
|
380
|
-
return { publicKey, privateKey };
|
|
381
|
-
}
|
|
382
|
-
export function defaultSigningKeyFilePath() {
|
|
383
|
-
return join(resolveHome(), ".flair", "mcp-signing-key.pem");
|
|
384
|
-
}
|
|
385
|
-
/** Write the RS256 private key PEM to a 0600 file (idempotent — reuses an
|
|
386
|
-
* existing file rather than silently rotating the signing key). */
|
|
387
|
-
export function ensureSigningKeyFile(filePath, deps = {}) {
|
|
388
|
-
const path = filePath ?? defaultSigningKeyFilePath();
|
|
389
|
-
if (existsSync(path)) {
|
|
390
|
-
return { path, reused: true };
|
|
391
|
-
}
|
|
392
|
-
const generate = deps.generate ?? generateRsaSigningKeyPair;
|
|
393
|
-
const { privateKey } = generate();
|
|
394
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
395
|
-
writeFileSync(path, privateKey, { mode: 0o600 });
|
|
396
|
-
chmodSync(path, 0o600);
|
|
397
|
-
return { path, reused: false };
|
|
398
|
-
}
|
|
399
|
-
/** Read back a signing key file's PEM contents (used to fold it into the
|
|
400
|
-
* secrets bundle — never logged, never returned in an `EnableMcpResult`). */
|
|
401
|
-
export function readSigningKeyFile(path) {
|
|
402
|
-
return readFileSync(path, "utf-8");
|
|
403
|
-
}
|
|
404
449
|
/**
|
|
405
450
|
* The `@harperfast/oauth` config block, matching the installed 2.2.0
|
|
406
451
|
* package's field names (node_modules/@harperfast/oauth/dist/types.d.ts).
|
|
@@ -431,6 +476,12 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
431
476
|
[provider]: {
|
|
432
477
|
clientId: `\${${envPrefix}_CLIENT_ID}`,
|
|
433
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}`,
|
|
434
485
|
},
|
|
435
486
|
},
|
|
436
487
|
mcp: {
|
|
@@ -467,7 +518,8 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
467
518
|
// resolution still runs cimd.js's full SSRF/document-validation
|
|
468
519
|
// pipeline regardless of this list.
|
|
469
520
|
clientIdMetadataDocuments: { allowedHosts: cimdAllowedHosts },
|
|
470
|
-
signingKeyPem
|
|
521
|
+
// Without signingKeyPem, minting reuses a persisted key or generates
|
|
522
|
+
// and persists one if oauth.harper_oauth_mcp_keys is empty.
|
|
471
523
|
},
|
|
472
524
|
},
|
|
473
525
|
};
|
|
@@ -501,8 +553,7 @@ function resolveLocalConfigPath(explicitPath) {
|
|
|
501
553
|
* to the reference). `enabled: false` writes literal `false` — decisively off
|
|
502
554
|
* regardless of environment.
|
|
503
555
|
*
|
|
504
|
-
*
|
|
505
|
-
* `~/.flair/config.yaml`.
|
|
556
|
+
* Uses `explicitPath` alone if given; otherwise `./config.yaml`, then `~/.flair/config.yaml`.
|
|
506
557
|
*/
|
|
507
558
|
export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
508
559
|
const { configPath, candidates } = resolveLocalConfigPath(explicitPath);
|
|
@@ -514,7 +565,11 @@ export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
|
514
565
|
return {
|
|
515
566
|
ok: false,
|
|
516
567
|
detail: `local config.yaml not found (tried: ${candidates.join(", ")}). ` +
|
|
517
|
-
|
|
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.`),
|
|
518
573
|
};
|
|
519
574
|
}
|
|
520
575
|
let raw;
|
|
@@ -863,11 +918,27 @@ function safeYamlLoad(text) {
|
|
|
863
918
|
export function idpCallbackUrl(issuer, idpProvider) {
|
|
864
919
|
return `${issuer.replace(/\/+$/, "")}/oauth/${idpProvider}/callback`;
|
|
865
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
|
+
}
|
|
866
927
|
/** The full set of env vars the restarted instance needs live. Contains
|
|
867
928
|
* secret VALUES — this is the one place they exist as a JS object; callers
|
|
868
929
|
* must never fold this into a CLI-printed / `EnableMcpResult` field. */
|
|
869
930
|
export function buildSecretsBundle(params) {
|
|
870
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
|
+
}
|
|
871
942
|
return {
|
|
872
943
|
// "true" is the ONLY value both readers of this flag accept (flair#1152,
|
|
873
944
|
// measured against oauth 2.5.0): flair's strict mcpOAuthEnabled() takes
|
|
@@ -878,12 +949,12 @@ export function buildSecretsBundle(params) {
|
|
|
878
949
|
// 401s, no AS is advertised). Keep this "true".
|
|
879
950
|
FLAIR_MCP_OAUTH: "true",
|
|
880
951
|
FLAIR_MCP_ISSUER: params.issuer.replace(/\/+$/, ""),
|
|
881
|
-
FLAIR_MCP_SIGNING_KEY_PEM: params.signingKeyPem,
|
|
882
952
|
[`${envPrefix}_CLIENT_ID`]: params.idpClientId,
|
|
883
953
|
[`${envPrefix}_CLIENT_SECRET`]: params.idpClientSecret,
|
|
954
|
+
[`${envPrefix}_REDIRECT_URI`]: `${origin}/oauth`,
|
|
884
955
|
};
|
|
885
956
|
}
|
|
886
|
-
|
|
957
|
+
function stagingFilePath(prefix, issuer) {
|
|
887
958
|
let host = "instance";
|
|
888
959
|
try {
|
|
889
960
|
host = new URL(issuer).hostname;
|
|
@@ -892,28 +963,45 @@ export function defaultSecretsStagingPath(issuer) {
|
|
|
892
963
|
/* fall through to the generic name */
|
|
893
964
|
}
|
|
894
965
|
const safe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
|
|
895
|
-
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);
|
|
896
980
|
}
|
|
897
981
|
/** Write the secrets bundle to a 0600 staging file, `KEY=VALUE` per line.
|
|
898
982
|
* This file legitimately carries secret material (like `grant`'s 0600 key
|
|
899
983
|
* files) — the "never print secret values" rule is about stdout/returned
|
|
900
|
-
* result objects, not this deliberately-created, permission-locked file.
|
|
901
|
-
|
|
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 = {}) {
|
|
902
991
|
mkdirSync(dirname(path), { recursive: true });
|
|
903
992
|
const body = Object.entries(bundle).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
|
|
904
|
-
writeFileSync(path, body, { mode: 0o600 });
|
|
993
|
+
writeFileSync(path, body, { mode: 0o600, flag: opts.exclusive ? "wx" : "w" });
|
|
905
994
|
chmodSync(path, 0o600);
|
|
906
995
|
}
|
|
907
996
|
/** Provision secrets per the shape-aware mechanism, staging the bundle to a
|
|
908
997
|
* 0600 file and returning ONLY names/paths/instructions — never values. */
|
|
909
998
|
export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
910
|
-
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism);
|
|
999
|
+
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism, opts.fabric);
|
|
911
1000
|
const path = opts.stagingPath ?? defaultSecretsStagingPath(instanceUrl);
|
|
912
1001
|
writeSecretsStagingFile(path, bundle);
|
|
913
1002
|
const varNames = Object.keys(bundle);
|
|
914
1003
|
const instructions = mechanism === "fabric-env-secrets"
|
|
915
|
-
? `
|
|
916
|
-
`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.`
|
|
917
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.`;
|
|
918
1006
|
return { mechanism, path, varNames, instructions };
|
|
919
1007
|
}
|
|
@@ -940,40 +1028,124 @@ export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
|
940
1028
|
* one rather than being handed a 404 about something else.
|
|
941
1029
|
*/
|
|
942
1030
|
export const HOSTED_OPS_PORT = 9925;
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
if (typeof target === "number")
|
|
947
|
-
return `http://127.0.0.1:${target}/`;
|
|
948
|
-
// A string target is the SERVED origin. Its own port serves the REST surface,
|
|
949
|
-
// 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) {
|
|
950
1034
|
try {
|
|
951
|
-
const u = new URL(
|
|
1035
|
+
const u = new URL(servedOrigin.includes("://") ? servedOrigin : `https://${servedOrigin}`);
|
|
952
1036
|
u.port = String(HOSTED_OPS_PORT);
|
|
953
1037
|
u.pathname = "/";
|
|
954
1038
|
u.search = "";
|
|
955
|
-
return u
|
|
1039
|
+
return u;
|
|
956
1040
|
}
|
|
957
1041
|
catch {
|
|
958
|
-
|
|
959
|
-
// let the caller's error path name the remedy.
|
|
960
|
-
return `${target.replace(/\/+$/, "")}/`;
|
|
1042
|
+
return null;
|
|
961
1043
|
}
|
|
962
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
|
+
}
|
|
963
1056
|
function opsBaseUrl(opsPortOrUrl) {
|
|
964
1057
|
return resolveOpsUrl(opsPortOrUrl);
|
|
965
1058
|
}
|
|
966
1059
|
function basicAuthHeader(adminUser, adminPass) {
|
|
967
1060
|
return `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
|
|
968
1061
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
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
|
+
}
|
|
976
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`);
|
|
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. */
|
|
977
1149
|
/**
|
|
978
1150
|
* Map the operator's IdP subject to their principal via `Credential(kind:
|
|
979
1151
|
* "idp")` — the SAME credential surface resources/mcp-handler.ts's
|
|
@@ -981,9 +1153,14 @@ function isResolvableCredential(cred) {
|
|
|
981
1153
|
*
|
|
982
1154
|
* ## The uniqueness constraint (flair#1317, K&S ruling 2026-08-21)
|
|
983
1155
|
*
|
|
984
|
-
* **
|
|
985
|
-
*
|
|
986
|
-
*
|
|
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.
|
|
987
1164
|
*
|
|
988
1165
|
* It used to dedup on `(kind, idpProvider, idpSubject)` while the resolver read
|
|
989
1166
|
* `(kind, idpSubject)`. A re-link under a different provider name therefore
|
|
@@ -996,17 +1173,20 @@ function isResolvableCredential(cred) {
|
|
|
996
1173
|
* stays on the row as audit/diagnostic metadata, but it does not participate in
|
|
997
1174
|
* uniqueness. So:
|
|
998
1175
|
*
|
|
999
|
-
* - same provider, existing active credential → RE-POINT
|
|
1000
|
-
*
|
|
1001
|
-
*
|
|
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
|
|
1002
1181
|
* (revoked rows are never reused here — a re-link after a revoke mints a
|
|
1003
1182
|
* fresh credential);
|
|
1004
1183
|
* - the re-point/insert and every revocation go out as ONE ops-API `upsert`
|
|
1005
|
-
* batch, so there is no observable window with two active
|
|
1006
|
-
* 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;
|
|
1007
1187
|
* - after the write the invariant is RE-READ and asserted. A store that
|
|
1008
|
-
* somehow holds ≠1 active credential for the subject is a
|
|
1009
|
-
* silent nondeterministic mapping.
|
|
1188
|
+
* somehow holds ≠1 active, principal-bearing credential for the subject is a
|
|
1189
|
+
* hard error, not a silent nondeterministic mapping.
|
|
1010
1190
|
*
|
|
1011
1191
|
* The principal Agent is created only if missing.
|
|
1012
1192
|
*
|
|
@@ -1019,22 +1199,24 @@ function isResolvableCredential(cred) {
|
|
|
1019
1199
|
* so the operator is told, not so the event is hidden.
|
|
1020
1200
|
*/
|
|
1021
1201
|
export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
1202
|
+
const target = identityMappingOpsUrl(params);
|
|
1203
|
+
const opsUrl = target.url;
|
|
1022
1204
|
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1023
|
-
const
|
|
1024
|
-
const
|
|
1205
|
+
const clock = deps.now ?? (() => new Date().toISOString());
|
|
1206
|
+
const now = clock();
|
|
1025
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
|
+
}
|
|
1026
1214
|
// Ensure the principal Agent exists.
|
|
1215
|
+
const agentQuery = mappingReadQuery("Agent", { id: params.principal });
|
|
1027
1216
|
const findRes = await fetchImpl(opsUrl, {
|
|
1028
1217
|
method: "POST",
|
|
1029
|
-
headers:
|
|
1030
|
-
body: JSON.stringify(
|
|
1031
|
-
operation: "search_by_value",
|
|
1032
|
-
database: "flair",
|
|
1033
|
-
table: "Agent",
|
|
1034
|
-
search_attribute: "id",
|
|
1035
|
-
search_value: params.principal,
|
|
1036
|
-
get_attributes: ["id"],
|
|
1037
|
-
}),
|
|
1218
|
+
headers: opsHeaders(authHeader),
|
|
1219
|
+
body: JSON.stringify(agentQuery),
|
|
1038
1220
|
});
|
|
1039
1221
|
if (!findRes.ok) {
|
|
1040
1222
|
const text = await findRes.text().catch(() => "");
|
|
@@ -1044,19 +1226,34 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1044
1226
|
// identity is absent — and saying "failed to look up principal 'x'" sends
|
|
1045
1227
|
// the reader to look at principals, which is where an evening goes.
|
|
1046
1228
|
//
|
|
1047
|
-
//
|
|
1048
|
-
//
|
|
1049
|
-
//
|
|
1050
|
-
//
|
|
1051
|
-
// name an --ops-url flag that does not exist).
|
|
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.
|
|
1052
1233
|
const hint = findRes.status === 404
|
|
1053
|
-
?
|
|
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}.`
|
|
1054
1237
|
: "";
|
|
1055
1238
|
throw new Error(`Identity mapping: the ops API call to ${opsUrl} failed (HTTP ${findRes.status})${hint}${text ? `: ${text}` : ""}`);
|
|
1056
1239
|
}
|
|
1057
|
-
|
|
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
|
+
}
|
|
1058
1245
|
let principalCreated = false;
|
|
1059
|
-
|
|
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));
|
|
1060
1257
|
const insertRes = await fetchImpl(opsUrl, {
|
|
1061
1258
|
method: "POST",
|
|
1062
1259
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -1072,8 +1269,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1072
1269
|
kind: params.principalKind,
|
|
1073
1270
|
type: params.principalKind,
|
|
1074
1271
|
status: "active",
|
|
1272
|
+
publicKey: `idp:${params.idpProvider}:${params.idpSubject}`,
|
|
1075
1273
|
admin: false,
|
|
1076
1274
|
defaultTrustTier: "endorsed",
|
|
1275
|
+
originatorInstanceId: principalHome,
|
|
1077
1276
|
createdAt: now,
|
|
1078
1277
|
updatedAt: now,
|
|
1079
1278
|
},
|
|
@@ -1085,31 +1284,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1085
1284
|
throw new Error(`Identity mapping: failed to create principal '${params.principal}' (HTTP ${insertRes.status}): ${text}`);
|
|
1086
1285
|
}
|
|
1087
1286
|
principalCreated = true;
|
|
1287
|
+
preflight.principalPresent = true;
|
|
1088
1288
|
}
|
|
1089
|
-
// ── flair#1317: look SUBJECT-WIDE, not (provider, subject) ─────────────────
|
|
1090
|
-
// The resolver's key is (kind, idpSubject); anything narrower here leaves
|
|
1091
|
-
// credentials that dedup cannot see but resolution can.
|
|
1092
|
-
const findCredentialsForSubject = async () => {
|
|
1093
|
-
const res = await fetchImpl(opsUrl, {
|
|
1094
|
-
method: "POST",
|
|
1095
|
-
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
1096
|
-
body: JSON.stringify({
|
|
1097
|
-
operation: "search_by_conditions",
|
|
1098
|
-
database: "flair",
|
|
1099
|
-
table: "Credential",
|
|
1100
|
-
operator: "and",
|
|
1101
|
-
conditions: [
|
|
1102
|
-
{ search_attribute: "kind", search_type: "equals", search_value: "idp" },
|
|
1103
|
-
{ search_attribute: "idpSubject", search_type: "equals", search_value: params.idpSubject },
|
|
1104
|
-
],
|
|
1105
|
-
get_attributes: ["id", "principalId", "idpProvider", "idpSubject", "status", "label", "createdAt"],
|
|
1106
|
-
}),
|
|
1107
|
-
});
|
|
1108
|
-
const body = res.ok ? await res.json().catch(() => []) : [];
|
|
1109
|
-
return Array.isArray(body) ? body : [];
|
|
1110
|
-
};
|
|
1111
|
-
const subjectCreds = await findCredentialsForSubject();
|
|
1112
|
-
const activeCreds = subjectCreds.filter(isResolvableCredential);
|
|
1113
1289
|
// Survivor: an ACTIVE same-provider credential is re-pointed (the idempotent
|
|
1114
1290
|
// re-run and the documented same-provider link). A revoked one is never
|
|
1115
1291
|
// resurrected — a re-link after a revoke mints a fresh credential.
|
|
@@ -1123,6 +1299,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1123
1299
|
// ops-API operation is the strongest atomicity this surface can express, and
|
|
1124
1300
|
// ordering the survivor first means even a partially-applied batch can never
|
|
1125
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();
|
|
1126
1306
|
const upsertRes = await fetchImpl(opsUrl, {
|
|
1127
1307
|
method: "POST",
|
|
1128
1308
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -1139,8 +1319,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1139
1319
|
status: "active",
|
|
1140
1320
|
idpProvider: params.idpProvider,
|
|
1141
1321
|
idpSubject: params.idpSubject,
|
|
1142
|
-
createdAt: reused ?
|
|
1143
|
-
lastUsedAt:
|
|
1322
|
+
createdAt: typeof reused?.createdAt === "string" ? reused.createdAt : writtenAt,
|
|
1323
|
+
lastUsedAt: writtenAt,
|
|
1144
1324
|
},
|
|
1145
1325
|
// Retained, not deleted: the revocation stays legible in storage and in
|
|
1146
1326
|
// Harper's table audit log (which records the full record image of
|
|
@@ -1155,8 +1335,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1155
1335
|
status: "revoked",
|
|
1156
1336
|
idpProvider: c.idpProvider,
|
|
1157
1337
|
idpSubject: params.idpSubject,
|
|
1158
|
-
createdAt: c.createdAt,
|
|
1159
|
-
updatedAt:
|
|
1338
|
+
createdAt: typeof c.createdAt === "string" ? c.createdAt : writtenAt,
|
|
1339
|
+
updatedAt: writtenAt,
|
|
1160
1340
|
})),
|
|
1161
1341
|
],
|
|
1162
1342
|
}),
|
|
@@ -1170,14 +1350,9 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1170
1350
|
// ≠1 active credential means the resolver's answer for this subject is
|
|
1171
1351
|
// order-dependent, so this fails LOUDLY rather than returning a mapping the
|
|
1172
1352
|
// operator would reasonably believe is deterministic.
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
throw new Error(`Identity mapping: the uniqueness invariant does not hold after the write — subject '${params.idpSubject}' ` +
|
|
1177
|
-
`has ${afterCreds.length} active Credential(kind:idp) row(s) [${seen}], expected exactly 1 (${credentialId}). ` +
|
|
1178
|
-
`Runtime resolution for this subject would be iteration-order-dependent (flair#1317). ` +
|
|
1179
|
-
`Inspect the Credential table for kind:"idp" idpSubject:"${params.idpSubject}" and revoke the rows that should not resolve.`);
|
|
1180
|
-
}
|
|
1353
|
+
await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, {
|
|
1354
|
+
id: credentialId, principalId: params.principal, idpProvider: params.idpProvider, status: "active",
|
|
1355
|
+
});
|
|
1181
1356
|
return {
|
|
1182
1357
|
principalCreated,
|
|
1183
1358
|
credentialId,
|
|
@@ -1186,6 +1361,349 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1186
1361
|
supersededCredentialIds: superseded.map((c) => String(c.id)),
|
|
1187
1362
|
};
|
|
1188
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
|
+
}
|
|
1189
1707
|
// ─── Restart only ────────────────────────────────────────────────────────────
|
|
1190
1708
|
/** `restart` only — used by `disableMcp` (flag off + restart, no config
|
|
1191
1709
|
* rewrite: the `@harperfast/oauth` config block is left in place; it is
|
|
@@ -1221,18 +1739,42 @@ async function fetchOAuthMetadata(origin, deps = {}) {
|
|
|
1221
1739
|
return { ok: false, unreachable: true, detail: `could not reach ${url}: ${err?.message ?? err}` };
|
|
1222
1740
|
}
|
|
1223
1741
|
if (deps.redirect === "manual" && (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400))) {
|
|
1224
|
-
return { ok: false, detail: "--instance answered with a redirect; point --instance at the instance itself." };
|
|
1742
|
+
return { ok: false, status: res.status, detail: "--instance answered with a redirect; point --instance at the instance itself." };
|
|
1225
1743
|
}
|
|
1226
1744
|
if (!res.ok) {
|
|
1227
|
-
return { ok: false, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
|
|
1745
|
+
return { ok: false, status: res.status, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
|
|
1228
1746
|
}
|
|
1229
1747
|
try {
|
|
1230
|
-
return { ok: true, url, body: await res.json() };
|
|
1748
|
+
return { ok: true, url, status: res.status, body: await res.json() };
|
|
1231
1749
|
}
|
|
1232
1750
|
catch {
|
|
1233
|
-
return { ok: false, detail: `${url} did not return JSON` };
|
|
1751
|
+
return { ok: false, status: res.status, detail: `${url} did not return JSON` };
|
|
1234
1752
|
}
|
|
1235
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
|
+
}
|
|
1236
1778
|
async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
1237
1779
|
const target = await fetchOAuthMetadata(instance, { ...deps, redirect: "manual" });
|
|
1238
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\`.`;
|
|
@@ -1243,7 +1785,7 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1243
1785
|
const found = typeof actual === "string" ? `names issuer=${JSON.stringify(actual)}` : `has no string issuer (got ${JSON.stringify(actual)})`;
|
|
1244
1786
|
return { ok: false, detail: `The target's own metadata at ${target.url} ${found}; expected ${issuer}. ${remedy}` };
|
|
1245
1787
|
}
|
|
1246
|
-
if (target.body?.token_endpoint !==
|
|
1788
|
+
if (target.body?.token_endpoint !== mcpTokenEndpoint(issuer)) {
|
|
1247
1789
|
return {
|
|
1248
1790
|
ok: false,
|
|
1249
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\`.`,
|
|
@@ -1251,6 +1793,143 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1251
1793
|
}
|
|
1252
1794
|
return { ok: true, detail: `Issuer ${issuer} matched the target's own OAuth authorization-server metadata at ${target.url}` };
|
|
1253
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
|
+
};
|
|
1824
|
+
}
|
|
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
|
+
};
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1254
1933
|
/**
|
|
1255
1934
|
* Hit the OAuth metadata endpoint from the operator's machine against the
|
|
1256
1935
|
* PUBLIC origin — the verification that matters is the one claude.ai's
|
|
@@ -1259,41 +1938,40 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1259
1938
|
* advertise CIMD support, is `ok: false` with a specific `detail`.
|
|
1260
1939
|
*
|
|
1261
1940
|
* flair#756: since CIMD is the only supported client-registration path now,
|
|
1262
|
-
*
|
|
1263
|
-
*
|
|
1264
|
-
* self-verify step, `grant`/`revoke`'s workflow gate
|
|
1265
|
-
* `flair mcp status`, so all four commands
|
|
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.
|
|
1266
1946
|
*/
|
|
1267
1947
|
export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
1268
1948
|
const normalizedIssuer = issuer.replace(/\/+$/, "");
|
|
1269
|
-
|
|
1270
|
-
if (metadata.ok === false)
|
|
1271
|
-
return metadata;
|
|
1272
|
-
const { url, body } = metadata;
|
|
1273
|
-
// ── The flair's-own-server check runs BEFORE the shape check (flair#1094) ──
|
|
1949
|
+
// ── The discriminator runs BEFORE the shape check (flair#1094, flair#2283) ──
|
|
1274
1950
|
//
|
|
1275
|
-
//
|
|
1276
|
-
//
|
|
1277
|
-
// which it is not by default — so the shape check fired first and returned
|
|
1278
|
-
// "the metadata shape is unexpected", which is true, useless, and points at
|
|
1279
|
-
// 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.
|
|
1280
1953
|
//
|
|
1281
|
-
//
|
|
1282
|
-
//
|
|
1283
|
-
//
|
|
1284
|
-
|
|
1285
|
-
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") {
|
|
1286
1965
|
return {
|
|
1287
1966
|
ok: false,
|
|
1288
|
-
issuer:
|
|
1289
|
-
registrationEndpoint: body?.registration_endpoint,
|
|
1290
|
-
tokenEndpoint:
|
|
1291
|
-
detail:
|
|
1292
|
-
`(token_endpoint=${body.token_endpoint}) — the /mcp surface is NOT enabled on that instance. ` +
|
|
1293
|
-
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
1294
|
-
`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),
|
|
1295
1971
|
};
|
|
1296
1972
|
}
|
|
1973
|
+
const url = observation.url;
|
|
1974
|
+
const body = observation.body;
|
|
1297
1975
|
// ── registration_endpoint is OPTIONAL and must not be required (Kern, #1101) ─
|
|
1298
1976
|
//
|
|
1299
1977
|
// Requiring it made self-verify fail on a CORRECTLY enabled instance — the
|
|
@@ -1327,25 +2005,6 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
1327
2005
|
detail: `${url} responded but the metadata shape is unexpected (issuer/token_endpoint) — got issuer=${JSON.stringify(body?.issuer)}`,
|
|
1328
2006
|
};
|
|
1329
2007
|
}
|
|
1330
|
-
// flair#1000: this path is now served by flair ITSELF when FLAIR_MCP_OAUTH is
|
|
1331
|
-
// off, so a 200 no longer proves the plugin answered. flair's own document
|
|
1332
|
-
// (resources/oauth-discovery.ts) is identifiable by its token endpoint —
|
|
1333
|
-
// `<issuer>/OAuthToken`, where the plugin's is `<issuer>/oauth/mcp/token`.
|
|
1334
|
-
// Name the real cause here: before this existed the operator got a 404 whose
|
|
1335
|
-
// message already asked the right question, and falling through to the CIMD
|
|
1336
|
-
// branch would send them to a plugin knob that is not the problem.
|
|
1337
|
-
if (body.token_endpoint === `${normalizedIssuer}/OAuthToken`) {
|
|
1338
|
-
return {
|
|
1339
|
-
ok: false,
|
|
1340
|
-
issuer: body.issuer,
|
|
1341
|
-
registrationEndpoint: body.registration_endpoint,
|
|
1342
|
-
tokenEndpoint: body.token_endpoint,
|
|
1343
|
-
detail: `${url} answered with flair's OWN OAuth 2.1 authorization server, not the MCP one ` +
|
|
1344
|
-
`(token_endpoint=${body.token_endpoint}) — the /mcp surface is NOT enabled on that instance. ` +
|
|
1345
|
-
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
1346
|
-
`component declared in its config.yaml?`,
|
|
1347
|
-
};
|
|
1348
|
-
}
|
|
1349
2008
|
// flair#756: confirm CIMD is actually advertised (node_modules/@harperfast/
|
|
1350
2009
|
// oauth/dist/lib/mcp/wellKnown.js:129-165's buildAuthorizationServerMetadata:
|
|
1351
2010
|
// `client_id_metadata_document_supported` is set only when
|
|
@@ -1365,6 +2024,22 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
1365
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?`,
|
|
1366
2025
|
};
|
|
1367
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
|
+
}
|
|
1368
2043
|
return {
|
|
1369
2044
|
ok: true,
|
|
1370
2045
|
issuer: body.issuer,
|
|
@@ -1461,6 +2136,20 @@ export async function captureBootDiscriminator(opsPortOrUrl, adminUser, adminPas
|
|
|
1461
2136
|
}
|
|
1462
2137
|
return { pid };
|
|
1463
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
|
+
}
|
|
1464
2153
|
/**
|
|
1465
2154
|
* Full `flair mcp enable` orchestration. No `process.exit`, no console
|
|
1466
2155
|
* output — directly unit-testable with a mocked fetch and temp dirs, same
|
|
@@ -1486,30 +2175,56 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1486
2175
|
//
|
|
1487
2176
|
// Initialised to the first step rather than left undefined so a throw before
|
|
1488
2177
|
// any assignment cannot be attributed to an arbitrary fallback name.
|
|
1489
|
-
let currentStep = "
|
|
2178
|
+
let currentStep = "target-shape-check";
|
|
1490
2179
|
const dryRun = Boolean(params.dryRun);
|
|
1491
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
|
+
}
|
|
1492
2187
|
// ── Local-origin refusal (scenario addendum, binding) ─────────────────────
|
|
1493
2188
|
currentStep = "local-origin-check";
|
|
1494
|
-
const
|
|
2189
|
+
const rawIssuer = params.issuer ?? params.instance;
|
|
2190
|
+
const issuer = rawIssuer.replace(/\/$/, "");
|
|
2191
|
+
const localCheck = checkLocalOriginRefusal(issuer);
|
|
1495
2192
|
if (localCheck.refused) {
|
|
1496
2193
|
push(false, localCheck.message);
|
|
1497
|
-
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" };
|
|
1498
2195
|
}
|
|
1499
|
-
push(true, `${
|
|
1500
|
-
const issuer = (params.issuer ?? params.instance).replace(/\/+$/, "");
|
|
2196
|
+
push(true, `${issuer}: URL parsed; hostname/IP-literal check passed (no DNS lookup)`);
|
|
1501
2197
|
const idpProvider = params.idpProvider ?? "github";
|
|
1502
2198
|
const principal = params.principal ?? "self";
|
|
1503
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);
|
|
1504
2211
|
try {
|
|
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
|
+
}
|
|
1505
2227
|
// ── --cimd-allowed-hosts (flair#2113) ─────────────────────────────────────
|
|
1506
|
-
// Before any step with a side effect: the hosts are validated, a Fabric
|
|
1507
|
-
// target is refused, the config.yaml to edit must exist with an
|
|
1508
|
-
// @harperfast/oauth mcp block, and (except under --dry-run, which skips it)
|
|
1509
|
-
// the preflight match must pass. Any of these failing refuses the flag with
|
|
1510
|
-
// nothing changed. The list itself is ensured
|
|
1511
|
-
// at local-config-update, before the restart: written unless the file
|
|
1512
|
-
// already holds that exact list, then read back.
|
|
1513
2228
|
let cimdAllowedHosts;
|
|
1514
2229
|
if (params.cimdAllowedHosts !== undefined) {
|
|
1515
2230
|
currentStep = "cimd-allowed-hosts";
|
|
@@ -1523,7 +2238,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1523
2238
|
catch (err) {
|
|
1524
2239
|
return refuse(err?.message ?? String(err));
|
|
1525
2240
|
}
|
|
1526
|
-
const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance);
|
|
2241
|
+
const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance, params.fabric);
|
|
1527
2242
|
if (shapeRefusal)
|
|
1528
2243
|
return refuse(shapeRefusal);
|
|
1529
2244
|
const current = readLocalConfigCimdAllowedHosts(params.localConfigPath);
|
|
@@ -1552,23 +2267,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1552
2267
|
`then reads it back; a run that stops before that step does not write it); ${target.detail}`);
|
|
1553
2268
|
}
|
|
1554
2269
|
}
|
|
1555
|
-
// ── RS256 signing keypair ─────────────────────────────────────────────────
|
|
1556
|
-
currentStep = "signing-key";
|
|
1557
|
-
// flair#2113 review: --dry-run writes no file, so it reports the key a real
|
|
1558
|
-
// run would reuse or generate instead of creating one. Same path and same
|
|
1559
|
-
// existence test as ensureSigningKeyFile.
|
|
1560
|
-
let keyResult;
|
|
1561
|
-
if (dryRun) {
|
|
1562
|
-
const keyPath = params.signingKeyFilePath ?? defaultSigningKeyFilePath();
|
|
1563
|
-
keyResult = { path: keyPath, reused: existsSync(keyPath) };
|
|
1564
|
-
push(true, keyResult.reused
|
|
1565
|
-
? `signing key found at ${keyPath}; a run without --dry-run reuses it`
|
|
1566
|
-
: `no signing key at ${keyPath}; a run without --dry-run generates one there (0600). --dry-run did not create it`);
|
|
1567
|
-
}
|
|
1568
|
-
else {
|
|
1569
|
-
keyResult = ensureSigningKeyFile(params.signingKeyFilePath, { generate: deps.generateRsaKeyPair });
|
|
1570
|
-
push(true, `signing key ${keyResult.reused ? "reused" : "generated"} at ${keyResult.path} (0600)`);
|
|
1571
|
-
}
|
|
1572
2270
|
// ── @harperfast/oauth config (flair#1136: shipped in config.yaml) ──────
|
|
1573
2271
|
// The block ships uncommented with mcp.enabled: ${FLAIR_MCP_OAUTH}
|
|
1574
2272
|
// (flair#1152), so the environment turns it on. This step writes nothing;
|
|
@@ -1597,8 +2295,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1597
2295
|
push(true, `${idpProvider} OAuth app credentials present; callback URL: ${callbackUrl}`);
|
|
1598
2296
|
if (dryRun) {
|
|
1599
2297
|
// Dry-run stops here. Under --dry-run nothing above wrote a file or made
|
|
1600
|
-
// a remote call
|
|
1601
|
-
// nothing below this line runs.
|
|
2298
|
+
// a remote call, and nothing below this line runs.
|
|
1602
2299
|
return {
|
|
1603
2300
|
ok: true,
|
|
1604
2301
|
dryRun: true,
|
|
@@ -1606,19 +2303,16 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1606
2303
|
issuer,
|
|
1607
2304
|
resource: `${issuer}/mcp`,
|
|
1608
2305
|
callbackUrl,
|
|
1609
|
-
signingKeyFilePath: keyResult.path,
|
|
1610
2306
|
};
|
|
1611
2307
|
}
|
|
1612
2308
|
// ── Secrets provisioning (shape-aware, never silent) ──────────────────────
|
|
1613
|
-
|
|
2309
|
+
currentStep = "secrets-provisioning";
|
|
1614
2310
|
const bundle = buildSecretsBundle({
|
|
1615
2311
|
issuer,
|
|
1616
|
-
signingKeyPem,
|
|
1617
2312
|
idpProvider,
|
|
1618
2313
|
idpClientId: params.idpClientId,
|
|
1619
2314
|
idpClientSecret: params.idpClientSecret,
|
|
1620
2315
|
});
|
|
1621
|
-
currentStep = "secrets-provisioning";
|
|
1622
2316
|
if (bundle.FLAIR_MCP_ISSUER !== issuer) {
|
|
1623
2317
|
throw new Error(`the FLAIR_MCP_ISSUER being pushed does not equal the issuer checked (${issuer})`);
|
|
1624
2318
|
}
|
|
@@ -1628,10 +2322,11 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1628
2322
|
// write; not staging costs an operator stranded mid-enable.
|
|
1629
2323
|
const secretsResult = provisionSecrets(params.instance, bundle, {
|
|
1630
2324
|
mechanism: params.secretsMechanism,
|
|
2325
|
+
fabric: params.fabric,
|
|
1631
2326
|
stagingPath: params.secretsStagingPath,
|
|
1632
2327
|
});
|
|
1633
2328
|
// Ask the TARGET whether it can take these, rather than inferring from its
|
|
1634
|
-
// hostname or its version
|
|
2329
|
+
// hostname or its version.
|
|
1635
2330
|
// An explicit --secrets-mechanism is an operator override and is honoured
|
|
1636
2331
|
// without a probe: they have said what they want.
|
|
1637
2332
|
let secretsPushed = false;
|
|
@@ -1664,7 +2359,9 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1664
2359
|
// ── Identity mapping (Credential kind:idp) ────────────────────────────────
|
|
1665
2360
|
currentStep = "identity-mapping";
|
|
1666
2361
|
const mapping = await provisionIdpIdentityMapping({
|
|
1667
|
-
|
|
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,
|
|
1668
2365
|
adminUser: params.adminUser,
|
|
1669
2366
|
adminPass: params.adminPass,
|
|
1670
2367
|
principal,
|
|
@@ -1681,12 +2378,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1681
2378
|
// credential (one active credential per subject is the invariant). That is
|
|
1682
2379
|
// a credential dying, so it is stated as such, by id: an operator must
|
|
1683
2380
|
// never discover it later from something that stopped working.
|
|
1684
|
-
const supersedeNote = mapping
|
|
1685
|
-
? ` SUPERSEDED: ${mapping.supersededCredentialIds.length} prior Credential(kind:idp) row(s) for this subject ` +
|
|
1686
|
-
`were REVOKED, not de-duplicated — ${mapping.supersededCredentialIds.join(", ")}. ` +
|
|
1687
|
-
`They no longer resolve, and anything relying on them stops working. ` +
|
|
1688
|
-
`Exactly one active credential per (kind, idpSubject) is the invariant that keeps resolution deterministic.`
|
|
1689
|
-
: "";
|
|
2381
|
+
const supersedeNote = supersededCredentialNote(mapping);
|
|
1690
2382
|
push(true, `connector identity: mapped sub '${params.idpSubject}' (provider '${idpProvider}') to Agent '${principal}'; ` +
|
|
1691
2383
|
`see docs/access-control.md for how /mcp tool calls use it. ` +
|
|
1692
2384
|
`principal ${mapping.principalCreated ? "created" : "already existed"}; ` +
|
|
@@ -1699,14 +2391,14 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1699
2391
|
let confirmed = Boolean(params.confirmSecretsApplied);
|
|
1700
2392
|
if (!confirmed && deps.confirmPrompt) {
|
|
1701
2393
|
confirmed = await deps.confirmPrompt(secretsPushed
|
|
1702
|
-
?
|
|
2394
|
+
? fabricTarget
|
|
1703
2395
|
? `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you restarted the Fabric instance to load them?`
|
|
1704
2396
|
: `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you loaded them into the instance's process environment?`
|
|
1705
2397
|
: `Have you applied the ${secretsResult.varNames.length} vars staged at ${secretsResult.path} to ${params.instance}'s environment?`);
|
|
1706
2398
|
}
|
|
1707
2399
|
if (!confirmed) {
|
|
1708
2400
|
push(false, secretsPushed
|
|
1709
|
-
? `not confirmed: the secrets were pushed to ${params.instance} and read back; ${
|
|
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.`
|
|
1710
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).`);
|
|
1711
2403
|
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path };
|
|
1712
2404
|
}
|
|
@@ -1721,8 +2413,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1721
2413
|
// - Fabric: `enable` does not restart the instance; the operator applies
|
|
1722
2414
|
// the environment and restarts. Report the requirement LOUDLY — never
|
|
1723
2415
|
// report success with /mcp still dark.
|
|
1724
|
-
|
|
1725
|
-
if (isFabric) {
|
|
2416
|
+
if (fabricTarget) {
|
|
1726
2417
|
// ── Fabric: operator-deploy requirement ──────────────────────────────
|
|
1727
2418
|
currentStep = "fabric-operator-deploy";
|
|
1728
2419
|
const host = new URL(params.instance).hostname;
|
|
@@ -1732,7 +2423,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1732
2423
|
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
1733
2424
|
if (!binding.ok) {
|
|
1734
2425
|
push(false, binding.detail);
|
|
1735
|
-
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "issuer-target-binding", issuer, resource: `${issuer}/mcp`, secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path,
|
|
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 };
|
|
1736
2427
|
}
|
|
1737
2428
|
currentStep = "fabric-operator-deploy";
|
|
1738
2429
|
// The target's metadata names the issuer. Now check the public origin.
|
|
@@ -1752,7 +2443,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1752
2443
|
pasteBlock: buildClaudePasteBlock(resource),
|
|
1753
2444
|
secretsMechanism: secretsResult.mechanism,
|
|
1754
2445
|
secretsPath: secretsResult.path,
|
|
1755
|
-
signingKeyFilePath: keyResult.path,
|
|
1756
2446
|
callbackUrl,
|
|
1757
2447
|
};
|
|
1758
2448
|
}
|
|
@@ -1785,14 +2475,33 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1785
2475
|
resource: `${issuer}/mcp`,
|
|
1786
2476
|
secretsMechanism: secretsResult.mechanism,
|
|
1787
2477
|
secretsPath: secretsResult.path,
|
|
1788
|
-
signingKeyFilePath: keyResult.path,
|
|
1789
2478
|
callbackUrl,
|
|
1790
2479
|
};
|
|
1791
2480
|
}
|
|
1792
2481
|
// ── Standalone (non-Fabric): update local config + restart ────────────
|
|
1793
2482
|
currentStep = "local-config-update";
|
|
1794
2483
|
const localConfigResult = updateLocalConfigMcpEnabled(true, params.localConfigPath);
|
|
1795
|
-
|
|
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);
|
|
1796
2505
|
// flair#2113: ensure --cimd-allowed-hosts (written unless the file already
|
|
1797
2506
|
// holds that exact list) and read it back. A failure here stops the flow
|
|
1798
2507
|
// before the restart.
|
|
@@ -1812,7 +2521,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1812
2521
|
resource: `${issuer}/mcp`,
|
|
1813
2522
|
secretsMechanism: secretsResult.mechanism,
|
|
1814
2523
|
secretsPath: secretsResult.path,
|
|
1815
|
-
signingKeyFilePath: keyResult.path,
|
|
1816
2524
|
callbackUrl,
|
|
1817
2525
|
};
|
|
1818
2526
|
}
|
|
@@ -1837,7 +2545,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1837
2545
|
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
1838
2546
|
if (!binding.ok) {
|
|
1839
2547
|
push(false, binding.detail);
|
|
1840
|
-
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "self-verify", issuer, resource: `${issuer}/mcp`, secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path,
|
|
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 };
|
|
1841
2549
|
}
|
|
1842
2550
|
const verify = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
|
|
1843
2551
|
if (!verify.ok) {
|
|
@@ -1864,7 +2572,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1864
2572
|
pasteBlock: buildClaudePasteBlock(resource),
|
|
1865
2573
|
secretsMechanism: secretsResult.mechanism,
|
|
1866
2574
|
secretsPath: secretsResult.path,
|
|
1867
|
-
signingKeyFilePath: keyResult.path,
|
|
1868
2575
|
callbackUrl,
|
|
1869
2576
|
cimdAllowedHosts: writtenCimd?.hosts,
|
|
1870
2577
|
cimdAllowedHostsConfigPath: writtenCimd?.path,
|
|
@@ -1882,8 +2589,8 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1882
2589
|
// Two results for one step, and the ✓ instructs several minutes of manual
|
|
1883
2590
|
// work in a web UI that the ✗ makes pointless. Read in order, you do the
|
|
1884
2591
|
// work first.
|
|
1885
|
-
// No
|
|
1886
|
-
//
|
|
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
|
|
1887
2594
|
// would attribute a throw to a step chosen for being a plausible default —
|
|
1888
2595
|
// the same misattribution this handler exists to prevent, one layer down.
|
|
1889
2596
|
push(false, `unexpected error: ${err?.message ?? err}`);
|
|
@@ -1922,12 +2629,147 @@ export async function disableMcp(params, deps = {}) {
|
|
|
1922
2629
|
return { ok: true, detail: `restart requested for ${params.instance}` };
|
|
1923
2630
|
}
|
|
1924
2631
|
/**
|
|
1925
|
-
*
|
|
1926
|
-
*
|
|
1927
|
-
*
|
|
1928
|
-
*
|
|
1929
|
-
*
|
|
1930
|
-
*
|
|
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
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
/**
|
|
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.
|
|
1931
2773
|
*/
|
|
1932
2774
|
export async function mcpStatus(params, deps = {}) {
|
|
1933
2775
|
const verify = await selfVerifyMcpMetadata(params.instance, { fetchImpl: deps.fetchImpl });
|