@tpsdev-ai/flair 0.59.0 → 0.63.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 +10 -10
- package/SECURITY.md +49 -5
- package/config.yaml +23 -12
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/execute.js +1 -0
- 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/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1054 -367
- package/dist/commands/agent.js +233 -90
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +211 -39
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +71 -8
- package/dist/commands/doctor.js +711 -146
- package/dist/commands/export.js +57 -23
- package/dist/commands/federation.js +787 -82
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +27 -19
- package/dist/commands/import.js +136 -20
- package/dist/commands/init.js +469 -200
- package/dist/commands/integrity.js +387 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +108 -52
- package/dist/commands/memory.js +203 -35
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +51 -47
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +428 -62
- package/dist/commands/quality.js +13 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +537 -80
- package/dist/commands/restore.js +413 -65
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +235 -40
- package/dist/commands/soul.js +4 -9
- package/dist/commands/status.js +94 -38
- package/dist/commands/test.js +7 -3
- package/dist/commands/upgrade.js +77 -23
- package/dist/commands/workspace.js +13 -11
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +136 -4
- package/dist/doctor-client.js +534 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +273 -180
- package/dist/hook-install.js +670 -6
- package/dist/install/clients.js +171 -35
- 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 +88 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1069 -60
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +43 -11
- 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/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -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/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +38 -3
- 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 +1182 -341
- 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 +4 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/ops-url.js +52 -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/promotion-content-hash.js +20 -0
- 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-archive.js +760 -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-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +448 -0
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +114 -14
- package/dist/memory-id-checkpoint.js +347 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +303 -26
- package/dist/rem/runner.js +317 -96
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +463 -33
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +248 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +238 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -78
- package/dist/resources/Credential.js +183 -10
- package/dist/resources/Federation.js +915 -145
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +3300 -758
- package/dist/resources/MemoryArchive.js +171 -53
- package/dist/resources/MemoryBootstrap.js +122 -61
- package/dist/resources/MemoryCandidate.js +37 -3
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +545 -50
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +368 -46
- package/dist/resources/MemoryPurge.js +348 -0
- package/dist/resources/MemoryReflect.js +71 -12
- package/dist/resources/MemoryReindex.js +111 -17
- package/dist/resources/Message.js +16 -5
- package/dist/resources/OAuth.js +342 -48
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +405 -19
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +166 -51
- package/dist/resources/PromoteMemoryCandidate.js +24 -7
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +191 -76
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +207 -63
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +138 -83
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +534 -171
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +161 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +60 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +163 -22
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +587 -0
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +141 -19
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +450 -56
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +187 -40
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +4 -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 +144 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +32 -7
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +489 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +90 -19
- package/dist/resources/migrations/dir-safety.js +61 -3
- package/dist/resources/migrations/embedding-stamp.js +462 -82
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +27 -27
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +870 -77
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +81 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +113 -72
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +40 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -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 +256 -0
- package/dist/resources/owner-scoped-writes.js +89 -0
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +143 -17
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-type-kit.js +2 -4
- 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 +163 -0
- package/dist/resources/request-transaction.js +46 -1
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +116 -0
- package/dist/resources/semantic-retrieval-core.js +27 -15
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +24 -14
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +789 -0
- package/dist/resources/skill-write-fault.js +20 -0
- package/dist/resources/skill-write-policy.js +68 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -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 +235 -0
- package/dist/resources/usage-recording.js +186 -70
- package/dist/resources/write-back.js +383 -0
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -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 +88 -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/federation-retry-row.js +101 -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/instruction-event-contract.js +17 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +4 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/open-live-row.js +20 -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/soul-scope-fields.js +26 -0
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +164 -54
- package/docs/api-reference.md +165 -32
- package/docs/auth.md +46 -30
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +37 -7
- package/docs/deploying-on-fabric.md +178 -0
- package/docs/deployment.md +19 -0
- package/docs/embedding-in-a-harper-app.md +17 -15
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +61 -3
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +14 -14
- package/docs/mcp-clients.md +12 -7
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +16 -13
- package/docs/notes/mcp-oauth-model2.md +40 -11
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +4 -4
- package/docs/quickstart.md +12 -4
- package/docs/releasing.md +25 -19
- package/docs/rem.md +32 -3
- package/docs/secrets-and-keys.md +21 -4
- package/docs/standalone-local.md +30 -2
- package/docs/supply-chain-policy.md +34 -16
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +46 -6
- package/package.json +24 -12
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +6 -3
- package/schemas/federation.graphql +41 -1
- package/schemas/memory.graphql +91 -7
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
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,18 +476,25 @@ 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: {
|
|
437
488
|
// flair#1152: whole-token env reference — same flag flair's in-process
|
|
438
|
-
// route gates on. ASYMMETRY (load-bearing, measured on
|
|
439
|
-
// the component's coerceConfigBoolean
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
//
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
//
|
|
489
|
+
// route gates on. ASYMMETRY (load-bearing, measured on
|
|
490
|
+
// @harperfast/oauth 2.9.0): the component's coerceConfigBoolean trims
|
|
491
|
+
// and lowercases, mapping "true"/"false" to a boolean, and
|
|
492
|
+
// normalizeBooleanField deletes strings it cannot coerce (unresolved
|
|
493
|
+
// placeholder, "1", "yes", garbage), so its disabled default applies
|
|
494
|
+
// (dist/lib/config.js); flair's mcpOAuthEnabled()
|
|
495
|
+
// (resources/mcp-oauth-flag.ts) accepts 1/true/yes/on. Both readers
|
|
496
|
+
// accept "true". "1"/"yes"/"on" leave the component AS off; /mcp is
|
|
497
|
+
// not mounted. Garbage and an unset variable disable both. On oauth
|
|
446
498
|
// <2.5.0 there is NO normalization and an unresolved placeholder is a
|
|
447
499
|
// truthy string (fail-open) — which is why the resolved-version
|
|
448
500
|
// assertion in mcp-oauth-boot-safety.test.ts exists. If component
|
|
@@ -467,7 +519,8 @@ export function buildMcpOAuthConfigBlock(params) {
|
|
|
467
519
|
// resolution still runs cimd.js's full SSRF/document-validation
|
|
468
520
|
// pipeline regardless of this list.
|
|
469
521
|
clientIdMetadataDocuments: { allowedHosts: cimdAllowedHosts },
|
|
470
|
-
signingKeyPem
|
|
522
|
+
// Without signingKeyPem, minting reuses a persisted key or generates
|
|
523
|
+
// and persists one if oauth.harper_oauth_mcp_keys is empty.
|
|
471
524
|
},
|
|
472
525
|
},
|
|
473
526
|
};
|
|
@@ -501,8 +554,7 @@ function resolveLocalConfigPath(explicitPath) {
|
|
|
501
554
|
* to the reference). `enabled: false` writes literal `false` — decisively off
|
|
502
555
|
* regardless of environment.
|
|
503
556
|
*
|
|
504
|
-
*
|
|
505
|
-
* `~/.flair/config.yaml`.
|
|
557
|
+
* Uses `explicitPath` alone if given; otherwise `./config.yaml`, then `~/.flair/config.yaml`.
|
|
506
558
|
*/
|
|
507
559
|
export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
508
560
|
const { configPath, candidates } = resolveLocalConfigPath(explicitPath);
|
|
@@ -514,7 +566,11 @@ export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
|
|
|
514
566
|
return {
|
|
515
567
|
ok: false,
|
|
516
568
|
detail: `local config.yaml not found (tried: ${candidates.join(", ")}). ` +
|
|
517
|
-
|
|
569
|
+
(enabled
|
|
570
|
+
? explicitPath
|
|
571
|
+
? `Place your component config.yaml at ${explicitPath}, then re-run with the same explicit path.`
|
|
572
|
+
: `Re-run \`flair mcp enable\` from the directory that holds your component config.yaml (or place it at ${candidates[1]}).`
|
|
573
|
+
: `Set mcp.enabled: ${targetLabel} in your component config.yaml manually, then restart.`),
|
|
518
574
|
};
|
|
519
575
|
}
|
|
520
576
|
let raw;
|
|
@@ -863,27 +919,41 @@ function safeYamlLoad(text) {
|
|
|
863
919
|
export function idpCallbackUrl(issuer, idpProvider) {
|
|
864
920
|
return `${issuer.replace(/\/+$/, "")}/oauth/${idpProvider}/callback`;
|
|
865
921
|
}
|
|
922
|
+
export class IdpRedirectOriginError extends Error {
|
|
923
|
+
constructor(envPrefix) {
|
|
924
|
+
super(`Cannot stage ${envPrefix}_CLIENT_ID and ${envPrefix}_CLIENT_SECRET: ${envPrefix}_REDIRECT_URI requires a known HTTP(S) issuer origin.`);
|
|
925
|
+
this.name = "IdpRedirectOriginError";
|
|
926
|
+
}
|
|
927
|
+
}
|
|
866
928
|
/** The full set of env vars the restarted instance needs live. Contains
|
|
867
929
|
* secret VALUES — this is the one place they exist as a JS object; callers
|
|
868
930
|
* must never fold this into a CLI-printed / `EnableMcpResult` field. */
|
|
869
931
|
export function buildSecretsBundle(params) {
|
|
870
932
|
const envPrefix = `OAUTH_${params.idpProvider.toUpperCase()}`;
|
|
933
|
+
let origin;
|
|
934
|
+
try {
|
|
935
|
+
const url = new URL(params.issuer);
|
|
936
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
937
|
+
throw new IdpRedirectOriginError(envPrefix);
|
|
938
|
+
origin = url.origin;
|
|
939
|
+
}
|
|
940
|
+
catch {
|
|
941
|
+
throw new IdpRedirectOriginError(envPrefix);
|
|
942
|
+
}
|
|
871
943
|
return {
|
|
872
|
-
// "true" is the
|
|
873
|
-
//
|
|
874
|
-
//
|
|
875
|
-
//
|
|
876
|
-
//
|
|
877
|
-
// component's AS stays OFF — fail-closed but broken-on (every request
|
|
878
|
-
// 401s, no AS is advertised). Keep this "true".
|
|
944
|
+
// "true" is the recommended value both readers of this flag accept
|
|
945
|
+
// (flair#1152): flair's strict mcpOAuthEnabled() takes 1/true/yes/on, but
|
|
946
|
+
// the component's coerceConfigBoolean maps only true/false strings
|
|
947
|
+
// (trimmed, any case) to a boolean and returns undefined otherwise, and
|
|
948
|
+
// normalizeBooleanField then deletes the field (disabled default applies).
|
|
879
949
|
FLAIR_MCP_OAUTH: "true",
|
|
880
950
|
FLAIR_MCP_ISSUER: params.issuer.replace(/\/+$/, ""),
|
|
881
|
-
FLAIR_MCP_SIGNING_KEY_PEM: params.signingKeyPem,
|
|
882
951
|
[`${envPrefix}_CLIENT_ID`]: params.idpClientId,
|
|
883
952
|
[`${envPrefix}_CLIENT_SECRET`]: params.idpClientSecret,
|
|
953
|
+
[`${envPrefix}_REDIRECT_URI`]: `${origin}/oauth`,
|
|
884
954
|
};
|
|
885
955
|
}
|
|
886
|
-
|
|
956
|
+
function stagingFilePath(prefix, issuer) {
|
|
887
957
|
let host = "instance";
|
|
888
958
|
try {
|
|
889
959
|
host = new URL(issuer).hostname;
|
|
@@ -892,28 +962,45 @@ export function defaultSecretsStagingPath(issuer) {
|
|
|
892
962
|
/* fall through to the generic name */
|
|
893
963
|
}
|
|
894
964
|
const safe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
|
|
895
|
-
return join(resolveHome(), ".flair",
|
|
965
|
+
return join(resolveHome(), ".flair", `${prefix}-${safe}.env`);
|
|
966
|
+
}
|
|
967
|
+
export function defaultSecretsStagingPath(issuer) {
|
|
968
|
+
return stagingFilePath("mcp-enable-secrets", issuer);
|
|
969
|
+
}
|
|
970
|
+
/** The staging file `--refresh-flag` uses when the caller names none.
|
|
971
|
+
*
|
|
972
|
+
* DELIBERATELY a different filename from `defaultSecretsStagingPath`'s. The two
|
|
973
|
+
* commands stage different bundles — `enable` the full IdP credentials bundle,
|
|
974
|
+
* refresh the single `FLAIR_MCP_OAUTH` variable — and while they shared a path a
|
|
975
|
+
* refresh could truncate a credentials bundle a previous `mcp enable` had staged
|
|
976
|
+
* and not yet applied (flair#2283). */
|
|
977
|
+
export function defaultRefreshSecretsStagingPath(issuer) {
|
|
978
|
+
return stagingFilePath("mcp-refresh-secrets", issuer);
|
|
896
979
|
}
|
|
897
980
|
/** Write the secrets bundle to a 0600 staging file, `KEY=VALUE` per line.
|
|
898
981
|
* This file legitimately carries secret material (like `grant`'s 0600 key
|
|
899
982
|
* files) — the "never print secret values" rule is about stdout/returned
|
|
900
|
-
* result objects, not this deliberately-created, permission-locked file.
|
|
901
|
-
|
|
983
|
+
* result objects, not this deliberately-created, permission-locked file.
|
|
984
|
+
*
|
|
985
|
+
* `exclusive` opens with `O_CREAT|O_EXCL` (flag `wx`): the write FAILS rather
|
|
986
|
+
* than truncate a file that is already there. The refresh fallback uses it so a
|
|
987
|
+
* pre-existing file at the target path — including the full IdP credentials
|
|
988
|
+
* bundle an operator may have staged there — can never be erased (flair#2283). */
|
|
989
|
+
export function writeSecretsStagingFile(path, bundle, opts = {}) {
|
|
902
990
|
mkdirSync(dirname(path), { recursive: true });
|
|
903
991
|
const body = Object.entries(bundle).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
|
|
904
|
-
writeFileSync(path, body, { mode: 0o600 });
|
|
992
|
+
writeFileSync(path, body, { mode: 0o600, flag: opts.exclusive ? "wx" : "w" });
|
|
905
993
|
chmodSync(path, 0o600);
|
|
906
994
|
}
|
|
907
995
|
/** Provision secrets per the shape-aware mechanism, staging the bundle to a
|
|
908
996
|
* 0600 file and returning ONLY names/paths/instructions — never values. */
|
|
909
997
|
export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
910
|
-
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism);
|
|
998
|
+
const mechanism = selectSecretsMechanism(instanceUrl, opts.mechanism, opts.fabric);
|
|
911
999
|
const path = opts.stagingPath ?? defaultSecretsStagingPath(instanceUrl);
|
|
912
1000
|
writeSecretsStagingFile(path, bundle);
|
|
913
1001
|
const varNames = Object.keys(bundle);
|
|
914
1002
|
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.`
|
|
1003
|
+
? `Apply the ${varNames.length} vars staged at ${path} via Fabric Studio → Cluster Settings → Environment, then re-run with --confirm-secrets-applied.`
|
|
917
1004
|
: `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
1005
|
return { mechanism, path, varNames, instructions };
|
|
919
1006
|
}
|
|
@@ -940,40 +1027,124 @@ export function provisionSecrets(instanceUrl, bundle, opts = {}) {
|
|
|
940
1027
|
* one rather than being handed a 404 about something else.
|
|
941
1028
|
*/
|
|
942
1029
|
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.
|
|
1030
|
+
/** The served origin's host at HOSTED_OPS_PORT, or null when the origin does
|
|
1031
|
+
* not parse. A bare host name is read as https. */
|
|
1032
|
+
function hostedOpsUrl(servedOrigin) {
|
|
950
1033
|
try {
|
|
951
|
-
const u = new URL(
|
|
1034
|
+
const u = new URL(servedOrigin.includes("://") ? servedOrigin : `https://${servedOrigin}`);
|
|
952
1035
|
u.port = String(HOSTED_OPS_PORT);
|
|
953
1036
|
u.pathname = "/";
|
|
954
1037
|
u.search = "";
|
|
955
|
-
return u
|
|
1038
|
+
return u;
|
|
956
1039
|
}
|
|
957
1040
|
catch {
|
|
958
|
-
|
|
959
|
-
// let the caller's error path name the remedy.
|
|
960
|
-
return `${target.replace(/\/+$/, "")}/`;
|
|
1041
|
+
return null;
|
|
961
1042
|
}
|
|
962
1043
|
}
|
|
1044
|
+
export function resolveOpsUrl(target, explicitOpsUrl) {
|
|
1045
|
+
if (explicitOpsUrl)
|
|
1046
|
+
return `${explicitOpsUrl.replace(/\/+$/, "")}/`;
|
|
1047
|
+
if (typeof target === "number")
|
|
1048
|
+
return `http://127.0.0.1:${target}/`;
|
|
1049
|
+
// A string target is the SERVED origin. Its own port serves the REST surface,
|
|
1050
|
+
// not the ops API, so reuse the host and apply the hosted ops port.
|
|
1051
|
+
// Unparseable — preserve the old behaviour rather than inventing a URL, and
|
|
1052
|
+
// let the caller's error path name the remedy.
|
|
1053
|
+
return hostedOpsUrl(target)?.toString() ?? `${target.replace(/\/+$/, "")}/`;
|
|
1054
|
+
}
|
|
963
1055
|
function opsBaseUrl(opsPortOrUrl) {
|
|
964
1056
|
return resolveOpsUrl(opsPortOrUrl);
|
|
965
1057
|
}
|
|
966
1058
|
function basicAuthHeader(adminUser, adminPass) {
|
|
967
1059
|
return `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
|
|
968
1060
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
1061
|
+
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 ` +
|
|
1062
|
+
`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 ` +
|
|
1063
|
+
`hostedOrigin as the same canonical http:// or https:// origin form, whose host is used at port ${HOSTED_OPS_PORT}. ` +
|
|
1064
|
+
`The string must exactly equal its parsed URL origin or that origin followed by /. No request was sent.`;
|
|
1065
|
+
/** Show only the parsed protocol, hostname and port of a refused target. The
|
|
1066
|
+
* display is built without interpolating the raw input, and excludes its
|
|
1067
|
+
* userinfo, path, query and fragment. Parsed components can match input text.
|
|
1068
|
+
* Use the placeholder for a non-string, a parse error or an empty hostname. */
|
|
1069
|
+
function showOpsTarget(value) {
|
|
1070
|
+
if (typeof value !== "string")
|
|
1071
|
+
return "<unparseable value>";
|
|
1072
|
+
try {
|
|
1073
|
+
const u = new URL(value);
|
|
1074
|
+
if (!u.hostname)
|
|
1075
|
+
return "<unparseable value>";
|
|
1076
|
+
return `${u.protocol}//${u.hostname}${u.port ? `:${u.port}` : ""}`;
|
|
1077
|
+
}
|
|
1078
|
+
catch {
|
|
1079
|
+
return "<unparseable value>";
|
|
1080
|
+
}
|
|
976
1081
|
}
|
|
1082
|
+
/** A URL string is accepted only when parsing leaves its origin spelling
|
|
1083
|
+
* unchanged (apart from an optional `/`). This also rejects empty ? and #. */
|
|
1084
|
+
function canonicalHttpOrigin(value) {
|
|
1085
|
+
if (typeof value !== "string")
|
|
1086
|
+
return null;
|
|
1087
|
+
try {
|
|
1088
|
+
const u = new URL(value);
|
|
1089
|
+
if ((u.protocol === "http:" || u.protocol === "https:") &&
|
|
1090
|
+
!u.username && !u.password &&
|
|
1091
|
+
(value === u.origin || value === `${u.origin}/`))
|
|
1092
|
+
return u;
|
|
1093
|
+
}
|
|
1094
|
+
catch {
|
|
1095
|
+
// A malformed URL is not an ops target.
|
|
1096
|
+
}
|
|
1097
|
+
return null;
|
|
1098
|
+
}
|
|
1099
|
+
export function targetOriginRefusal(instance) {
|
|
1100
|
+
if (canonicalHttpOrigin(instance))
|
|
1101
|
+
return;
|
|
1102
|
+
const origin = showOpsTarget(instance);
|
|
1103
|
+
return "Target must be a canonical http:// or https:// origin, optionally followed by /." +
|
|
1104
|
+
(canonicalHttpOrigin(origin) ? ` Use ${origin}.` : "");
|
|
1105
|
+
}
|
|
1106
|
+
/** Resolve the ops target, or throw naming the field, its safe display and the
|
|
1107
|
+
* accepted forms. One implementation, so every identity-mapping command sends
|
|
1108
|
+
* its ops calls to the same address (flair#2115). */
|
|
1109
|
+
function identityMappingOpsUrl(target) {
|
|
1110
|
+
const { opsPortOrUrl, hostedOrigin } = target;
|
|
1111
|
+
const refuse = (what) => {
|
|
1112
|
+
throw new Error(`Identity mapping: ${what}. ${IDENTITY_MAPPING_TARGET_FORMS}`);
|
|
1113
|
+
};
|
|
1114
|
+
if (opsPortOrUrl !== undefined && hostedOrigin !== undefined) {
|
|
1115
|
+
return refuse(`got both opsPortOrUrl ${showOpsTarget(opsPortOrUrl)} and hostedOrigin ${showOpsTarget(hostedOrigin)}`);
|
|
1116
|
+
}
|
|
1117
|
+
if (hostedOrigin !== undefined) {
|
|
1118
|
+
const u = canonicalHttpOrigin(hostedOrigin);
|
|
1119
|
+
if (!u) {
|
|
1120
|
+
return refuse(`cannot read hostedOrigin ${showOpsTarget(hostedOrigin)} as a served origin`);
|
|
1121
|
+
}
|
|
1122
|
+
return { url: resolveOpsUrl(u.origin), hosted: true };
|
|
1123
|
+
}
|
|
1124
|
+
if (opsPortOrUrl === undefined)
|
|
1125
|
+
return refuse("got neither opsPortOrUrl nor hostedOrigin");
|
|
1126
|
+
if (typeof opsPortOrUrl === "number" && Number.isInteger(opsPortOrUrl) && opsPortOrUrl >= 1 && opsPortOrUrl <= 65535) {
|
|
1127
|
+
return { url: resolveOpsUrl(opsPortOrUrl), hosted: false };
|
|
1128
|
+
}
|
|
1129
|
+
if (typeof opsPortOrUrl === "string") {
|
|
1130
|
+
const u = canonicalHttpOrigin(opsPortOrUrl);
|
|
1131
|
+
if (u) {
|
|
1132
|
+
return { url: `${u.origin}/`, hosted: false };
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
return refuse(`cannot tell which ops API opsPortOrUrl ${showOpsTarget(opsPortOrUrl)} names`);
|
|
1136
|
+
}
|
|
1137
|
+
/** The linking layer's Credential tests are the SAME ones the resolver applies
|
|
1138
|
+
* (src/lib/credential-status-rule.ts, imported above): a row maps a principal
|
|
1139
|
+
* only when its `status` is exactly "active" and it names a principal
|
|
1140
|
+
* (`credentialMapsPrincipal`), and a row that names no principal
|
|
1141
|
+
* (`credentialPrincipalId` is null) is skipped on read. The resolver refuses a
|
|
1142
|
+
* subject when at least one row matches it but none maps a principal (with no
|
|
1143
|
+
* matching row at all it may JIT-provision), and resolves the subject through
|
|
1144
|
+
* the active, principal-bearing row this layer writes, even when a
|
|
1145
|
+
* principal-less row remains beside it. The linking layer MUST use the same
|
|
1146
|
+
* tests — a credential the linker considers inactive but the resolver would
|
|
1147
|
+
* still serve is exactly the invisible-duplicate hole #1317 is about. */
|
|
977
1148
|
/**
|
|
978
1149
|
* Map the operator's IdP subject to their principal via `Credential(kind:
|
|
979
1150
|
* "idp")` — the SAME credential surface resources/mcp-handler.ts's
|
|
@@ -981,9 +1152,14 @@ function isResolvableCredential(cred) {
|
|
|
981
1152
|
*
|
|
982
1153
|
* ## The uniqueness constraint (flair#1317, K&S ruling 2026-08-21)
|
|
983
1154
|
*
|
|
984
|
-
* **
|
|
985
|
-
*
|
|
986
|
-
*
|
|
1155
|
+
* **The ruling: at most one ACTIVE, principal-bearing `Credential(kind:"idp",
|
|
1156
|
+
* idpSubject:<sub>)`, regardless of `idpProvider`.** This function's
|
|
1157
|
+
* post-write read verifies one such row at the time of that read, on every
|
|
1158
|
+
* write it makes (`flair mcp enable`, `flair principal link`); it does not
|
|
1159
|
+
* hold the invariant for other writers. The MCP and XAA JIT provisioners also write a
|
|
1160
|
+
* mapping, when their own lookup finds no matching row, and do not run this
|
|
1161
|
+
* check. A principal-less row maps nothing and is skipped, so it may remain
|
|
1162
|
+
* active beside the mapping.
|
|
987
1163
|
*
|
|
988
1164
|
* It used to dedup on `(kind, idpProvider, idpSubject)` while the resolver read
|
|
989
1165
|
* `(kind, idpSubject)`. A re-link under a different provider name therefore
|
|
@@ -996,17 +1172,20 @@ function isResolvableCredential(cred) {
|
|
|
996
1172
|
* stays on the row as audit/diagnostic metadata, but it does not participate in
|
|
997
1173
|
* uniqueness. So:
|
|
998
1174
|
*
|
|
999
|
-
* - same provider, existing active credential → RE-POINT
|
|
1000
|
-
*
|
|
1001
|
-
*
|
|
1175
|
+
* - same provider, existing active, principal-bearing credential → RE-POINT
|
|
1176
|
+
* it (`credentialReused`);
|
|
1177
|
+
* - any OTHER active, principal-bearing credential for the subject →
|
|
1178
|
+
* SUPERSEDE it: terminal `status: "revoked"`, never a soft flag a later
|
|
1179
|
+
* path could flip back
|
|
1002
1180
|
* (revoked rows are never reused here — a re-link after a revoke mints a
|
|
1003
1181
|
* fresh credential);
|
|
1004
1182
|
* - 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
|
|
1183
|
+
* batch, so there is no observable window with two active,
|
|
1184
|
+
* principal-bearing credentials or zero. If the batch fails, nothing is
|
|
1185
|
+
* claimed and the call throws;
|
|
1007
1186
|
* - 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.
|
|
1187
|
+
* somehow holds ≠1 active, principal-bearing credential for the subject is a
|
|
1188
|
+
* hard error, not a silent nondeterministic mapping.
|
|
1010
1189
|
*
|
|
1011
1190
|
* The principal Agent is created only if missing.
|
|
1012
1191
|
*
|
|
@@ -1019,22 +1198,24 @@ function isResolvableCredential(cred) {
|
|
|
1019
1198
|
* so the operator is told, not so the event is hidden.
|
|
1020
1199
|
*/
|
|
1021
1200
|
export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
1201
|
+
const target = identityMappingOpsUrl(params);
|
|
1202
|
+
const opsUrl = target.url;
|
|
1022
1203
|
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1023
|
-
const
|
|
1024
|
-
const
|
|
1204
|
+
const clock = deps.now ?? (() => new Date().toISOString());
|
|
1205
|
+
const now = clock();
|
|
1025
1206
|
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1207
|
+
// flair#2359 — the ONE shared agent-ID rule, before any read or write. The
|
|
1208
|
+
// principal Agent below is inserted through the operations API, so the Agent
|
|
1209
|
+
// resource's own guard never runs on it.
|
|
1210
|
+
if (!isValidAgentId(params.principal)) {
|
|
1211
|
+
throw new Error(`Identity mapping: ${invalidAgentIdMessage(params.principal)}`);
|
|
1212
|
+
}
|
|
1026
1213
|
// Ensure the principal Agent exists.
|
|
1214
|
+
const agentQuery = mappingReadQuery("Agent", { id: params.principal });
|
|
1027
1215
|
const findRes = await fetchImpl(opsUrl, {
|
|
1028
1216
|
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
|
-
}),
|
|
1217
|
+
headers: opsHeaders(authHeader),
|
|
1218
|
+
body: JSON.stringify(agentQuery),
|
|
1038
1219
|
});
|
|
1039
1220
|
if (!findRes.ok) {
|
|
1040
1221
|
const text = await findRes.text().catch(() => "");
|
|
@@ -1044,19 +1225,34 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1044
1225
|
// identity is absent — and saying "failed to look up principal 'x'" sends
|
|
1045
1226
|
// the reader to look at principals, which is where an evening goes.
|
|
1046
1227
|
//
|
|
1047
|
-
//
|
|
1048
|
-
//
|
|
1049
|
-
//
|
|
1050
|
-
//
|
|
1051
|
-
// name an --ops-url flag that does not exist).
|
|
1228
|
+
// For `hostedOrigin`, retain the served-origin diagnosis and explain that
|
|
1229
|
+
// `enable` derived the address: it has no option to point its ops calls
|
|
1230
|
+
// elsewhere (flair#2116). A 404 at a caller-named opsPortOrUrl does not
|
|
1231
|
+
// establish which service answered, so give that path a neutral hint.
|
|
1052
1232
|
const hint = findRes.status === 404
|
|
1053
|
-
?
|
|
1233
|
+
? target.hosted
|
|
1234
|
+
? ` — 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}.`
|
|
1235
|
+
: ` — opsPortOrUrl names this address; verify that the ops API answers requests at ${opsUrl}.`
|
|
1054
1236
|
: "";
|
|
1055
1237
|
throw new Error(`Identity mapping: the ops API call to ${opsUrl} failed (HTTP ${findRes.status})${hint}${text ? `: ${text}` : ""}`);
|
|
1056
1238
|
}
|
|
1057
|
-
|
|
1239
|
+
// flair#2115 — the principal is created only after a valid empty answer.
|
|
1240
|
+
const foundAgents = await opsRecordList(findRes, opsUrl, agentQuery);
|
|
1241
|
+
if (foundAgents.length === 0 && params.principalMustExist) {
|
|
1242
|
+
throw new Error(principalMissingMessage(params.principal));
|
|
1243
|
+
}
|
|
1058
1244
|
let principalCreated = false;
|
|
1059
|
-
|
|
1245
|
+
const findCredentialsForSubject = () => readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject);
|
|
1246
|
+
const subjectCreds = await findCredentialsForSubject();
|
|
1247
|
+
const activeCreds = subjectCreds.filter(credentialMapsPrincipal);
|
|
1248
|
+
// flair#2222 — retain Agent presence and the compared principal-bearing IdP fields.
|
|
1249
|
+
const preflight = mappingPreflight(params.principal, params.idpSubject, foundAgents.length > 0, subjectCreds);
|
|
1250
|
+
if (foundAgents.length === 0) {
|
|
1251
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight);
|
|
1252
|
+
// flair#2433 — the new principal Agent's home is THIS instance's federation
|
|
1253
|
+
// id, resolved through the one shared rule. A create stamps it; a body value
|
|
1254
|
+
// is never the source.
|
|
1255
|
+
const principalHome = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, params.adminUser, params.adminPass, fetchImpl));
|
|
1060
1256
|
const insertRes = await fetchImpl(opsUrl, {
|
|
1061
1257
|
method: "POST",
|
|
1062
1258
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -1072,8 +1268,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1072
1268
|
kind: params.principalKind,
|
|
1073
1269
|
type: params.principalKind,
|
|
1074
1270
|
status: "active",
|
|
1271
|
+
publicKey: `idp:${params.idpProvider}:${params.idpSubject}`,
|
|
1075
1272
|
admin: false,
|
|
1076
1273
|
defaultTrustTier: "endorsed",
|
|
1274
|
+
originatorInstanceId: principalHome,
|
|
1077
1275
|
createdAt: now,
|
|
1078
1276
|
updatedAt: now,
|
|
1079
1277
|
},
|
|
@@ -1085,31 +1283,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1085
1283
|
throw new Error(`Identity mapping: failed to create principal '${params.principal}' (HTTP ${insertRes.status}): ${text}`);
|
|
1086
1284
|
}
|
|
1087
1285
|
principalCreated = true;
|
|
1286
|
+
preflight.principalPresent = true;
|
|
1088
1287
|
}
|
|
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
1288
|
// Survivor: an ACTIVE same-provider credential is re-pointed (the idempotent
|
|
1114
1289
|
// re-run and the documented same-provider link). A revoked one is never
|
|
1115
1290
|
// resurrected — a re-link after a revoke mints a fresh credential.
|
|
@@ -1123,6 +1298,10 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1123
1298
|
// ops-API operation is the strongest atomicity this surface can express, and
|
|
1124
1299
|
// ordering the survivor first means even a partially-applied batch can never
|
|
1125
1300
|
// leave the subject with ZERO resolvable credentials (the fail-open denial).
|
|
1301
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight, principalCreated);
|
|
1302
|
+
// The mapping's times are read immediately before sending the mapping
|
|
1303
|
+
// upsert, not at the start of the run.
|
|
1304
|
+
const writtenAt = clock();
|
|
1126
1305
|
const upsertRes = await fetchImpl(opsUrl, {
|
|
1127
1306
|
method: "POST",
|
|
1128
1307
|
headers: { "Content-Type": "application/json", Authorization: authHeader },
|
|
@@ -1139,8 +1318,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1139
1318
|
status: "active",
|
|
1140
1319
|
idpProvider: params.idpProvider,
|
|
1141
1320
|
idpSubject: params.idpSubject,
|
|
1142
|
-
createdAt: reused ?
|
|
1143
|
-
lastUsedAt:
|
|
1321
|
+
createdAt: typeof reused?.createdAt === "string" ? reused.createdAt : writtenAt,
|
|
1322
|
+
lastUsedAt: writtenAt,
|
|
1144
1323
|
},
|
|
1145
1324
|
// Retained, not deleted: the revocation stays legible in storage and in
|
|
1146
1325
|
// Harper's table audit log (which records the full record image of
|
|
@@ -1155,8 +1334,8 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1155
1334
|
status: "revoked",
|
|
1156
1335
|
idpProvider: c.idpProvider,
|
|
1157
1336
|
idpSubject: params.idpSubject,
|
|
1158
|
-
createdAt: c.createdAt,
|
|
1159
|
-
updatedAt:
|
|
1337
|
+
createdAt: typeof c.createdAt === "string" ? c.createdAt : writtenAt,
|
|
1338
|
+
updatedAt: writtenAt,
|
|
1160
1339
|
})),
|
|
1161
1340
|
],
|
|
1162
1341
|
}),
|
|
@@ -1170,14 +1349,9 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1170
1349
|
// ≠1 active credential means the resolver's answer for this subject is
|
|
1171
1350
|
// order-dependent, so this fails LOUDLY rather than returning a mapping the
|
|
1172
1351
|
// 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
|
-
}
|
|
1352
|
+
await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, {
|
|
1353
|
+
id: credentialId, principalId: params.principal, idpProvider: params.idpProvider, status: "active",
|
|
1354
|
+
});
|
|
1181
1355
|
return {
|
|
1182
1356
|
principalCreated,
|
|
1183
1357
|
credentialId,
|
|
@@ -1186,6 +1360,349 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
|
|
|
1186
1360
|
supersededCredentialIds: superseded.map((c) => String(c.id)),
|
|
1187
1361
|
};
|
|
1188
1362
|
}
|
|
1363
|
+
/** The admin Basic header every ops call on this surface carries. */
|
|
1364
|
+
function opsHeaders(authHeader) {
|
|
1365
|
+
return { "Content-Type": "application/json", Authorization: authHeader };
|
|
1366
|
+
}
|
|
1367
|
+
function mappingReadQuery(table, equals) {
|
|
1368
|
+
const fields = table === "Agent" ? ["id"] :
|
|
1369
|
+
["id", "kind", "principalId", "idpProvider", "idpSubject", "status", "label", "createdAt"];
|
|
1370
|
+
if (table === "Agent") {
|
|
1371
|
+
return { operation: "search_by_value", database: "flair", table,
|
|
1372
|
+
search_attribute: "id", search_value: equals.id, get_attributes: fields };
|
|
1373
|
+
}
|
|
1374
|
+
return { operation: "search_by_conditions", database: "flair", table, operator: "and",
|
|
1375
|
+
conditions: Object.entries(equals).map(([search_attribute, search_value]) => ({ search_attribute, search_type: "equals", search_value })), get_attributes: fields };
|
|
1376
|
+
}
|
|
1377
|
+
async function opsReadRows(fetchImpl, opsUrl, authHeader, query, written, refuseAmbiguous = false) {
|
|
1378
|
+
const res = await fetchImpl(opsUrl, { method: "POST", headers: opsHeaders(authHeader), body: JSON.stringify(query) });
|
|
1379
|
+
if (!res.ok) {
|
|
1380
|
+
const text = await res.text().catch(() => "");
|
|
1381
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} failed (HTTP ${res.status})${text ? `: ${text}` : ""}`);
|
|
1382
|
+
}
|
|
1383
|
+
return opsRecordList(res, opsUrl, query, written, refuseAmbiguous);
|
|
1384
|
+
}
|
|
1385
|
+
async function opsRecordList(res, opsUrl, query, written, refuseAmbiguous = false) {
|
|
1386
|
+
const parsed = await res.json().catch(() => null);
|
|
1387
|
+
if (!Array.isArray(parsed)) {
|
|
1388
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} did not answer with a record list; ` +
|
|
1389
|
+
`verify that the target answers operations API requests there.`);
|
|
1390
|
+
}
|
|
1391
|
+
const predicate = query.operation === "search_by_value"
|
|
1392
|
+
? [[query.search_attribute, query.search_value]]
|
|
1393
|
+
: query.conditions.map(c => [c.search_attribute, c.search_value]);
|
|
1394
|
+
const ids = new Set();
|
|
1395
|
+
const rows = [];
|
|
1396
|
+
for (const [index, row] of parsed.entries()) {
|
|
1397
|
+
const refuse = (reason) => {
|
|
1398
|
+
throw new Error(`Identity mapping: the ops API read at ${opsUrl} answered with a malformed ${query.table} record (entry ${index}): ${reason}.`);
|
|
1399
|
+
};
|
|
1400
|
+
if (row === null || typeof row !== "object" || Array.isArray(row))
|
|
1401
|
+
refuse("invalid-row-shape");
|
|
1402
|
+
if (!isNonEmptyString(row.id))
|
|
1403
|
+
refuse("missing-or-invalid-id");
|
|
1404
|
+
for (const [field, value] of predicate) {
|
|
1405
|
+
if (!query.get_attributes.includes(field))
|
|
1406
|
+
refuse(`predicate-attribute-not-requested:${field}`);
|
|
1407
|
+
if (!Object.hasOwn(row, field) || row[field] !== value)
|
|
1408
|
+
refuse(`query-mismatch:${field}`);
|
|
1409
|
+
}
|
|
1410
|
+
if (ids.has(row.id))
|
|
1411
|
+
refuse("duplicate-row-id");
|
|
1412
|
+
ids.add(row.id);
|
|
1413
|
+
if (query.table === "Credential" && credentialPrincipalId(row) === null)
|
|
1414
|
+
continue;
|
|
1415
|
+
if (query.table === "Credential" &&
|
|
1416
|
+
(typeof row.idpProvider !== "string" ||
|
|
1417
|
+
typeof row.idpSubject !== "string" ||
|
|
1418
|
+
(row.label != null && typeof row.label !== "string") ||
|
|
1419
|
+
(row.status != null && typeof row.status !== "string"))) {
|
|
1420
|
+
refuse("missing-or-invalid-credential-field");
|
|
1421
|
+
}
|
|
1422
|
+
rows.push(row);
|
|
1423
|
+
}
|
|
1424
|
+
if (refuseAmbiguous && query.table === "Credential" && predicate.some(([field]) => field === "idpSubject")) {
|
|
1425
|
+
const principals = [...new Set(rows.filter(credentialMapsPrincipal).map(row => row.principalId))];
|
|
1426
|
+
if (principals.length > 1) {
|
|
1427
|
+
throw new Error(`Identity mapping: ambiguous-prior-principals: ${principals.join(", ")} — refusing the subject read. Run flair mcp enable to heal this subject mapping.`);
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
if (written) {
|
|
1431
|
+
const active = rows.filter(credentialMapsPrincipal);
|
|
1432
|
+
if (active.length !== 1 || Object.entries(written).some(([field, value]) => active[0][field] !== value)) {
|
|
1433
|
+
const subject = predicate.find(([field]) => field === "idpSubject")?.[1];
|
|
1434
|
+
const seen = active.map(c => `${c.id} → ${c.principalId} (provider '${c.idpProvider}')`).join("; ") || "none";
|
|
1435
|
+
throw new Error(`Identity mapping: post-write-mismatch — the uniqueness invariant does not hold after the write (flair#1317) — subject '${subject}' ` +
|
|
1436
|
+
`has ${active.length} resolvable (principal-bearing) active Credential(kind:idp) row(s) [${seen}], expected exactly 1 (${written.id}) ` +
|
|
1437
|
+
`for principal '${written.principalId}', provider '${written.idpProvider}', status 'active'. ` +
|
|
1438
|
+
`Principal-less legacy rows are skipped and may remain active. ` +
|
|
1439
|
+
`Inspect the Credential table for kind:"idp" idpSubject:"${subject}" and revoke the rows that should not resolve.`);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
return rows;
|
|
1443
|
+
}
|
|
1444
|
+
function isNonEmptyString(value) {
|
|
1445
|
+
return typeof value === "string" && value !== "";
|
|
1446
|
+
}
|
|
1447
|
+
async function readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, idpSubject, written, refuseAmbiguous = false) {
|
|
1448
|
+
return opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Credential", { kind: "idp", idpSubject }), written, refuseAmbiguous);
|
|
1449
|
+
}
|
|
1450
|
+
async function readIdpCredentialsForPrincipal(fetchImpl, opsUrl, authHeader, principal) {
|
|
1451
|
+
return opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Credential", { kind: "idp", principalId: principal }));
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* Refuse unless the principal exists, by name.
|
|
1455
|
+
*
|
|
1456
|
+
* A read that FAILED propagates: an unreadable Agent table is not an absent
|
|
1457
|
+
* principal, and this check stands in front of a mapping write (flair#2115).
|
|
1458
|
+
* The id is compared, not just the non-emptiness of the answer.
|
|
1459
|
+
*/
|
|
1460
|
+
async function assertPrincipalExists(fetchImpl, opsUrl, authHeader, principal) {
|
|
1461
|
+
const rows = await opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Agent", { id: principal }));
|
|
1462
|
+
if (rows.length === 0)
|
|
1463
|
+
throw new Error(principalMissingMessage(principal));
|
|
1464
|
+
}
|
|
1465
|
+
/** The one refusal a missing principal gets, wherever it is checked. */
|
|
1466
|
+
function principalMissingMessage(principal) {
|
|
1467
|
+
return (`No principal '${principal}' — nothing was written. Create the principal on the TARGET instance ` +
|
|
1468
|
+
`(run \`flair mcp enable\` against it: it creates the principal it maps), then re-run.`);
|
|
1469
|
+
}
|
|
1470
|
+
/** Canonicalize id, kind, principalId, idpProvider, idpSubject, status, label and createdAt. */
|
|
1471
|
+
function canonicalSubjectRows(rows) {
|
|
1472
|
+
return JSON.stringify(rows
|
|
1473
|
+
.map((r) => ({
|
|
1474
|
+
id: String(r?.id),
|
|
1475
|
+
kind: r?.kind ?? null,
|
|
1476
|
+
principalId: r?.principalId ?? null,
|
|
1477
|
+
idpProvider: r?.idpProvider ?? null,
|
|
1478
|
+
idpSubject: r?.idpSubject ?? null,
|
|
1479
|
+
status: r?.status ?? null,
|
|
1480
|
+
label: r?.label ?? null,
|
|
1481
|
+
createdAt: r?.createdAt ?? null,
|
|
1482
|
+
}))
|
|
1483
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)));
|
|
1484
|
+
}
|
|
1485
|
+
function mappingPreflight(principal, idpSubject, principalPresent, subjectRows) {
|
|
1486
|
+
return { principal, idpSubject, principalPresent, subjectRows: canonicalSubjectRows(subjectRows) };
|
|
1487
|
+
}
|
|
1488
|
+
/** Valid comparison differences refuse here; invalid changed rows can fail earlier validation
|
|
1489
|
+
* with missing-or-invalid-credential-field. Both fail closed. */
|
|
1490
|
+
function mappingChangedMessage(principal, idpSubject, principalCreated = false) {
|
|
1491
|
+
return (`Identity mapping: mapping-changed-underneath — the Agent presence or compared IdP mapping fields for principal '${principal}' ` +
|
|
1492
|
+
`and IdP subject '${idpSubject}' changed on the target between this command's validation and its write. ` +
|
|
1493
|
+
(principalCreated ? `Agent '${principal}' was created; no rollback was attempted. No Credential write was made. ` : `Nothing was written. `) +
|
|
1494
|
+
`Re-run the command.`);
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Re-read the state a preflight validated and refuse if it moved.
|
|
1498
|
+
*
|
|
1499
|
+
* A failed read propagates: an unreadable table is not an unchanged one, and
|
|
1500
|
+
* this stands in front of a write. Called immediately before each write in
|
|
1501
|
+
* `provisionIdpIdentityMapping`, `linkPrincipalMapping` and
|
|
1502
|
+
* `unlinkPrincipalMapping`.
|
|
1503
|
+
*/
|
|
1504
|
+
async function assertMappingUnchanged(fetchImpl, opsUrl, authHeader, preflight, principalCreated = false) {
|
|
1505
|
+
const agents = await opsReadRows(fetchImpl, opsUrl, authHeader, mappingReadQuery("Agent", { id: preflight.principal }));
|
|
1506
|
+
if ((agents.length > 0) !== preflight.principalPresent) {
|
|
1507
|
+
throw new Error(mappingChangedMessage(preflight.principal, preflight.idpSubject, principalCreated));
|
|
1508
|
+
}
|
|
1509
|
+
const rows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, preflight.idpSubject);
|
|
1510
|
+
if (canonicalSubjectRows(rows) !== preflight.subjectRows) {
|
|
1511
|
+
throw new Error(mappingChangedMessage(preflight.principal, preflight.idpSubject, principalCreated));
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* flair#2115 — `flair principal link|unlink|links` carry the target instance's
|
|
1516
|
+
* admin credential to its operations API, so the target they accept is narrower
|
|
1517
|
+
* than `checkLocalOriginRefusal`'s claude.ai-oriented one: a `hostedOrigin`
|
|
1518
|
+
* that `checkMappingTargetRefusal` refuses is refused. The numeric
|
|
1519
|
+
* `opsPortOrUrl` form names the caller's own address and is left alone.
|
|
1520
|
+
*
|
|
1521
|
+
* Called before the first request, so a refused target never sees one.
|
|
1522
|
+
*/
|
|
1523
|
+
function assertMappingTarget(target) {
|
|
1524
|
+
const { hostedOrigin } = target;
|
|
1525
|
+
if (hostedOrigin === undefined)
|
|
1526
|
+
return;
|
|
1527
|
+
const check = checkMappingTargetRefusal(String(hostedOrigin));
|
|
1528
|
+
if (check.refused)
|
|
1529
|
+
throw new Error(check.message);
|
|
1530
|
+
}
|
|
1531
|
+
/** The exactly-one target fields, rebuilt so they can be spread into a fresh
|
|
1532
|
+
* literal (a union value cannot be spread into one). */
|
|
1533
|
+
function mappingTargetFields(target) {
|
|
1534
|
+
const t = target;
|
|
1535
|
+
return t.hostedOrigin !== undefined
|
|
1536
|
+
? { hostedOrigin: String(t.hostedOrigin) }
|
|
1537
|
+
: { opsPortOrUrl: t.opsPortOrUrl };
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* `flair principal link` — map one IdP subject to a principal that already
|
|
1541
|
+
* exists, through `provisionIdpIdentityMapping` (the `mcp enable` step).
|
|
1542
|
+
*
|
|
1543
|
+
* - the subject already mapped to THIS principal (no active row names another):
|
|
1544
|
+
* reported, exit 0, NO write;
|
|
1545
|
+
* - the subject mapped to a DIFFERENT principal: refused by name unless
|
|
1546
|
+
* `replace` is set; with `replace`, the write re-points it and the result
|
|
1547
|
+
* names the principal it left;
|
|
1548
|
+
* - a missing principal is refused by name with nothing written;
|
|
1549
|
+
* - a failed read is refused: it never counts as "no mapping";
|
|
1550
|
+
* - a target `checkMappingTargetRefusal` refuses is refused before any request.
|
|
1551
|
+
*/
|
|
1552
|
+
export async function linkPrincipalMapping(params, deps = {}) {
|
|
1553
|
+
assertMappingTarget(params);
|
|
1554
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1555
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1556
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1557
|
+
// Refuse a missing requested principal before either mapping branch.
|
|
1558
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1559
|
+
const subjectRows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, undefined, true);
|
|
1560
|
+
const active = subjectRows.filter(credentialMapsPrincipal);
|
|
1561
|
+
const elsewhere = active.filter((c) => c?.principalId !== params.principal);
|
|
1562
|
+
if (elsewhere.length > 0 && !params.replace) {
|
|
1563
|
+
const current = [...new Set(elsewhere.map((c) => String(c?.principalId)))].join(", ");
|
|
1564
|
+
throw new Error(`IdP subject '${params.idpSubject}' is already mapped to principal '${current}', not '${params.principal}' — ` +
|
|
1565
|
+
`nothing was written. Pass --replace to move it.`);
|
|
1566
|
+
}
|
|
1567
|
+
if (active.length > 0 && elsewhere.length === 0) {
|
|
1568
|
+
const provider = String(active[0]?.idpProvider ?? params.idpProvider);
|
|
1569
|
+
return {
|
|
1570
|
+
action: "already-linked",
|
|
1571
|
+
principal: params.principal,
|
|
1572
|
+
idpProvider: provider,
|
|
1573
|
+
idpSubject: params.idpSubject,
|
|
1574
|
+
supersededCredentialIds: [],
|
|
1575
|
+
lines: [
|
|
1576
|
+
`Already linked: IdP subject '${params.idpSubject}' (provider '${provider}') → principal '${params.principal}'. No change.`,
|
|
1577
|
+
],
|
|
1578
|
+
};
|
|
1579
|
+
}
|
|
1580
|
+
const previousPrincipal = elsewhere.length > 0 ? String(elsewhere[0]?.principalId) : undefined;
|
|
1581
|
+
// flair#2222 — the write is the shared provisioner's; re-validate the state
|
|
1582
|
+
// this preflight acted on so a concurrent change refuses here, not after the
|
|
1583
|
+
// provisioner has already re-read and moved on.
|
|
1584
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, mappingPreflight(params.principal, params.idpSubject, true, subjectRows));
|
|
1585
|
+
const mapping = await provisionIdpIdentityMapping({
|
|
1586
|
+
...mappingTargetFields(params),
|
|
1587
|
+
adminUser: params.adminUser,
|
|
1588
|
+
adminPass: params.adminPass,
|
|
1589
|
+
principal: params.principal,
|
|
1590
|
+
principalKind: "human",
|
|
1591
|
+
idpProvider: params.idpProvider,
|
|
1592
|
+
idpSubject: params.idpSubject,
|
|
1593
|
+
principalMustExist: true,
|
|
1594
|
+
}, deps);
|
|
1595
|
+
const outcome = mapping.credentialReused ? "re-pointed" : "created";
|
|
1596
|
+
const line = previousPrincipal !== undefined
|
|
1597
|
+
? `Re-linked: IdP subject '${params.idpSubject}' (provider '${params.idpProvider}') was mapped to principal ` +
|
|
1598
|
+
`'${previousPrincipal}'; now mapped to '${params.principal}' — Credential(kind:idp) ${outcome} (${mapping.credentialId}).` +
|
|
1599
|
+
supersededCredentialNote(mapping)
|
|
1600
|
+
: `Linked: IdP subject '${params.idpSubject}' (provider '${params.idpProvider}') → principal '${params.principal}' ` +
|
|
1601
|
+
`— Credential(kind:idp) ${outcome} (${mapping.credentialId}).` + supersededCredentialNote(mapping);
|
|
1602
|
+
return {
|
|
1603
|
+
action: previousPrincipal !== undefined ? "replaced" : "linked",
|
|
1604
|
+
principal: params.principal,
|
|
1605
|
+
idpProvider: params.idpProvider,
|
|
1606
|
+
idpSubject: params.idpSubject,
|
|
1607
|
+
previousPrincipal,
|
|
1608
|
+
credentialId: mapping.credentialId,
|
|
1609
|
+
credentialReused: mapping.credentialReused,
|
|
1610
|
+
supersededCredentialIds: mapping.supersededCredentialIds,
|
|
1611
|
+
lines: [line],
|
|
1612
|
+
};
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* `flair principal unlink` — revoke the subject's mapping to this principal.
|
|
1616
|
+
* A subject not mapped to that principal or carrying a different provider
|
|
1617
|
+
* name is refused before writing.
|
|
1618
|
+
*/
|
|
1619
|
+
export async function unlinkPrincipalMapping(params, deps = {}) {
|
|
1620
|
+
assertMappingTarget(params);
|
|
1621
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1622
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1623
|
+
const now = (deps.now ?? (() => new Date().toISOString()))();
|
|
1624
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1625
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1626
|
+
const subjectRows = await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject, undefined, true);
|
|
1627
|
+
const active = subjectRows.filter(credentialMapsPrincipal);
|
|
1628
|
+
const mine = active.filter((c) => c?.principalId === params.principal);
|
|
1629
|
+
if (mine.length === 0) {
|
|
1630
|
+
const elsewhere = [...new Set(active.map((c) => String(c?.principalId)))].join(", ");
|
|
1631
|
+
throw new Error(`IdP subject '${params.idpSubject}' is not mapped to principal '${params.principal}' — nothing was written.` +
|
|
1632
|
+
(elsewhere ? ` It is mapped to: ${elsewhere}.` : ` It has no active Credential(kind:idp) mapping.`));
|
|
1633
|
+
}
|
|
1634
|
+
const providers = [...new Set(mine.map((c) => String(c?.idpProvider)))];
|
|
1635
|
+
if (providers.length !== 1 || providers[0] !== params.idpProvider) {
|
|
1636
|
+
throw new Error(`IdP subject '${params.idpSubject}' is mapped to principal '${params.principal}' under provider ` +
|
|
1637
|
+
`'${providers.join(", ")}', not '${params.idpProvider}' — nothing was written. Re-run with ` +
|
|
1638
|
+
`--idp-provider ${providers[0]}.`);
|
|
1639
|
+
}
|
|
1640
|
+
// flair#2222 — re-validate the state this preflight acted on before revoking.
|
|
1641
|
+
await assertMappingUnchanged(fetchImpl, opsUrl, authHeader, mappingPreflight(params.principal, params.idpSubject, true, subjectRows));
|
|
1642
|
+
const ids = mine.map((c) => String(c?.id));
|
|
1643
|
+
const unconfirmedMessage = (unconfirmed) => `Identity mapping: revocation unconfirmed for Credential IDs: ${unconfirmed.join(", ")}`;
|
|
1644
|
+
const res = await fetchImpl(opsUrl, {
|
|
1645
|
+
method: "POST",
|
|
1646
|
+
headers: opsHeaders(authHeader),
|
|
1647
|
+
body: JSON.stringify({
|
|
1648
|
+
operation: "update",
|
|
1649
|
+
database: "flair",
|
|
1650
|
+
table: "Credential",
|
|
1651
|
+
records: ids.map((id) => ({ id, status: "revoked", updatedAt: now })),
|
|
1652
|
+
}),
|
|
1653
|
+
}).catch((err) => {
|
|
1654
|
+
throw new Error(`${unconfirmedMessage(ids)} — ${err instanceof Error ? err.message : String(err)}`);
|
|
1655
|
+
});
|
|
1656
|
+
if (!res.ok) {
|
|
1657
|
+
const text = await res.text().catch(() => "");
|
|
1658
|
+
throw new Error(`${unconfirmedMessage(ids)} (HTTP ${res.status})${text ? `: ${text}` : ""}`);
|
|
1659
|
+
}
|
|
1660
|
+
const result = await res.json().catch(() => null);
|
|
1661
|
+
const unconfirmed = ids.filter(id => !writeConfirmed(result, "update_hashes", id));
|
|
1662
|
+
if (unconfirmed.length > 0)
|
|
1663
|
+
throw new Error(unconfirmedMessage(unconfirmed));
|
|
1664
|
+
const remaining = (await readIdpCredentialsForSubject(fetchImpl, opsUrl, authHeader, params.idpSubject)
|
|
1665
|
+
.catch((err) => {
|
|
1666
|
+
throw new Error(`${unconfirmedMessage(ids)} — ${err instanceof Error ? err.message : String(err)}`);
|
|
1667
|
+
})).filter(credentialMapsPrincipal);
|
|
1668
|
+
if (remaining.length > 0) {
|
|
1669
|
+
throw new Error(`${unconfirmedMessage(remaining.map(c => c.id))} — subject '${params.idpSubject}' still has resolvable mappings.`);
|
|
1670
|
+
}
|
|
1671
|
+
return {
|
|
1672
|
+
principal: params.principal,
|
|
1673
|
+
idpSubject: params.idpSubject,
|
|
1674
|
+
revokedCredentialIds: ids,
|
|
1675
|
+
lines: [
|
|
1676
|
+
`Unlinked: IdP subject '${params.idpSubject}' is no longer mapped to principal '${params.principal}' — ` +
|
|
1677
|
+
`Credential(kind:idp) revoked (${ids.join(", ")}).`,
|
|
1678
|
+
],
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
/**
|
|
1682
|
+
* `flair principal links` — the principal's current (active) IdP mappings.
|
|
1683
|
+
* A missing principal is refused by name and a failed read is refused too: an
|
|
1684
|
+
* empty list is reported only after a valid read with no active mapping.
|
|
1685
|
+
*/
|
|
1686
|
+
export async function listPrincipalMappings(params, deps = {}) {
|
|
1687
|
+
assertMappingTarget(params);
|
|
1688
|
+
const { url: opsUrl } = identityMappingOpsUrl(params);
|
|
1689
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
1690
|
+
const authHeader = basicAuthHeader(params.adminUser, params.adminPass);
|
|
1691
|
+
await assertPrincipalExists(fetchImpl, opsUrl, authHeader, params.principal);
|
|
1692
|
+
const active = (await readIdpCredentialsForPrincipal(fetchImpl, opsUrl, authHeader, params.principal)).filter(credentialMapsPrincipal);
|
|
1693
|
+
const mappings = active.map((c) => ({
|
|
1694
|
+
credentialId: String(c?.id),
|
|
1695
|
+
idpProvider: String(c?.idpProvider),
|
|
1696
|
+
idpSubject: String(c?.idpSubject),
|
|
1697
|
+
}));
|
|
1698
|
+
return {
|
|
1699
|
+
principal: params.principal,
|
|
1700
|
+
mappings,
|
|
1701
|
+
lines: mappings.length === 0
|
|
1702
|
+
? [`No IdP mappings for principal '${params.principal}'.`]
|
|
1703
|
+
: mappings.map((m) => `IdP subject '${m.idpSubject}' (provider '${m.idpProvider}') → principal '${params.principal}' (${m.credentialId})`),
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1189
1706
|
// ─── Restart only ────────────────────────────────────────────────────────────
|
|
1190
1707
|
/** `restart` only — used by `disableMcp` (flag off + restart, no config
|
|
1191
1708
|
* rewrite: the `@harperfast/oauth` config block is left in place; it is
|
|
@@ -1221,18 +1738,42 @@ async function fetchOAuthMetadata(origin, deps = {}) {
|
|
|
1221
1738
|
return { ok: false, unreachable: true, detail: `could not reach ${url}: ${err?.message ?? err}` };
|
|
1222
1739
|
}
|
|
1223
1740
|
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." };
|
|
1741
|
+
return { ok: false, status: res.status, detail: "--instance answered with a redirect; point --instance at the instance itself." };
|
|
1225
1742
|
}
|
|
1226
1743
|
if (!res.ok) {
|
|
1227
|
-
return { ok: false, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
|
|
1744
|
+
return { ok: false, status: res.status, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
|
|
1228
1745
|
}
|
|
1229
1746
|
try {
|
|
1230
|
-
return { ok: true, url, body: await res.json() };
|
|
1747
|
+
return { ok: true, url, status: res.status, body: await res.json() };
|
|
1231
1748
|
}
|
|
1232
1749
|
catch {
|
|
1233
|
-
return { ok: false, detail: `${url} did not return JSON` };
|
|
1750
|
+
return { ok: false, status: res.status, detail: `${url} did not return JSON` };
|
|
1234
1751
|
}
|
|
1235
1752
|
}
|
|
1753
|
+
/** The MCP authorization server's token endpoint for `issuer` — the one
|
|
1754
|
+
* derivation of "the MCP token endpoint of this instance", shared by target
|
|
1755
|
+
* binding (`verifyTargetIssuer`) and public self-verification
|
|
1756
|
+
* (`selfVerifyMcpMetadata`) so both checks derive the expected token endpoint
|
|
1757
|
+
* from the same function. */
|
|
1758
|
+
function mcpTokenEndpoint(issuer) {
|
|
1759
|
+
return `${issuer.replace(/\/+$/, "")}/oauth/mcp/token`;
|
|
1760
|
+
}
|
|
1761
|
+
/** Which authorization server a `token_endpoint` STRING names, given an `issuer`
|
|
1762
|
+
* the caller already knows: flair's own OAuth 2.1 AS answers
|
|
1763
|
+
* `<issuer>/OAuthToken` (resources/oauth-discovery.ts); the `@harperfast/oauth`
|
|
1764
|
+
* plugin answers `<issuer>/oauth/mcp/token`. Anything else is neither. This is a
|
|
1765
|
+
* string comparison only — it does NOT observe which process answered, and it is
|
|
1766
|
+
* meaningful only when `issuer` is a value the caller knows independently of the
|
|
1767
|
+
* document. One implementation, so the self-verify, the discriminator below and
|
|
1768
|
+
* `flair doctor`/`flair deploy` share the endpoint comparison. */
|
|
1769
|
+
export function mcpAuthServerOwner(issuer, tokenEndpoint) {
|
|
1770
|
+
const normalized = issuer.replace(/\/+$/, "");
|
|
1771
|
+
if (tokenEndpoint === `${normalized}/OAuthToken`)
|
|
1772
|
+
return "flair-own";
|
|
1773
|
+
if (tokenEndpoint === mcpTokenEndpoint(normalized))
|
|
1774
|
+
return "plugin";
|
|
1775
|
+
return "other";
|
|
1776
|
+
}
|
|
1236
1777
|
async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
1237
1778
|
const target = await fetchOAuthMetadata(instance, { ...deps, redirect: "manual" });
|
|
1238
1779
|
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 +1784,7 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1243
1784
|
const found = typeof actual === "string" ? `names issuer=${JSON.stringify(actual)}` : `has no string issuer (got ${JSON.stringify(actual)})`;
|
|
1244
1785
|
return { ok: false, detail: `The target's own metadata at ${target.url} ${found}; expected ${issuer}. ${remedy}` };
|
|
1245
1786
|
}
|
|
1246
|
-
if (target.body?.token_endpoint !==
|
|
1787
|
+
if (target.body?.token_endpoint !== mcpTokenEndpoint(issuer)) {
|
|
1247
1788
|
return {
|
|
1248
1789
|
ok: false,
|
|
1249
1790
|
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 +1792,143 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1251
1792
|
}
|
|
1252
1793
|
return { ok: true, detail: `Issuer ${issuer} matched the target's own OAuth authorization-server metadata at ${target.url}` };
|
|
1253
1794
|
}
|
|
1795
|
+
/**
|
|
1796
|
+
* Read `origin`'s discovery document and classify it against the issuer(s) the
|
|
1797
|
+
* caller knows independently of the document.
|
|
1798
|
+
*
|
|
1799
|
+
* caller-known issuer + `/oauth/mcp/token` -> `plugin-live`
|
|
1800
|
+
* caller-known issuer + `/OAuthToken` -> `plugin-absent`
|
|
1801
|
+
* any other document -> `unrecognized`
|
|
1802
|
+
* request failed / non-2xx / non-JSON -> `unreachable`
|
|
1803
|
+
*
|
|
1804
|
+
* This is a string comparison against a caller-known issuer, not an observation
|
|
1805
|
+
* of which process answered. A document whose own `issuer` is not one of the
|
|
1806
|
+
* caller-known candidates (including one that names no issuer) is compared
|
|
1807
|
+
* against nothing and is `unrecognized` — the document is never the trust anchor.
|
|
1808
|
+
*
|
|
1809
|
+
* A failed read is never reported as a state of the surface: `unreachable`
|
|
1810
|
+
* carries `status` only when a response actually came back.
|
|
1811
|
+
*/
|
|
1812
|
+
export async function discriminateMcpOAuthDiscovery(origin, deps = {}) {
|
|
1813
|
+
const normalized = origin.replace(/\/+$/, "");
|
|
1814
|
+
const read = await fetchOAuthMetadata(normalized, deps);
|
|
1815
|
+
if (read.ok === false) {
|
|
1816
|
+
return {
|
|
1817
|
+
state: "unreachable",
|
|
1818
|
+
origin: normalized,
|
|
1819
|
+
url: `${normalized}/.well-known/oauth-authorization-server`,
|
|
1820
|
+
status: read.status,
|
|
1821
|
+
detail: read.detail,
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
const body = read.body;
|
|
1825
|
+
const tokenEndpoint = body?.token_endpoint;
|
|
1826
|
+
// The issuer(s) THIS caller knows without trusting the document: the origins
|
|
1827
|
+
// passed in (configured FLAIR_PUBLIC_URL / FLAIR_MCP_ISSUER, or the origin the
|
|
1828
|
+
// caller verifies) plus the address actually probed. The document's own
|
|
1829
|
+
// `issuer` is NOT one of them — a positive classification must be bound to an
|
|
1830
|
+
// issuer the caller knows independently (flair#2283). flair can publish
|
|
1831
|
+
// FLAIR_PUBLIC_URL as its issuer while a probe reaches it over loopback, so the
|
|
1832
|
+
// probed address alone is not the issuer.
|
|
1833
|
+
const candidates = [
|
|
1834
|
+
...new Set([...(deps.expectedIssuers ?? []), normalized]
|
|
1835
|
+
.map((issuer) => issuer.trim().replace(/\/+$/, ""))
|
|
1836
|
+
.filter((issuer) => issuer !== "")),
|
|
1837
|
+
];
|
|
1838
|
+
const docIssuer = typeof body?.issuer === "string" && body.issuer.trim() !== ""
|
|
1839
|
+
? body.issuer.trim().replace(/\/+$/, "")
|
|
1840
|
+
: undefined;
|
|
1841
|
+
// The document counts only when its own `issuer` EQUALS a candidate the caller
|
|
1842
|
+
// already knows. A document that names some OTHER issuer — or none — is
|
|
1843
|
+
// compared against nothing and cannot be positively classified.
|
|
1844
|
+
const bound = docIssuer !== undefined && candidates.includes(docIssuer) ? docIssuer : undefined;
|
|
1845
|
+
const owner = bound ? mcpAuthServerOwner(bound, tokenEndpoint) : "other";
|
|
1846
|
+
const common = {
|
|
1847
|
+
origin: normalized,
|
|
1848
|
+
url: read.url,
|
|
1849
|
+
status: read.status,
|
|
1850
|
+
issuer: typeof body?.issuer === "string" ? body.issuer : undefined,
|
|
1851
|
+
tokenEndpoint: typeof tokenEndpoint === "string" ? tokenEndpoint : undefined,
|
|
1852
|
+
body,
|
|
1853
|
+
};
|
|
1854
|
+
if (owner === "plugin") {
|
|
1855
|
+
return {
|
|
1856
|
+
...common,
|
|
1857
|
+
state: "plugin-live",
|
|
1858
|
+
detail: `${read.url} advertises token_endpoint=${JSON.stringify(tokenEndpoint)}, the MCP token endpoint of the caller-known issuer ${JSON.stringify(bound)}`,
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
if (owner === "flair-own") {
|
|
1862
|
+
return {
|
|
1863
|
+
...common,
|
|
1864
|
+
state: "plugin-absent",
|
|
1865
|
+
detail: `${read.url} advertises token_endpoint=${JSON.stringify(tokenEndpoint)}, flair's own authorization server for the caller-known issuer ${JSON.stringify(bound)}`,
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
const named = docIssuer === undefined
|
|
1869
|
+
? "the document names no issuer"
|
|
1870
|
+
: candidates.includes(docIssuer)
|
|
1871
|
+
? `the document names issuer=${JSON.stringify(body?.issuer)}, whose token endpoint ${JSON.stringify(tokenEndpoint)} is neither authorization server`
|
|
1872
|
+
: `the document names issuer=${JSON.stringify(body?.issuer)}, which is not an issuer this caller knows (known: ${candidates.map((c) => JSON.stringify(c)).join(", ")})`;
|
|
1873
|
+
return {
|
|
1874
|
+
...common,
|
|
1875
|
+
state: "unrecognized",
|
|
1876
|
+
detail: `${read.url} answered with an unrecognized discovery document — ${named}`,
|
|
1877
|
+
};
|
|
1878
|
+
}
|
|
1879
|
+
/** The detail `flair mcp enable`'s self-verify prints for a `plugin-absent` observation. */
|
|
1880
|
+
function mcpAbsentDetail(url, tokenEndpoint) {
|
|
1881
|
+
return (`${url} advertises flair's own token endpoint (token_endpoint=${tokenEndpoint}). ` +
|
|
1882
|
+
`Is FLAIR_MCP_OAUTH actually set on the restarted instance, and is the '@harperfast/oauth' ` +
|
|
1883
|
+
`component declared in its config.yaml?`);
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* The operator-facing report for a discovery observation, shared by `flair
|
|
1887
|
+
* doctor` and `flair deploy` so both word it identically.
|
|
1888
|
+
*
|
|
1889
|
+
* `mcpConfigured` is the locally inferred `FLAIR_MCP_OAUTH` the caller can see.
|
|
1890
|
+
* A `plugin-absent` observation is a document whose `issuer` equals a caller-known
|
|
1891
|
+
* candidate (a configured public URL / MCP issuer, or the verified origin) while
|
|
1892
|
+
* advertising flair's own `<issuer>/OAuthToken`; true yields a named failure with a
|
|
1893
|
+
* remedy, false yields an informational line. An `unreachable` or `unrecognized`
|
|
1894
|
+
* observation — including a document whose issuer is no candidate — is never a pass,
|
|
1895
|
+
* and never an error: it says the surface could not be confirmed.
|
|
1896
|
+
*/
|
|
1897
|
+
export function reportMcpOAuthDiscovery(observation, mcpConfigured) {
|
|
1898
|
+
switch (observation.state) {
|
|
1899
|
+
case "plugin-live":
|
|
1900
|
+
return {
|
|
1901
|
+
severity: "ok",
|
|
1902
|
+
pass: true,
|
|
1903
|
+
lines: [`MCP OAuth discovery: the metadata advertises the expected token endpoint (${observation.url}).`],
|
|
1904
|
+
};
|
|
1905
|
+
case "plugin-absent":
|
|
1906
|
+
if (!mcpConfigured) {
|
|
1907
|
+
return {
|
|
1908
|
+
severity: "info",
|
|
1909
|
+
pass: false,
|
|
1910
|
+
lines: [
|
|
1911
|
+
`MCP OAuth discovery: local configuration does not imply MCP OAuth is enabled; ${observation.url} advertises flair's own token endpoint.`,
|
|
1912
|
+
],
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
return {
|
|
1916
|
+
severity: "error",
|
|
1917
|
+
pass: false,
|
|
1918
|
+
lines: [
|
|
1919
|
+
`MCP OAuth discovery: local configuration implies FLAIR_MCP_OAUTH is enabled, but the document advertises flair's own token endpoint — ${observation.detail}.`,
|
|
1920
|
+
`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\`).`,
|
|
1921
|
+
],
|
|
1922
|
+
};
|
|
1923
|
+
case "unreachable":
|
|
1924
|
+
case "unrecognized":
|
|
1925
|
+
return {
|
|
1926
|
+
severity: "warn",
|
|
1927
|
+
pass: false,
|
|
1928
|
+
lines: [`MCP OAuth discovery: the MCP authorization server could not be confirmed — ${observation.detail}.`],
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1254
1932
|
/**
|
|
1255
1933
|
* Hit the OAuth metadata endpoint from the operator's machine against the
|
|
1256
1934
|
* PUBLIC origin — the verification that matters is the one claude.ai's
|
|
@@ -1259,41 +1937,40 @@ async function verifyTargetIssuer(instance, issuer, deps = {}) {
|
|
|
1259
1937
|
* advertise CIMD support, is `ok: false` with a specific `detail`.
|
|
1260
1938
|
*
|
|
1261
1939
|
* 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
|
|
1940
|
+
* this checks the public metadata's issuer, MCP token endpoint, and CIMD
|
|
1941
|
+
* advertisement; it does not exercise the token route or `/mcp`. The check
|
|
1942
|
+
* is reused by `enable`'s self-verify step, `grant`/`revoke`'s workflow gate
|
|
1943
|
+
* (src/commands/mcp.ts), and `flair mcp status`, so all four commands use the same
|
|
1944
|
+
* public metadata criterion.
|
|
1266
1945
|
*/
|
|
1267
1946
|
export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
1268
1947
|
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) ──
|
|
1948
|
+
// ── The discriminator runs BEFORE the shape check (flair#1094, flair#2283) ──
|
|
1274
1949
|
//
|
|
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.
|
|
1950
|
+
// A document bound to a caller-known issuer advertising `<issuer>/OAuthToken`
|
|
1951
|
+
// is named before checking registration_endpoint, even when DCR is off.
|
|
1280
1952
|
//
|
|
1281
|
-
//
|
|
1282
|
-
//
|
|
1283
|
-
//
|
|
1284
|
-
|
|
1285
|
-
if (
|
|
1953
|
+
// This used to be an inline token_endpoint comparison here. flair#2283 lifted
|
|
1954
|
+
// it into `discriminateMcpOAuthDiscovery` so `flair doctor` and `flair deploy`
|
|
1955
|
+
// run the SAME function instead of re-deriving the comparison.
|
|
1956
|
+
const observation = await discriminateMcpOAuthDiscovery(normalizedIssuer, { ...deps, expectedIssuers: [normalizedIssuer] });
|
|
1957
|
+
if (observation.state === "unreachable") {
|
|
1958
|
+
// `status` is absent when no response came back.
|
|
1959
|
+
return observation.status === undefined
|
|
1960
|
+
? { ok: false, unreachable: true, detail: observation.detail }
|
|
1961
|
+
: { ok: false, detail: observation.detail };
|
|
1962
|
+
}
|
|
1963
|
+
if (observation.state === "plugin-absent") {
|
|
1286
1964
|
return {
|
|
1287
1965
|
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?`,
|
|
1966
|
+
issuer: observation.issuer,
|
|
1967
|
+
registrationEndpoint: observation.body?.registration_endpoint,
|
|
1968
|
+
tokenEndpoint: observation.tokenEndpoint,
|
|
1969
|
+
detail: mcpAbsentDetail(observation.url, observation.tokenEndpoint),
|
|
1295
1970
|
};
|
|
1296
1971
|
}
|
|
1972
|
+
const url = observation.url;
|
|
1973
|
+
const body = observation.body;
|
|
1297
1974
|
// ── registration_endpoint is OPTIONAL and must not be required (Kern, #1101) ─
|
|
1298
1975
|
//
|
|
1299
1976
|
// Requiring it made self-verify fail on a CORRECTLY enabled instance — the
|
|
@@ -1327,25 +2004,6 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
1327
2004
|
detail: `${url} responded but the metadata shape is unexpected (issuer/token_endpoint) — got issuer=${JSON.stringify(body?.issuer)}`,
|
|
1328
2005
|
};
|
|
1329
2006
|
}
|
|
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
2007
|
// flair#756: confirm CIMD is actually advertised (node_modules/@harperfast/
|
|
1350
2008
|
// oauth/dist/lib/mcp/wellKnown.js:129-165's buildAuthorizationServerMetadata:
|
|
1351
2009
|
// `client_id_metadata_document_supported` is set only when
|
|
@@ -1365,6 +2023,22 @@ export async function selfVerifyMcpMetadata(issuer, deps = {}) {
|
|
|
1365
2023
|
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
2024
|
};
|
|
1367
2025
|
}
|
|
2026
|
+
// flair#2190: the public document must name the MCP authorization server's
|
|
2027
|
+
// token endpoint exactly — the same derivation target binding requires
|
|
2028
|
+
// (mcpTokenEndpoint). The flair's-own-server and CIMD checks above run
|
|
2029
|
+
// first, so those cases keep their specific remedies.
|
|
2030
|
+
if (body.token_endpoint !== mcpTokenEndpoint(normalizedIssuer)) {
|
|
2031
|
+
return {
|
|
2032
|
+
ok: false,
|
|
2033
|
+
issuer: body.issuer,
|
|
2034
|
+
registrationEndpoint: body.registration_endpoint,
|
|
2035
|
+
tokenEndpoint: body.token_endpoint,
|
|
2036
|
+
cimdSupported: true,
|
|
2037
|
+
detail: `Found token_endpoint=${JSON.stringify(body.token_endpoint)} in ${url}, not the MCP authorization server's ` +
|
|
2038
|
+
`expected token_endpoint=${mcpTokenEndpoint(normalizedIssuer)}. This metadata cannot verify the MCP endpoint. ` +
|
|
2039
|
+
`Check the public OAuth authorization-server metadata or proxy for ${normalizedIssuer}, then re-run \`flair mcp enable\`.`,
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
1368
2042
|
return {
|
|
1369
2043
|
ok: true,
|
|
1370
2044
|
issuer: body.issuer,
|
|
@@ -1461,6 +2135,20 @@ export async function captureBootDiscriminator(opsPortOrUrl, adminUser, adminPas
|
|
|
1461
2135
|
}
|
|
1462
2136
|
return { pid };
|
|
1463
2137
|
}
|
|
2138
|
+
/**
|
|
2139
|
+
* flair#1317/#2115 — the note a mapping reports when it revoked a prior
|
|
2140
|
+
* credential for the subject. Returned with a leading space so it appends to a
|
|
2141
|
+
* line, and empty when nothing was superseded. One implementation, so `flair
|
|
2142
|
+
* principal link` prints it exactly as `flair mcp enable` does.
|
|
2143
|
+
*/
|
|
2144
|
+
function supersededCredentialNote(mapping) {
|
|
2145
|
+
return mapping.credentialSuperseded
|
|
2146
|
+
? ` SUPERSEDED: ${mapping.supersededCredentialIds.length} prior Credential(kind:idp) row(s) for this subject ` +
|
|
2147
|
+
`were REVOKED, not de-duplicated — ${mapping.supersededCredentialIds.join(", ")}. ` +
|
|
2148
|
+
`The revoked rows no longer resolve. Future calls for this subject use the surviving mapping. ` +
|
|
2149
|
+
`Exactly one resolvable (principal-bearing) active credential remains per (kind, idpSubject). Principal-less legacy rows are skipped and may remain active.`
|
|
2150
|
+
: "";
|
|
2151
|
+
}
|
|
1464
2152
|
/**
|
|
1465
2153
|
* Full `flair mcp enable` orchestration. No `process.exit`, no console
|
|
1466
2154
|
* output — directly unit-testable with a mocked fetch and temp dirs, same
|
|
@@ -1486,30 +2174,56 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1486
2174
|
//
|
|
1487
2175
|
// Initialised to the first step rather than left undefined so a throw before
|
|
1488
2176
|
// any assignment cannot be attributed to an arbitrary fallback name.
|
|
1489
|
-
let currentStep = "
|
|
2177
|
+
let currentStep = "target-shape-check";
|
|
1490
2178
|
const dryRun = Boolean(params.dryRun);
|
|
1491
2179
|
const push = (ok, detail) => steps.push({ step: currentStep, ok, detail });
|
|
2180
|
+
const targetRefusal = targetOriginRefusal(params.instance) ?? fabricLoopbackRefusal(params.instance, params.fabric);
|
|
2181
|
+
if (targetRefusal) {
|
|
2182
|
+
currentStep = "target-shape-check";
|
|
2183
|
+
push(false, targetRefusal);
|
|
2184
|
+
return { ok: false, dryRun, refused: { message: targetRefusal }, steps, failedStep: "target-shape-check" };
|
|
2185
|
+
}
|
|
1492
2186
|
// ── Local-origin refusal (scenario addendum, binding) ─────────────────────
|
|
1493
2187
|
currentStep = "local-origin-check";
|
|
1494
|
-
const
|
|
2188
|
+
const rawIssuer = params.issuer ?? params.instance;
|
|
2189
|
+
const issuer = rawIssuer.replace(/\/$/, "");
|
|
2190
|
+
const localCheck = checkLocalOriginRefusal(issuer);
|
|
1495
2191
|
if (localCheck.refused) {
|
|
1496
2192
|
push(false, localCheck.message);
|
|
1497
|
-
return { ok: false, dryRun, refused: { message: localCheck.message }, steps, failedStep: "local-origin-check" };
|
|
2193
|
+
return { ok: false, dryRun, refused: { reason: localCheck.reason, message: localCheck.message }, steps, failedStep: "local-origin-check" };
|
|
1498
2194
|
}
|
|
1499
|
-
push(true, `${
|
|
1500
|
-
const issuer = (params.issuer ?? params.instance).replace(/\/+$/, "");
|
|
2195
|
+
push(true, `${issuer}: URL parsed; hostname/IP-literal check passed (no DNS lookup)`);
|
|
1501
2196
|
const idpProvider = params.idpProvider ?? "github";
|
|
1502
2197
|
const principal = params.principal ?? "self";
|
|
1503
2198
|
const principalKind = params.principalKind ?? "human";
|
|
2199
|
+
// flair#2359 — the resolved principal becomes the id of the Agent row the
|
|
2200
|
+
// identity-mapping step writes, so it must satisfy the shared agent-ID rule
|
|
2201
|
+
// before the dry run reports success and before any secrets are staged or
|
|
2202
|
+
// pushed.
|
|
2203
|
+
if (!isValidAgentId(principal)) {
|
|
2204
|
+
currentStep = "principal-id-check";
|
|
2205
|
+
const message = `principal: ${invalidAgentIdMessage(principal)} Nothing was changed.`;
|
|
2206
|
+
push(false, message);
|
|
2207
|
+
return { ok: false, dryRun, refused: { reason: "invalid", message }, steps, failedStep: "principal-id-check" };
|
|
2208
|
+
}
|
|
2209
|
+
const fabricTarget = isFabricTarget(params.instance, params.fabric);
|
|
1504
2210
|
try {
|
|
2211
|
+
// ── Issuer origin (flair#2194) ────────────────────────────────────────────
|
|
2212
|
+
currentStep = "issuer-origin-check";
|
|
2213
|
+
const issuerIssue = issuerOriginRefusal(rawIssuer);
|
|
2214
|
+
if (issuerIssue) {
|
|
2215
|
+
push(false, issuerIssue);
|
|
2216
|
+
return { ok: false, dryRun, refused: { message: issuerIssue }, steps, failedStep: "issuer-origin-check" };
|
|
2217
|
+
}
|
|
2218
|
+
push(true, `issuer ${issuer} is an absolute http(s) origin`);
|
|
2219
|
+
if (!dryRun && !fabricTarget && !isLoopbackUrl(params.instance)) {
|
|
2220
|
+
currentStep = "target-shape-check";
|
|
2221
|
+
const message = `${params.instance} is not a loopback URL or a *.harperfabric.com target. ` +
|
|
2222
|
+
`For Harper Fabric behind a custom domain, use --fabric. Nothing was changed.`;
|
|
2223
|
+
push(false, message);
|
|
2224
|
+
return { ok: false, dryRun, refused: { message }, steps, failedStep: "target-shape-check" };
|
|
2225
|
+
}
|
|
1505
2226
|
// ── --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
2227
|
let cimdAllowedHosts;
|
|
1514
2228
|
if (params.cimdAllowedHosts !== undefined) {
|
|
1515
2229
|
currentStep = "cimd-allowed-hosts";
|
|
@@ -1523,7 +2237,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1523
2237
|
catch (err) {
|
|
1524
2238
|
return refuse(err?.message ?? String(err));
|
|
1525
2239
|
}
|
|
1526
|
-
const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance);
|
|
2240
|
+
const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance, params.fabric);
|
|
1527
2241
|
if (shapeRefusal)
|
|
1528
2242
|
return refuse(shapeRefusal);
|
|
1529
2243
|
const current = readLocalConfigCimdAllowedHosts(params.localConfigPath);
|
|
@@ -1552,23 +2266,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1552
2266
|
`then reads it back; a run that stops before that step does not write it); ${target.detail}`);
|
|
1553
2267
|
}
|
|
1554
2268
|
}
|
|
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
2269
|
// ── @harperfast/oauth config (flair#1136: shipped in config.yaml) ──────
|
|
1573
2270
|
// The block ships uncommented with mcp.enabled: ${FLAIR_MCP_OAUTH}
|
|
1574
2271
|
// (flair#1152), so the environment turns it on. This step writes nothing;
|
|
@@ -1597,8 +2294,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1597
2294
|
push(true, `${idpProvider} OAuth app credentials present; callback URL: ${callbackUrl}`);
|
|
1598
2295
|
if (dryRun) {
|
|
1599
2296
|
// Dry-run stops here. Under --dry-run nothing above wrote a file or made
|
|
1600
|
-
// a remote call
|
|
1601
|
-
// nothing below this line runs.
|
|
2297
|
+
// a remote call, and nothing below this line runs.
|
|
1602
2298
|
return {
|
|
1603
2299
|
ok: true,
|
|
1604
2300
|
dryRun: true,
|
|
@@ -1606,19 +2302,16 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1606
2302
|
issuer,
|
|
1607
2303
|
resource: `${issuer}/mcp`,
|
|
1608
2304
|
callbackUrl,
|
|
1609
|
-
signingKeyFilePath: keyResult.path,
|
|
1610
2305
|
};
|
|
1611
2306
|
}
|
|
1612
2307
|
// ── Secrets provisioning (shape-aware, never silent) ──────────────────────
|
|
1613
|
-
|
|
2308
|
+
currentStep = "secrets-provisioning";
|
|
1614
2309
|
const bundle = buildSecretsBundle({
|
|
1615
2310
|
issuer,
|
|
1616
|
-
signingKeyPem,
|
|
1617
2311
|
idpProvider,
|
|
1618
2312
|
idpClientId: params.idpClientId,
|
|
1619
2313
|
idpClientSecret: params.idpClientSecret,
|
|
1620
2314
|
});
|
|
1621
|
-
currentStep = "secrets-provisioning";
|
|
1622
2315
|
if (bundle.FLAIR_MCP_ISSUER !== issuer) {
|
|
1623
2316
|
throw new Error(`the FLAIR_MCP_ISSUER being pushed does not equal the issuer checked (${issuer})`);
|
|
1624
2317
|
}
|
|
@@ -1628,10 +2321,11 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1628
2321
|
// write; not staging costs an operator stranded mid-enable.
|
|
1629
2322
|
const secretsResult = provisionSecrets(params.instance, bundle, {
|
|
1630
2323
|
mechanism: params.secretsMechanism,
|
|
2324
|
+
fabric: params.fabric,
|
|
1631
2325
|
stagingPath: params.secretsStagingPath,
|
|
1632
2326
|
});
|
|
1633
2327
|
// Ask the TARGET whether it can take these, rather than inferring from its
|
|
1634
|
-
// hostname or its version
|
|
2328
|
+
// hostname or its version.
|
|
1635
2329
|
// An explicit --secrets-mechanism is an operator override and is honoured
|
|
1636
2330
|
// without a probe: they have said what they want.
|
|
1637
2331
|
let secretsPushed = false;
|
|
@@ -1664,7 +2358,9 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1664
2358
|
// ── Identity mapping (Credential kind:idp) ────────────────────────────────
|
|
1665
2359
|
currentStep = "identity-mapping";
|
|
1666
2360
|
const mapping = await provisionIdpIdentityMapping({
|
|
1667
|
-
|
|
2361
|
+
// The instance URL is the served origin: ask for its host at the hosted
|
|
2362
|
+
// ops port, the address resolveOpsUrl gives the other steps (flair#2102).
|
|
2363
|
+
hostedOrigin: params.instance,
|
|
1668
2364
|
adminUser: params.adminUser,
|
|
1669
2365
|
adminPass: params.adminPass,
|
|
1670
2366
|
principal,
|
|
@@ -1681,12 +2377,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1681
2377
|
// credential (one active credential per subject is the invariant). That is
|
|
1682
2378
|
// a credential dying, so it is stated as such, by id: an operator must
|
|
1683
2379
|
// 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
|
-
: "";
|
|
2380
|
+
const supersedeNote = supersededCredentialNote(mapping);
|
|
1690
2381
|
push(true, `connector identity: mapped sub '${params.idpSubject}' (provider '${idpProvider}') to Agent '${principal}'; ` +
|
|
1691
2382
|
`see docs/access-control.md for how /mcp tool calls use it. ` +
|
|
1692
2383
|
`principal ${mapping.principalCreated ? "created" : "already existed"}; ` +
|
|
@@ -1699,14 +2390,14 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1699
2390
|
let confirmed = Boolean(params.confirmSecretsApplied);
|
|
1700
2391
|
if (!confirmed && deps.confirmPrompt) {
|
|
1701
2392
|
confirmed = await deps.confirmPrompt(secretsPushed
|
|
1702
|
-
?
|
|
2393
|
+
? fabricTarget
|
|
1703
2394
|
? `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you restarted the Fabric instance to load them?`
|
|
1704
2395
|
: `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you loaded them into the instance's process environment?`
|
|
1705
2396
|
: `Have you applied the ${secretsResult.varNames.length} vars staged at ${secretsResult.path} to ${params.instance}'s environment?`);
|
|
1706
2397
|
}
|
|
1707
2398
|
if (!confirmed) {
|
|
1708
2399
|
push(false, secretsPushed
|
|
1709
|
-
? `not confirmed: the secrets were pushed to ${params.instance} and read back; ${
|
|
2400
|
+
? `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
2401
|
: `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
2402
|
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path };
|
|
1712
2403
|
}
|
|
@@ -1721,8 +2412,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1721
2412
|
// - Fabric: `enable` does not restart the instance; the operator applies
|
|
1722
2413
|
// the environment and restarts. Report the requirement LOUDLY — never
|
|
1723
2414
|
// report success with /mcp still dark.
|
|
1724
|
-
|
|
1725
|
-
if (isFabric) {
|
|
2415
|
+
if (fabricTarget) {
|
|
1726
2416
|
// ── Fabric: operator-deploy requirement ──────────────────────────────
|
|
1727
2417
|
currentStep = "fabric-operator-deploy";
|
|
1728
2418
|
const host = new URL(params.instance).hostname;
|
|
@@ -1732,7 +2422,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1732
2422
|
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
1733
2423
|
if (!binding.ok) {
|
|
1734
2424
|
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,
|
|
2425
|
+
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
2426
|
}
|
|
1737
2427
|
currentStep = "fabric-operator-deploy";
|
|
1738
2428
|
// The target's metadata names the issuer. Now check the public origin.
|
|
@@ -1752,7 +2442,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1752
2442
|
pasteBlock: buildClaudePasteBlock(resource),
|
|
1753
2443
|
secretsMechanism: secretsResult.mechanism,
|
|
1754
2444
|
secretsPath: secretsResult.path,
|
|
1755
|
-
signingKeyFilePath: keyResult.path,
|
|
1756
2445
|
callbackUrl,
|
|
1757
2446
|
};
|
|
1758
2447
|
}
|
|
@@ -1785,14 +2474,33 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1785
2474
|
resource: `${issuer}/mcp`,
|
|
1786
2475
|
secretsMechanism: secretsResult.mechanism,
|
|
1787
2476
|
secretsPath: secretsResult.path,
|
|
1788
|
-
signingKeyFilePath: keyResult.path,
|
|
1789
2477
|
callbackUrl,
|
|
1790
2478
|
};
|
|
1791
2479
|
}
|
|
1792
2480
|
// ── Standalone (non-Fabric): update local config + restart ────────────
|
|
1793
2481
|
currentStep = "local-config-update";
|
|
1794
2482
|
const localConfigResult = updateLocalConfigMcpEnabled(true, params.localConfigPath);
|
|
1795
|
-
|
|
2483
|
+
if (!localConfigResult.ok) {
|
|
2484
|
+
// flair#2193: stop BEFORE the restart. The mcp.enabled update was not
|
|
2485
|
+
// confirmed (the file may have changed), and the metadata checks below
|
|
2486
|
+
// could still pass and report success.
|
|
2487
|
+
const retry = params.localConfigPath
|
|
2488
|
+
? "retry the call with the same explicit path"
|
|
2489
|
+
: "re-run `flair mcp enable`";
|
|
2490
|
+
push(false, `${localConfigResult.detail} This command did not restart the instance. Fix the cause above, then ${retry}.`);
|
|
2491
|
+
return {
|
|
2492
|
+
ok: false,
|
|
2493
|
+
dryRun,
|
|
2494
|
+
steps,
|
|
2495
|
+
failedStep: "local-config-update",
|
|
2496
|
+
issuer,
|
|
2497
|
+
resource: `${issuer}/mcp`,
|
|
2498
|
+
secretsMechanism: secretsResult.mechanism,
|
|
2499
|
+
secretsPath: secretsResult.path,
|
|
2500
|
+
callbackUrl,
|
|
2501
|
+
};
|
|
2502
|
+
}
|
|
2503
|
+
push(true, localConfigResult.detail);
|
|
1796
2504
|
// flair#2113: ensure --cimd-allowed-hosts (written unless the file already
|
|
1797
2505
|
// holds that exact list) and read it back. A failure here stops the flow
|
|
1798
2506
|
// before the restart.
|
|
@@ -1812,7 +2520,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1812
2520
|
resource: `${issuer}/mcp`,
|
|
1813
2521
|
secretsMechanism: secretsResult.mechanism,
|
|
1814
2522
|
secretsPath: secretsResult.path,
|
|
1815
|
-
signingKeyFilePath: keyResult.path,
|
|
1816
2523
|
callbackUrl,
|
|
1817
2524
|
};
|
|
1818
2525
|
}
|
|
@@ -1837,7 +2544,7 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1837
2544
|
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
1838
2545
|
if (!binding.ok) {
|
|
1839
2546
|
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,
|
|
2547
|
+
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
2548
|
}
|
|
1842
2549
|
const verify = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
|
|
1843
2550
|
if (!verify.ok) {
|
|
@@ -1864,7 +2571,6 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1864
2571
|
pasteBlock: buildClaudePasteBlock(resource),
|
|
1865
2572
|
secretsMechanism: secretsResult.mechanism,
|
|
1866
2573
|
secretsPath: secretsResult.path,
|
|
1867
|
-
signingKeyFilePath: keyResult.path,
|
|
1868
2574
|
callbackUrl,
|
|
1869
2575
|
cimdAllowedHosts: writtenCimd?.hosts,
|
|
1870
2576
|
cimdAllowedHostsConfigPath: writtenCimd?.path,
|
|
@@ -1882,8 +2588,8 @@ export async function enableMcp(params, deps = {}) {
|
|
|
1882
2588
|
// Two results for one step, and the ✓ instructs several minutes of manual
|
|
1883
2589
|
// work in a web UI that the ✗ makes pointless. Read in order, you do the
|
|
1884
2590
|
// work first.
|
|
1885
|
-
// No
|
|
1886
|
-
//
|
|
2591
|
+
// No fallback step NAME: currentStep is initialised to the first step, so
|
|
2592
|
+
// there is no undefined case to invent a name for. A fallback here
|
|
1887
2593
|
// would attribute a throw to a step chosen for being a plausible default —
|
|
1888
2594
|
// the same misattribution this handler exists to prevent, one layer down.
|
|
1889
2595
|
push(false, `unexpected error: ${err?.message ?? err}`);
|
|
@@ -1922,12 +2628,147 @@ export async function disableMcp(params, deps = {}) {
|
|
|
1922
2628
|
return { ok: true, detail: `restart requested for ${params.instance}` };
|
|
1923
2629
|
}
|
|
1924
2630
|
/**
|
|
1925
|
-
*
|
|
1926
|
-
*
|
|
1927
|
-
*
|
|
1928
|
-
*
|
|
1929
|
-
*
|
|
1930
|
-
*
|
|
2631
|
+
* flair#2283 — the one-shot migration for an instance that still holds the old
|
|
2632
|
+
* staged value (`FLAIR_MCP_OAUTH=1`, recorded by `buildSecretsBundle` before
|
|
2633
|
+
* flair#1284 changed the staged value to `true`). Flair's own reader accepts
|
|
2634
|
+
* `1`, but the `@harperfast/oauth` component does not enable its MCP AS for `1`.
|
|
2635
|
+
*
|
|
2636
|
+
* Attempts an encrypted `FLAIR_MCP_OAUTH=true` push and checks the processEnv marker.
|
|
2637
|
+
* After a confirmed push and PID-verified restart, checks target and public
|
|
2638
|
+
* discovery against the requested issuer and its MCP token endpoint.
|
|
2639
|
+
* A failed probe, local encryption failure, refused or unconfirmed push, or
|
|
2640
|
+
* unconfirmed read-back attempts a 0600 fallback and returns `{ ok: false }`
|
|
2641
|
+
* before discovery checks; the CLI exits non-zero. Refresh has
|
|
2642
|
+
* a separate default filename; `--secrets-path` can select `mcp enable`'s path.
|
|
2643
|
+
* An occupied explicit path is refused before probing, including in dry run; an occupied default path
|
|
2644
|
+
* is refused when fallback is needed. The fallback writer opens exclusively.
|
|
2645
|
+
* Does not run IdP intake, apply CIMD changes or read or write IdP secret values.
|
|
2646
|
+
*/
|
|
2647
|
+
export async function refreshMcpOAuthFlag(params, deps = {}) {
|
|
2648
|
+
const steps = [];
|
|
2649
|
+
const dryRun = Boolean(params.dryRun);
|
|
2650
|
+
let currentStep = "target-shape-check";
|
|
2651
|
+
const push = (ok, detail) => steps.push({ step: currentStep, ok, detail });
|
|
2652
|
+
// Set only after the fallback writer returns successfully.
|
|
2653
|
+
let stagedFallbackPath;
|
|
2654
|
+
const targetRefusal = targetOriginRefusal(params.instance) ?? fabricLoopbackRefusal(params.instance, params.fabric);
|
|
2655
|
+
if (targetRefusal) {
|
|
2656
|
+
push(false, targetRefusal);
|
|
2657
|
+
return { ok: false, dryRun, refused: { message: targetRefusal }, steps, failedStep: "target-shape-check" };
|
|
2658
|
+
}
|
|
2659
|
+
push(true, `${params.instance}: target shape accepted`);
|
|
2660
|
+
const issuer = (params.issuer ?? params.instance).replace(/\/+$/, "");
|
|
2661
|
+
const stagedPath = params.secretsStagingPath ?? defaultRefreshSecretsStagingPath(params.instance);
|
|
2662
|
+
// The one-var fallback is written EXCLUSIVELY. An occupied path — the target's
|
|
2663
|
+
// OWN default INCLUDED — is refused by name, never truncated, because it may be
|
|
2664
|
+
// the full IdP credentials bundle a prior `mcp enable --secrets-path` staged
|
|
2665
|
+
// there (flair#2283). Returns the refusal message instead of writing in that
|
|
2666
|
+
// case; `stagedFallbackPath` is set only when a file was really created.
|
|
2667
|
+
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`;
|
|
2668
|
+
// Returns the refusal message when the target path is already occupied, or null
|
|
2669
|
+
// when the file was really created; `stagedFallbackPath` is set only in the latter
|
|
2670
|
+
// case (flair#2283).
|
|
2671
|
+
const writeFallback = () => {
|
|
2672
|
+
try {
|
|
2673
|
+
writeSecretsStagingFile(stagedPath, { FLAIR_MCP_OAUTH: "true" }, { exclusive: true });
|
|
2674
|
+
stagedFallbackPath = stagedPath;
|
|
2675
|
+
return null;
|
|
2676
|
+
}
|
|
2677
|
+
catch (err) {
|
|
2678
|
+
if (err?.code === "EEXIST")
|
|
2679
|
+
return occupiedMessage(stagedPath);
|
|
2680
|
+
throw err;
|
|
2681
|
+
}
|
|
2682
|
+
};
|
|
2683
|
+
try {
|
|
2684
|
+
currentStep = "secrets-provisioning";
|
|
2685
|
+
// An EXPLICIT staging path is the operator's own target. Refuse an occupied one
|
|
2686
|
+
// BEFORE probing, so no request is made and the file is left byte-identical
|
|
2687
|
+
// (flair#2283).
|
|
2688
|
+
if (params.secretsStagingPath && lstatSync(params.secretsStagingPath, { throwIfNoEntry: false })) {
|
|
2689
|
+
const message = occupiedMessage(params.secretsStagingPath);
|
|
2690
|
+
push(false, message);
|
|
2691
|
+
return { ok: false, dryRun, steps, refused: { message }, failedStep: "secrets-provisioning" };
|
|
2692
|
+
}
|
|
2693
|
+
if (dryRun) {
|
|
2694
|
+
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.`);
|
|
2695
|
+
return { ok: true, dryRun: true, steps };
|
|
2696
|
+
}
|
|
2697
|
+
// Attempt fallback creation when the update could not be pushed or confirmed.
|
|
2698
|
+
const cap = await probeSecretsCapability(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), { fetchImpl: deps.fetchImpl });
|
|
2699
|
+
if (!cap.available || !cap.publicKeyPem) {
|
|
2700
|
+
const refusal = writeFallback();
|
|
2701
|
+
if (refusal) {
|
|
2702
|
+
push(false, refusal);
|
|
2703
|
+
return { ok: false, dryRun, steps, refused: { message: refusal }, failedStep: "secrets-provisioning" };
|
|
2704
|
+
}
|
|
2705
|
+
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.`);
|
|
2706
|
+
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsPath: stagedFallbackPath };
|
|
2707
|
+
}
|
|
2708
|
+
const pushed = await pushSecrets(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), { FLAIR_MCP_OAUTH: "true" }, cap.publicKeyPem, { fetchImpl: deps.fetchImpl, sealImpl: deps.sealImpl });
|
|
2709
|
+
if (!pushed.allOk) {
|
|
2710
|
+
const failedResults = pushed.results.filter((r) => !r.ok);
|
|
2711
|
+
const failed = failedResults.map((r) => `${r.name} (${r.detail})`).join("; ");
|
|
2712
|
+
const lead = failedResults.every((r) => r.kind === "local-failure")
|
|
2713
|
+
? "FLAIR_MCP_OAUTH=true local encryption failure: nothing was sent, nothing stored by this attempt"
|
|
2714
|
+
: failedResults.some((r) => r.kind === "push-unconfirmed")
|
|
2715
|
+
? "FLAIR_MCP_OAUTH=true push outcome could not be confirmed (it may have been stored)"
|
|
2716
|
+
: failedResults.every((r) => r.kind === "confirm")
|
|
2717
|
+
? "FLAIR_MCP_OAUTH=true received a successful push response, but its storage with processEnv=true could not be confirmed"
|
|
2718
|
+
: "FLAIR_MCP_OAUTH=true push was refused by the target";
|
|
2719
|
+
const refusal = writeFallback()?.replace(/^/, `${lead}: ${failed}. `);
|
|
2720
|
+
if (refusal) {
|
|
2721
|
+
push(false, refusal);
|
|
2722
|
+
return { ok: false, dryRun, steps, refused: { message: refusal }, failedStep: "secrets-provisioning" };
|
|
2723
|
+
}
|
|
2724
|
+
push(false, `${lead}: ${failed}. The one-var bundle is staged at ${stagedPath} (0600); apply it and restart.`);
|
|
2725
|
+
return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsPath: stagedFallbackPath };
|
|
2726
|
+
}
|
|
2727
|
+
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.`);
|
|
2728
|
+
// Restart for the env-secrets decryptor to load the updated secret.
|
|
2729
|
+
currentStep = "restart";
|
|
2730
|
+
const pre = await captureBootDiscriminator(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
|
|
2731
|
+
await triggerRemoteRestart(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
|
|
2732
|
+
push(true, `restart triggered against ${params.instance}`);
|
|
2733
|
+
currentStep = "verify-restart";
|
|
2734
|
+
const post = await waitForOpsApi(resolveOpsUrl(params.instance), basicAuthHeader(params.adminUser, params.adminPass), pre.pid, { fetchImpl: deps.fetchImpl, timeoutMs: deps.waitForOpsApiTimeoutMs, pollMs: deps.waitForOpsApiPollMs });
|
|
2735
|
+
push(true, `process restarted: pid changed ${pre.pid} -> ${post.pid}`);
|
|
2736
|
+
// Bind the verification to the target: the target's OWN document must
|
|
2737
|
+
// advertise the issuer we are about to verify, and its token endpoint must
|
|
2738
|
+
// be the MCP one. Without this, a matching document elsewhere could let a
|
|
2739
|
+
// broken target report ok (flair#2283).
|
|
2740
|
+
currentStep = "issuer-target-binding";
|
|
2741
|
+
const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
|
|
2742
|
+
if (!binding.ok) {
|
|
2743
|
+
push(false, binding.detail);
|
|
2744
|
+
return { ok: false, dryRun, refused: { message: binding.detail }, steps, failedStep: "issuer-target-binding" };
|
|
2745
|
+
}
|
|
2746
|
+
push(true, binding.detail);
|
|
2747
|
+
// The PUBLIC document read at `issuer` must name the SAME verified issuer and
|
|
2748
|
+
// its token endpoint, else refuse by name. The discriminator is bound to the
|
|
2749
|
+
// issuer this caller verified — `issuer` — so a document naming any other
|
|
2750
|
+
// issuer is not a positive result (flair#2283).
|
|
2751
|
+
currentStep = "self-verify";
|
|
2752
|
+
const observation = await discriminateMcpOAuthDiscovery(issuer, { fetchImpl: deps.fetchImpl, expectedIssuers: [issuer] });
|
|
2753
|
+
if (observation.state !== "plugin-live") {
|
|
2754
|
+
push(false, `refused: the public document at ${issuer} did not confirm the MCP authorization server for the verified issuer ${issuer} — ${observation.detail}`);
|
|
2755
|
+
return { ok: false, dryRun, steps, failedStep: "self-verify" };
|
|
2756
|
+
}
|
|
2757
|
+
push(true, observation.detail);
|
|
2758
|
+
return { ok: true, dryRun: false, steps };
|
|
2759
|
+
}
|
|
2760
|
+
catch (err) {
|
|
2761
|
+
push(false, `unexpected error: ${err?.message ?? err}`);
|
|
2762
|
+
return { ok: false, dryRun, steps, failedStep: currentStep, secretsPath: stagedFallbackPath };
|
|
2763
|
+
}
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Reports a live public-metadata check (not a stale local marker): hits the
|
|
2767
|
+
* same well-known metadata endpoint `enable`'s self-verify step checks. An expected issuer,
|
|
2768
|
+
* exact MCP token endpoint, CIMD advertisement and, when present, a string
|
|
2769
|
+
* `registration_endpoint` verify the public metadata;
|
|
2770
|
+
* they do not prove that the token route or `/mcp` is usable. `status` reports
|
|
2771
|
+
* the live metadata check's result rather than guessing from local files.
|
|
1931
2772
|
*/
|
|
1932
2773
|
export async function mcpStatus(params, deps = {}) {
|
|
1933
2774
|
const verify = await selfVerifyMcpMetadata(params.instance, { fetchImpl: deps.fetchImpl });
|