@tpsdev-ai/flair 0.57.0 → 0.59.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.
Files changed (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -140,11 +140,13 @@
140
140
  * expansion.
141
141
  */
142
142
  import { probeSecretsCapability, pushSecrets, PROCESS_ENV_TIER } from "./secrets-push.js";
143
- import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from "node:fs";
144
- import { join, dirname } from "node:path";
143
+ import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync, realpathSync } from "node:fs";
144
+ import { hostname as osHostname } from "node:os";
145
+ import { join, dirname, resolve } from "node:path";
145
146
  import { generateKeyPairSync, randomBytes } from "node:crypto";
146
147
  import yaml from "js-yaml";
147
148
  import { resolveHome } from "./home.js";
149
+ import { defaultReadProcessCmdline, defaultReadProcessCwd } from "./upgrade-exec-path.js";
148
150
  // ─── CIMD constants ──────────────────────────────────────────────────────────
149
151
  /** Default `clientIdMetadataDocuments.allowedHosts` allowlist — see the
150
152
  * module header's "claude.ai CIMD/redirect-URI allowlist hosts" note for
@@ -251,6 +253,122 @@ export function selectSecretsMechanism(instanceUrl, override) {
251
253
  return override;
252
254
  return isFabricOrigin(instanceUrl) ? "fabric-env-secrets" : "env-file";
253
255
  }
256
+ // ─── --cimd-allowed-hosts (flair#2113) ───────────────────────────────────────
257
+ //
258
+ // The component reads `mcp.clientIdMetadataDocuments.allowedHosts` from the
259
+ // `@harperfast/oauth` block of the component config.yaml. A whole-token `${VAR}`
260
+ // there can carry ONE host, but not a comma-separated list, and it cannot keep
261
+ // the default when unset. Measured on the installed @harperfast/oauth 2.5.0
262
+ // (dist/lib/config.js, `expandEnvVar` + `normalizeMcpSecurityConfig`): the
263
+ // variable's value becomes a one-entry list and is never split on commas; an
264
+ // unset variable leaves the literal placeholder as the only entry, so the
265
+ // claude.ai + claude.com default stops applying; and an empty value becomes
266
+ // `[]`, for which dist/lib/mcp/cimd.js skips its allowedHosts gate.
267
+ //
268
+ // So `enable` ensures a literal list in a config.yaml on THIS machine (the
269
+ // file it already edits for mcp.enabled), after the preflight match in
270
+ // `checkTargetRunsFromConfig`. It refuses a Fabric origin and, outside
271
+ // --dry-run, a failed match. --dry-run skips the match and never writes the list.
272
+ /** The config key the flag sets, as operator messages name it. */
273
+ export const CIMD_ALLOWED_HOSTS_CONFIG_KEY = "mcp.clientIdMetadataDocuments.allowedHosts";
274
+ /** A `--cimd-allowed-hosts` value that is not a list of lowercase bare hostnames. */
275
+ export class CimdAllowedHostsError extends Error {
276
+ constructor(message) {
277
+ super(message);
278
+ this.name = "CimdAllowedHostsError";
279
+ }
280
+ }
281
+ const HOSTNAME_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
282
+ /**
283
+ * Validate `--cimd-allowed-hosts` entries: lowercase bare hostnames only.
284
+ * Throws `CimdAllowedHostsError` for an empty list, or for the first bad entry
285
+ * (named, 1-based). Spaces around an entry are trimmed; nothing else is
286
+ * rewritten: an uppercase entry is refused, not lowercased.
287
+ */
288
+ export function validateCimdAllowedHosts(entries) {
289
+ const flag = "--cimd-allowed-hosts";
290
+ if (entries.length === 0 || (entries.length === 1 && String(entries[0]).trim() === "")) {
291
+ throw new CimdAllowedHostsError(`${flag}: no hostnames given. Pass one or more lowercase hostnames, comma-separated (for example claude.ai,claude.com).`);
292
+ }
293
+ const hosts = [];
294
+ for (let i = 0; i < entries.length; i++) {
295
+ const host = String(entries[i]).trim();
296
+ const refuse = (why) => {
297
+ throw new CimdAllowedHostsError(`${flag} entry ${i + 1} ${why}`);
298
+ };
299
+ if (host === "")
300
+ refuse("is empty. Remove the extra comma, or pass a hostname.");
301
+ const shown = JSON.stringify(host);
302
+ if (host.includes("*"))
303
+ refuse(`(${shown}) is a wildcard. List each hostname exactly.`);
304
+ if (host.includes("/"))
305
+ refuse(`(${shown}) is a URL or path. Pass the bare hostname only.`);
306
+ if (host.startsWith("[") || host.split(":").length > 2)
307
+ refuse(`(${shown}) looks like an IPv6 address. Pass a hostname.`);
308
+ if (host.includes(":"))
309
+ refuse(`(${shown}) contains ":" (a port or scheme). Pass the bare hostname only.`);
310
+ if (host !== host.toLowerCase())
311
+ refuse(`(${shown}) has uppercase letters. Hostnames must be lowercase.`);
312
+ const labels = host.split(".");
313
+ if (host.length > 253 || !labels.every((label) => HOSTNAME_LABEL.test(label))) {
314
+ refuse(`(${shown}) is not a valid hostname: dot-separated labels of a-z, 0-9 and inner hyphens, ` +
315
+ `each 1-63 characters, 253 in all at most.`);
316
+ }
317
+ if (/^[0-9]+$/.test(labels[labels.length - 1]))
318
+ refuse(`(${shown}) ends in a numeric label, as an IP address does. Pass a hostname.`);
319
+ if (hosts.includes(host))
320
+ refuse(`(${shown}) repeats an earlier entry.`);
321
+ hosts.push(host);
322
+ }
323
+ return hosts;
324
+ }
325
+ /**
326
+ * The refusal for a Fabric target, else null. `enable` writes a config.yaml
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))
332
+ return null;
333
+ return (`--cimd-allowed-hosts is refused for a Fabric instance (${new URL(instanceUrl).hostname}): ` +
334
+ `the component reads ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} from the @harperfast/oauth block of the config.yaml ` +
335
+ `deployed with it, and this command does not write that file. ` +
336
+ `Set the key in the config.yaml you deploy, then redeploy. Nothing was changed.`);
337
+ }
338
+ /**
339
+ * The CLI's reading of `--cimd-allowed-hosts`: `{}` when the flag is absent,
340
+ * `{ hosts }` when it is valid for this target, `{ error }` otherwise. An
341
+ * explicit empty value is an error, never "absent".
342
+ */
343
+ export function cimdAllowedHostsFromFlag(raw, instanceUrl) {
344
+ if (raw === undefined)
345
+ return {};
346
+ let hosts;
347
+ try {
348
+ hosts = validateCimdAllowedHosts(String(raw).split(","));
349
+ }
350
+ catch (err) {
351
+ return { error: err?.message ?? String(err) };
352
+ }
353
+ const refusal = cimdAllowedHostsShapeRefusal(instanceUrl);
354
+ return refusal ? { error: refusal } : { hosts };
355
+ }
356
+ /**
357
+ * The note a successful `enable` prints when the list this run confirmed
358
+ * leaves claude.ai out. `enable` ensures the requested list in config.yaml
359
+ * (it writes the list only when the file does not already hold that exact
360
+ * list) and reads it back; the argument is that read-back list.
361
+ * dist/lib/mcp/cimd.js treats a client_id URL whose host is not on a non-empty
362
+ * allowedHosts as an unknown client. Null when this run confirmed no list, or
363
+ * one with claude.ai.
364
+ */
365
+ export function claudeAiExcludedNote(written) {
366
+ if (!written || written.includes("claude.ai"))
367
+ return null;
368
+ return (`claude.ai is not in the ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} list this run ensured and read back (${JSON.stringify(written)}), ` +
369
+ `so while the instance uses that list, a CIMD client_id URL on claude.ai is refused. ` +
370
+ `Re-run with claude.ai in --cimd-allowed-hosts to allow it.`);
371
+ }
254
372
  /** RS256 signing keypair for `mcp.signingKeyPem` — `crypto.generateKeyPairSync`,
255
373
  * never a PRNG shortcut (Sherlock's Model-2 requirement 2 implementation note). */
256
374
  export function generateRsaSigningKeyPair() {
@@ -360,6 +478,18 @@ export function buildMcpOAuthConfigBlock(params) {
360
478
  * bundle stages FLAIR_MCP_OAUTH=true — see buildSecretsBundle for why it
361
479
  * must be "true"), never as a literal in the config file. */
362
480
  export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
481
+ /**
482
+ * The local component config.yaml `enable` edits: `explicitPath` alone when
483
+ * given, otherwise `./config.yaml`, then `~/.flair/config.yaml` — the first
484
+ * that exists. Shared by `updateLocalConfigMcpEnabled` and the flair#2113
485
+ * allowedHosts writer so both edit the same file.
486
+ */
487
+ function resolveLocalConfigPath(explicitPath) {
488
+ const candidates = explicitPath
489
+ ? [explicitPath]
490
+ : ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
491
+ return { configPath: candidates.find((p) => existsSync(p)) ?? null, candidates };
492
+ }
363
493
  /**
364
494
  * Set mcp.enabled in a local component config.yaml to the flair#1152 shape.
365
495
  * Best-effort: returns `{ ok: false }` with a reason when the file can't be
@@ -375,16 +505,7 @@ export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
375
505
  * `~/.flair/config.yaml`.
376
506
  */
377
507
  export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
378
- const candidates = explicitPath
379
- ? [explicitPath]
380
- : ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
381
- let configPath = null;
382
- for (const p of candidates) {
383
- if (existsSync(p)) {
384
- configPath = p;
385
- break;
386
- }
387
- }
508
+ const { configPath, candidates } = resolveLocalConfigPath(explicitPath);
388
509
  // The value the file should carry for this call (flair#1152): the env
389
510
  // reference when enabling, literal false when disabling.
390
511
  const target = enabled ? MCP_ENABLED_ENV_REFERENCE : false;
@@ -447,6 +568,296 @@ export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
447
568
  }
448
569
  return { ok: true, detail: `mcp.enabled set to ${targetLabel} in ${configPath}` };
449
570
  }
571
+ const readConfigFile = (path) => readFileSync(path, "utf-8");
572
+ const writeConfigFile = (path, data) => writeFileSync(path, data, { encoding: "utf-8" });
573
+ /** Parse `path` and reach its `@harperfast/oauth` → `mcp` mapping. Every failure is a named `ok: false`. */
574
+ function loadOauthMcpBlock(path, readFile) {
575
+ let raw;
576
+ try {
577
+ raw = readFile(path);
578
+ }
579
+ catch (err) {
580
+ return { ok: false, detail: `cannot read ${path}: ${err?.message ?? err}` };
581
+ }
582
+ let doc;
583
+ try {
584
+ doc = yaml.load(raw);
585
+ }
586
+ catch (err) {
587
+ return { ok: false, detail: `cannot parse ${path} as YAML: ${err?.message ?? err}` };
588
+ }
589
+ const isMapping = (v) => !!v && typeof v === "object" && !Array.isArray(v);
590
+ const mcp = isMapping(doc) && isMapping(doc["@harperfast/oauth"]) ? doc["@harperfast/oauth"].mcp : undefined;
591
+ if (!isMapping(mcp))
592
+ return { ok: false, detail: `${path} has no @harperfast/oauth block with an mcp mapping` };
593
+ const cimd = mcp.clientIdMetadataDocuments;
594
+ if (cimd !== undefined && cimd !== null && !isMapping(cimd)) {
595
+ return { ok: false, detail: `${path}: mcp.clientIdMetadataDocuments is not a mapping` };
596
+ }
597
+ return { ok: true, detail: `${path} parsed`, raw, doc, mcp };
598
+ }
599
+ function sameHostList(value, hosts) {
600
+ return Array.isArray(value) && value.length === hosts.length && value.every((h, i) => h === hosts[i]);
601
+ }
602
+ /**
603
+ * Read-only: which config.yaml would `updateLocalConfigCimdAllowedHosts` write,
604
+ * and what list does it carry now? Same file resolution as
605
+ * `updateLocalConfigMcpEnabled`. `enable` runs this before any step with a
606
+ * side effect, so a file that is missing, unreadable or not valid YAML, or that
607
+ * has no `@harperfast/oauth` → `mcp` mapping, refuses the flag up front. It
608
+ * does not check that the file can be written: a write failure fails the later
609
+ * `local-config-update` step.
610
+ */
611
+ export function readLocalConfigCimdAllowedHosts(explicitPath, deps = {}) {
612
+ const { configPath: found, candidates } = resolveLocalConfigPath(explicitPath);
613
+ if (!found)
614
+ return { ok: false, detail: `no config.yaml found (tried: ${candidates.join(", ")})` };
615
+ const configPath = resolve(found);
616
+ const loaded = loadOauthMcpBlock(configPath, deps.readFile ?? readConfigFile);
617
+ if (!loaded.ok)
618
+ return { ok: false, path: configPath, detail: loaded.detail };
619
+ return {
620
+ ok: true,
621
+ path: configPath,
622
+ current: loaded.mcp.clientIdMetadataDocuments?.allowedHosts,
623
+ detail: `${configPath} carries ${CIMD_ALLOWED_HOSTS_CONFIG_KEY}: ${JSON.stringify(loaded.mcp.clientIdMetadataDocuments?.allowedHosts ?? null)}`,
624
+ };
625
+ }
626
+ /**
627
+ * The application directory a Harper `run` or `dev` command line names,
628
+ * resolved against the process's working directory; null when the command
629
+ * line has no `run`/`dev` token. With no directory argument Harper runs the
630
+ * application in its working directory (harper's bin/harper.js: `dev` falls
631
+ * through to `run`, whose folder argument is realpath'd from the cwd).
632
+ */
633
+ export function harperAppDirFromCmdline(cmdline, cwd) {
634
+ const tokens = cmdline.split(/\0|\s+/).filter((t) => t.length > 0);
635
+ const at = tokens.findIndex((t) => t === "run" || t === "dev");
636
+ if (at === -1)
637
+ return null;
638
+ const arg = tokens[at + 1];
639
+ return resolve(cwd, arg && !arg.startsWith("-") ? arg : ".");
640
+ }
641
+ /**
642
+ * flair#2113 review: the preflight match between the target and `configPath`.
643
+ * All required:
644
+ * 1. the target's ops API `system_information` reports this machine's
645
+ * hostname and a Harper core process id;
646
+ * 2. that pid's working directory and command line can be read on this
647
+ * machine, and the command line names a `run`/`dev` application
648
+ * directory (`harperAppDirFromCmdline`);
649
+ * 3. `config.yaml` in that application directory and `configPath` resolve
650
+ * to the same file (`realpath`).
651
+ * A check that fails, or cannot be completed, gives `ok: false` with the
652
+ * reason.
653
+ */
654
+ export async function checkTargetRunsFromConfig(instance, adminUser, adminPass, configPath, deps = {}) {
655
+ const fetchImpl = deps.fetchImpl ?? fetch;
656
+ const readCwd = deps.readProcessCwd ?? defaultReadProcessCwd;
657
+ const readCmdline = deps.readProcessCmdline ?? defaultReadProcessCmdline;
658
+ const localHost = (deps.localHostname ?? osHostname)();
659
+ const opsUrl = resolveOpsUrl(instance);
660
+ let data;
661
+ try {
662
+ const res = await fetchImpl(opsUrl, {
663
+ method: "POST",
664
+ headers: { "Content-Type": "application/json", Authorization: basicAuthHeader(adminUser, adminPass) },
665
+ body: JSON.stringify({ operation: "system_information", attributes: ["system", "harperdb_processes"] }),
666
+ });
667
+ if (!res.ok) {
668
+ return { ok: false, detail: `the target's ops API at ${opsUrl} answered system_information with HTTP ${res.status}` };
669
+ }
670
+ data = await res.json();
671
+ }
672
+ catch (err) {
673
+ return { ok: false, detail: `could not ask the target's ops API at ${opsUrl} for system_information: ${err?.message ?? err}` };
674
+ }
675
+ const targetHost = data?.system?.hostname;
676
+ const pid = data?.harperdb_processes?.core?.[0]?.pid;
677
+ if (typeof targetHost !== "string" || targetHost === "" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
678
+ return { ok: false, detail: `the target's system_information did not report both its hostname and its Harper process id` };
679
+ }
680
+ if (targetHost.toLowerCase() !== localHost.toLowerCase()) {
681
+ return { ok: false, detail: `the target reports host ${JSON.stringify(targetHost)}, and this machine is ${JSON.stringify(localHost)}` };
682
+ }
683
+ const cwd = readCwd(pid);
684
+ if (!cwd) {
685
+ return { ok: false, detail: `the target reports pid ${pid}, and that pid's working directory could not be read on this machine` };
686
+ }
687
+ const cmdline = readCmdline(pid);
688
+ const appDir = cmdline ? harperAppDirFromCmdline(cmdline, cwd) : null;
689
+ if (!appDir) {
690
+ return {
691
+ ok: false,
692
+ detail: `the target reports pid ${pid}, which runs in ${cwd} on this machine, and its application directory could not be read from its command line`,
693
+ };
694
+ }
695
+ let targetConfig;
696
+ let editedConfig;
697
+ try {
698
+ targetConfig = realpathSync(join(appDir, "config.yaml"));
699
+ editedConfig = realpathSync(configPath);
700
+ }
701
+ catch (err) {
702
+ return { ok: false, detail: `the target reports pid ${pid}, whose command line on this machine names application directory ${appDir}, and a config.yaml could not be resolved: ${err?.message ?? err}` };
703
+ }
704
+ if (targetConfig !== editedConfig) {
705
+ return { ok: false, detail: `the target reports pid ${pid}, whose command line on this machine names application directory ${appDir}; its config.yaml is not ${editedConfig} by realpath` };
706
+ }
707
+ return {
708
+ ok: true,
709
+ detail: `preflight match: the target reports host ${targetHost} and pid ${pid}; that pid's command line on this machine names application directory ${appDir}, whose config.yaml is ${editedConfig} by realpath`,
710
+ };
711
+ }
712
+ /**
713
+ * Replace the value of `@harperfast/oauth` → `mcp` → `clientIdMetadataDocuments`
714
+ * → `allowedHosts` in `raw` with a block sequence of `hosts`, touching no line
715
+ * outside the list's own lines (comments between its items go with it).
716
+ * Returns null when the key is absent, appears more than once, or has a value
717
+ * this line scan does not handle (for example a flow sequence spanning lines);
718
+ * the caller then re-emits the parsed document instead. The caller also
719
+ * re-parses the result and compares it with the intended document before
720
+ * using it.
721
+ */
722
+ function replaceAllowedHostsLines(raw, hosts) {
723
+ const path = ["@harperfast/oauth", "mcp", "clientIdMetadataDocuments", "allowedHosts"];
724
+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";
725
+ const lines = raw.split(eol);
726
+ const skippable = (line) => /^\s*(#.*)?$/.test(line);
727
+ const indentOf = (line) => line.length - line.trimStart().length;
728
+ const keyLine = /^\s*(?:"([^"]*)"|'([^']*)'|([^\s#'"\-][^:#]*?))\s*:(?:\s+(.*))?$/;
729
+ const stack = [];
730
+ let at = -1;
731
+ let atIndent = 0;
732
+ let atRest = "";
733
+ for (let i = 0; i < lines.length; i++) {
734
+ const line = lines[i];
735
+ if (skippable(line))
736
+ continue;
737
+ const indent = indentOf(line);
738
+ while (stack.length > 0 && stack[stack.length - 1].indent >= indent)
739
+ stack.pop();
740
+ const m = keyLine.exec(line);
741
+ if (!m)
742
+ continue;
743
+ stack.push({ indent, key: m[1] ?? m[2] ?? m[3] });
744
+ if (stack.length === path.length && stack.every((s, k) => s.key === path[k])) {
745
+ if (at !== -1)
746
+ return null;
747
+ at = i;
748
+ atIndent = indent;
749
+ atRest = (m[4] ?? "").replace(/(^|\s+)#.*$/, "").trim();
750
+ }
751
+ }
752
+ if (at === -1)
753
+ return null;
754
+ let end = at;
755
+ if (atRest === "") {
756
+ for (let j = at + 1; j < lines.length; j++) {
757
+ const line = lines[j];
758
+ if (skippable(line))
759
+ continue;
760
+ const indent = indentOf(line);
761
+ if (indent > atIndent || (indent === atIndent && line.trimStart().startsWith("-"))) {
762
+ end = j;
763
+ continue;
764
+ }
765
+ break;
766
+ }
767
+ }
768
+ else if (atRest.startsWith("[") && !atRest.endsWith("]")) {
769
+ return null;
770
+ }
771
+ const pad = " ".repeat(atIndent);
772
+ const block = [`${pad}allowedHosts:`, ...hosts.map((h) => `${pad} - ${JSON.stringify(h)}`)];
773
+ return [...lines.slice(0, at), ...block, ...lines.slice(end + 1)].join(eol);
774
+ }
775
+ /**
776
+ * Set `mcp.clientIdMetadataDocuments.allowedHosts` in the local component
777
+ * config.yaml (same file resolution as `updateLocalConfigMcpEnabled`) to
778
+ * `hosts`, then read the file back. `ok: true` only when the read-back equals
779
+ * `hosts`; `readBack` is that read-back, never the intended value.
780
+ *
781
+ * The edit rewrites only the list's own lines when it can find them and the
782
+ * result parses to the intended document, so comments outside the list
783
+ * survive; otherwise it re-emits the parsed document, as
784
+ * `updateLocalConfigMcpEnabled` does, and says so in `detail`.
785
+ */
786
+ export function updateLocalConfigCimdAllowedHosts(hosts, explicitPath, deps = {}) {
787
+ const readFile = deps.readFile ?? readConfigFile;
788
+ const writeFile = deps.writeFile ?? writeConfigFile;
789
+ let list;
790
+ try {
791
+ list = validateCimdAllowedHosts(hosts);
792
+ }
793
+ catch (err) {
794
+ return { ok: false, detail: err?.message ?? String(err) };
795
+ }
796
+ const { configPath: found, candidates } = resolveLocalConfigPath(explicitPath);
797
+ if (!found)
798
+ return { ok: false, detail: `no config.yaml found (tried: ${candidates.join(", ")})` };
799
+ const configPath = resolve(found);
800
+ const loaded = loadOauthMcpBlock(configPath, readFile);
801
+ if (!loaded.ok)
802
+ return { ok: false, path: configPath, detail: loaded.detail };
803
+ let how;
804
+ let wrote = false;
805
+ if (sameHostList(loaded.mcp.clientIdMetadataDocuments?.allowedHosts, list)) {
806
+ how = "the file already held this list, so the allowed-hosts write was skipped";
807
+ }
808
+ else {
809
+ const intended = structuredClone(loaded.doc);
810
+ const mcp = intended["@harperfast/oauth"].mcp;
811
+ mcp.clientIdMetadataDocuments = { ...(mcp.clientIdMetadataDocuments ?? {}), allowedHosts: [...list] };
812
+ const edited = replaceAllowedHostsLines(loaded.raw ?? "", list);
813
+ let text;
814
+ if (edited !== null && JSON.stringify(safeYamlLoad(edited)) === JSON.stringify(intended)) {
815
+ text = edited;
816
+ how = "only the list's own lines were rewritten";
817
+ }
818
+ else {
819
+ text = yaml.dump(intended, { lineWidth: -1, noCompatMode: true });
820
+ how = "the file was re-emitted from its parsed form, so its comments were not kept";
821
+ }
822
+ try {
823
+ writeFile(configPath, text);
824
+ }
825
+ catch (err) {
826
+ return { ok: false, path: configPath, detail: `cannot write ${configPath}: ${err?.message ?? err}` };
827
+ }
828
+ wrote = true;
829
+ }
830
+ const back = loadOauthMcpBlock(configPath, readFile);
831
+ if (!back.ok) {
832
+ return {
833
+ ok: false,
834
+ path: configPath,
835
+ detail: `${wrote ? `wrote ${configPath} but ` : ""}could not read it back: ${back.detail}`,
836
+ };
837
+ }
838
+ const readBack = back.mcp.clientIdMetadataDocuments?.allowedHosts;
839
+ if (!sameHostList(readBack, list)) {
840
+ return {
841
+ ok: false,
842
+ path: configPath,
843
+ detail: `${configPath} reads back ${CIMD_ALLOWED_HOSTS_CONFIG_KEY}: ${JSON.stringify(readBack ?? null)}, not ${JSON.stringify(list)}`,
844
+ };
845
+ }
846
+ return {
847
+ ok: true,
848
+ path: configPath,
849
+ readBack: [...readBack],
850
+ detail: `${CIMD_ALLOWED_HOSTS_CONFIG_KEY} in ${configPath} reads back as ${JSON.stringify(readBack)} (${how})`,
851
+ };
852
+ }
853
+ function safeYamlLoad(text) {
854
+ try {
855
+ return yaml.load(text);
856
+ }
857
+ catch {
858
+ return undefined;
859
+ }
860
+ }
450
861
  /** The exact callback URL to hand the operator when they create the IdP
451
862
  * OAuth app ("with the exact GitHub callback URL printed"). */
452
863
  export function idpCallbackUrl(issuer, idpProvider) {
@@ -635,9 +1046,11 @@ export async function provisionIdpIdentityMapping(params, deps = {}) {
635
1046
  //
636
1047
  // 404 in particular almost always means the request reached the SERVED
637
1048
  // origin instead of the ops API: the flair REST component owns `/` there and
638
- // answers 404. Say that, and name the flag that fixes it.
1049
+ // answers 404. Say that, and say where the address came from: `enable` has
1050
+ // no option to point its ops calls elsewhere (flair#2116: this hint used to
1051
+ // name an --ops-url flag that does not exist).
639
1052
  const hint = findRes.status === 404
640
- ? ` — 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. Pass --ops-url <url> to point at it explicitly.`
1053
+ ? ` — 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}.`
641
1054
  : "";
642
1055
  throw new Error(`Identity mapping: the ops API call to ${opsUrl} failed (HTTP ${findRes.status})${hint}${text ? `: ${text}` : ""}`);
643
1056
  }
@@ -792,6 +1205,52 @@ export async function triggerRemoteRestart(opsPortOrUrl, adminUser, adminPass, d
792
1205
  throw new Error(`restart failed (HTTP ${restartRes.status}): ${text}`);
793
1206
  }
794
1207
  }
1208
+ /** Fetch and parse the metadata document at an origin without assuming its
1209
+ * `issuer` equals that origin. A target can serve a public proxy issuer. */
1210
+ async function fetchOAuthMetadata(origin, deps = {}) {
1211
+ const url = `${origin.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`;
1212
+ const fetchImpl = deps.fetchImpl ?? fetch;
1213
+ let res;
1214
+ try {
1215
+ res = await fetchImpl(url, {
1216
+ signal: AbortSignal.timeout(15_000),
1217
+ ...(deps.redirect ? { redirect: deps.redirect } : {}),
1218
+ });
1219
+ }
1220
+ catch (err) {
1221
+ return { ok: false, unreachable: true, detail: `could not reach ${url}: ${err?.message ?? err}` };
1222
+ }
1223
+ 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." };
1225
+ }
1226
+ if (!res.ok) {
1227
+ return { ok: false, detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?` };
1228
+ }
1229
+ try {
1230
+ return { ok: true, url, body: await res.json() };
1231
+ }
1232
+ catch {
1233
+ return { ok: false, detail: `${url} did not return JSON` };
1234
+ }
1235
+ }
1236
+ async function verifyTargetIssuer(instance, issuer, deps = {}) {
1237
+ const target = await fetchOAuthMetadata(instance, { ...deps, redirect: "manual" });
1238
+ 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\`.`;
1239
+ if (target.ok === false)
1240
+ return { ok: false, detail: `Cannot confirm the target's configured issuer: ${target.detail} ${remedy}` };
1241
+ if (target.body?.issuer !== issuer) {
1242
+ const actual = target.body?.issuer;
1243
+ const found = typeof actual === "string" ? `names issuer=${JSON.stringify(actual)}` : `has no string issuer (got ${JSON.stringify(actual)})`;
1244
+ return { ok: false, detail: `The target's own metadata at ${target.url} ${found}; expected ${issuer}. ${remedy}` };
1245
+ }
1246
+ if (target.body?.token_endpoint !== `${issuer}/oauth/mcp/token`) {
1247
+ return {
1248
+ ok: false,
1249
+ 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\`.`,
1250
+ };
1251
+ }
1252
+ return { ok: true, detail: `Issuer ${issuer} matched the target's own OAuth authorization-server metadata at ${target.url}` };
1253
+ }
795
1254
  /**
796
1255
  * Hit the OAuth metadata endpoint from the operator's machine against the
797
1256
  * PUBLIC origin — the verification that matters is the one claude.ai's
@@ -806,29 +1265,11 @@ export async function triggerRemoteRestart(opsPortOrUrl, adminUser, adminPass, d
806
1265
  * `flair mcp status`, so all four commands agree on what "enabled" means.
807
1266
  */
808
1267
  export async function selfVerifyMcpMetadata(issuer, deps = {}) {
809
- const fetchImpl = deps.fetchImpl ?? fetch;
810
1268
  const normalizedIssuer = issuer.replace(/\/+$/, "");
811
- const url = `${normalizedIssuer}/.well-known/oauth-authorization-server`;
812
- let res;
813
- try {
814
- res = await fetchImpl(url, { signal: AbortSignal.timeout(15_000) });
815
- }
816
- catch (err) {
817
- return { ok: false, detail: `could not reach ${url}: ${err?.message ?? err}` };
818
- }
819
- if (!res.ok) {
820
- return {
821
- ok: false,
822
- detail: `${url} returned HTTP ${res.status} — is FLAIR_MCP_OAUTH actually set on the restarted instance?`,
823
- };
824
- }
825
- let body;
826
- try {
827
- body = await res.json();
828
- }
829
- catch {
830
- return { ok: false, detail: `${url} did not return JSON` };
831
- }
1269
+ const metadata = await fetchOAuthMetadata(normalizedIssuer, deps);
1270
+ if (metadata.ok === false)
1271
+ return metadata;
1272
+ const { url, body } = metadata;
832
1273
  // ── The flair's-own-server check runs BEFORE the shape check (flair#1094) ──
833
1274
  //
834
1275
  // It used to run after, and that made the DEFAULT flag-off case misreport.
@@ -1028,9 +1469,8 @@ export async function captureBootDiscriminator(opsPortOrUrl, adminUser, adminPas
1028
1469
  * hope).
1029
1470
  *
1030
1471
  * flair#756: no DCR step anywhere in this flow — CIMD needs no
1031
- * pre-registration, so there is nothing to do after the restart besides
1032
- * self-verify. `self-verify` is now the ONLY live call that happens after
1033
- * `apply-config-and-restart`.
1472
+ * pre-registration. The target's MCP metadata issuer is
1473
+ * checked before the public issuer metadata can count as completion.
1034
1474
  */
1035
1475
  export async function enableMcp(params, deps = {}) {
1036
1476
  const steps = [];
@@ -1062,18 +1502,86 @@ export async function enableMcp(params, deps = {}) {
1062
1502
  const principal = params.principal ?? "self";
1063
1503
  const principalKind = params.principalKind ?? "human";
1064
1504
  try {
1505
+ // ── --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
+ let cimdAllowedHosts;
1514
+ if (params.cimdAllowedHosts !== undefined) {
1515
+ currentStep = "cimd-allowed-hosts";
1516
+ const refuse = (message) => {
1517
+ push(false, message);
1518
+ return { ok: false, dryRun, refused: { message }, steps, failedStep: "cimd-allowed-hosts" };
1519
+ };
1520
+ try {
1521
+ cimdAllowedHosts = validateCimdAllowedHosts(params.cimdAllowedHosts);
1522
+ }
1523
+ catch (err) {
1524
+ return refuse(err?.message ?? String(err));
1525
+ }
1526
+ const shapeRefusal = cimdAllowedHostsShapeRefusal(params.instance);
1527
+ if (shapeRefusal)
1528
+ return refuse(shapeRefusal);
1529
+ const current = readLocalConfigCimdAllowedHosts(params.localConfigPath);
1530
+ if (!current.ok) {
1531
+ return refuse(`--cimd-allowed-hosts cannot be applied: ${current.detail}. Run this command on the instance's host, from the ` +
1532
+ `directory that holds the config.yaml it runs from, or edit ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} there by hand. ` +
1533
+ `Nothing was changed.`);
1534
+ }
1535
+ const change = `${CIMD_ALLOWED_HOSTS_CONFIG_KEY} in ${current.path}: ${JSON.stringify(current.current ?? null)} -> ` +
1536
+ `${JSON.stringify(cimdAllowedHosts)}`;
1537
+ if (dryRun) {
1538
+ push(true, `${change} (--dry-run: the target was not checked, and the list was not written)`);
1539
+ }
1540
+ else {
1541
+ const target = await checkTargetRunsFromConfig(params.instance, params.adminUser, params.adminPass, current.path, {
1542
+ fetchImpl: deps.fetchImpl,
1543
+ readProcessCwd: deps.readProcessCwd,
1544
+ readProcessCmdline: deps.readProcessCmdline,
1545
+ localHostname: deps.localHostname,
1546
+ });
1547
+ if (!target.ok) {
1548
+ return refuse(`--cimd-allowed-hosts refused: ${target.detail}. Edit ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} by hand in the ` +
1549
+ `config.yaml the target runs from, on its host, then restart it. Nothing was changed.`);
1550
+ }
1551
+ push(true, `${change} (the local-config-update step, before the restart, writes it unless the file already holds that exact list, ` +
1552
+ `then reads it back; a run that stops before that step does not write it); ${target.detail}`);
1553
+ }
1554
+ }
1065
1555
  // ── RS256 signing keypair ─────────────────────────────────────────────────
1066
1556
  currentStep = "signing-key";
1067
- const keyResult = ensureSigningKeyFile(params.signingKeyFilePath, { generate: deps.generateRsaKeyPair });
1068
- push(true, `signing key ${keyResult.reused ? "reused" : "generated"} at ${keyResult.path} (0600)`);
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
+ }
1069
1572
  // ── @harperfast/oauth config (flair#1136: shipped in config.yaml) ──────
1070
- // The block ships uncommented with mcp.enabled: false (inert default).
1573
+ // The block ships uncommented with mcp.enabled: ${FLAIR_MCP_OAUTH}
1574
+ // (flair#1152), so the environment turns it on. This step writes nothing;
1575
+ // it reports the block config.yaml ships (flair#2116: it used to print
1576
+ // false), and a --cimd-allowed-hosts value only as requested, never as shipped.
1071
1577
  // set_configuration is removed — the block lives in the component's own
1072
1578
  // config.yaml, not in harperdb-config.yaml where Fabric would wipe it.
1073
- const cimdAllowedHosts = params.cimdAllowedHosts ?? DEFAULT_CIMD_ALLOWED_HOSTS;
1074
1579
  currentStep = "config-block";
1075
- push(true, `@harperfast/oauth config ships in config.yaml (mcp.enabled=false, ` +
1076
- `dynamicClientRegistration.enabled=false, clientIdMetadataDocuments.allowedHosts=${JSON.stringify(cimdAllowedHosts)})`);
1580
+ push(true, `@harperfast/oauth config ships in config.yaml; this step writes nothing (mcp.enabled=${MCP_ENABLED_ENV_REFERENCE}, read from the instance environment; ` +
1581
+ `dynamicClientRegistration.enabled=false, clientIdMetadataDocuments.allowedHosts=${JSON.stringify(DEFAULT_CIMD_ALLOWED_HOSTS)})` +
1582
+ (cimdAllowedHosts
1583
+ ? `; --cimd-allowed-hosts ${JSON.stringify(cimdAllowedHosts)} was requested; the cimd-allowed-hosts step above says whether and when this run writes it`
1584
+ : ""));
1077
1585
  // ── IdP OAuth-app credential intake ───────────────────────────────────────
1078
1586
  currentStep = "idp-credentials";
1079
1587
  const callbackUrl = idpCallbackUrl(issuer, idpProvider);
@@ -1088,9 +1596,9 @@ export async function enableMcp(params, deps = {}) {
1088
1596
  }
1089
1597
  push(true, `${idpProvider} OAuth app credentials present; callback URL: ${callbackUrl}`);
1090
1598
  if (dryRun) {
1091
- // Dry-run stops here — everything above is pure/local generation; no
1092
- // remote mutation has happened, and nothing below this line would run
1093
- // without --dry-run either.
1599
+ // Dry-run stops here. Under --dry-run nothing above wrote a file or made
1600
+ // a remote call (the signing-key step only reports the key path), and
1601
+ // nothing below this line runs.
1094
1602
  return {
1095
1603
  ok: true,
1096
1604
  dryRun: true,
@@ -1111,6 +1619,9 @@ export async function enableMcp(params, deps = {}) {
1111
1619
  idpClientSecret: params.idpClientSecret,
1112
1620
  });
1113
1621
  currentStep = "secrets-provisioning";
1622
+ if (bundle.FLAIR_MCP_ISSUER !== issuer) {
1623
+ throw new Error(`the FLAIR_MCP_ISSUER being pushed does not equal the issuer checked (${issuer})`);
1624
+ }
1114
1625
  // Stage first, unconditionally. If the push works the file is a no-op the
1115
1626
  // operator never opens; if anything about the push is uncertain they still
1116
1627
  // have the thing that always works, without a re-run. Staging costs a 0600
@@ -1176,45 +1687,94 @@ export async function enableMcp(params, deps = {}) {
1176
1687
  `They no longer resolve, and anything relying on them stops working. ` +
1177
1688
  `Exactly one active credential per (kind, idpSubject) is the invariant that keeps resolution deterministic.`
1178
1689
  : "";
1179
- push(true, `connector identity: sub '${params.idpSubject}' (provider '${idpProvider}') resolves to Agent '${principal}' — ` +
1180
- `every /mcp call reads and writes AS '${principal}'. ` +
1690
+ push(true, `connector identity: mapped sub '${params.idpSubject}' (provider '${idpProvider}') to Agent '${principal}'; ` +
1691
+ `see docs/access-control.md for how /mcp tool calls use it. ` +
1181
1692
  `principal ${mapping.principalCreated ? "created" : "already existed"}; ` +
1182
1693
  `Credential(kind:idp) ${mapping.credentialReused ? "re-pointed" : "created"} (${mapping.credentialId}).` +
1183
1694
  `${supersedeNote} ` +
1184
1695
  `If your CLI signs as a DIFFERENT agent id, the connector sees that agent's DISTINCT memory scope (by design) — ` +
1185
1696
  `re-run with --principal <your-agent-id> to link them. ` +
1186
1697
  `Diagnostic: the bootstrap tool's agentId/scope fields always say who the server resolved you to.`);
1187
- // ── Gate: confirm the staged secrets are actually live before restarting ─
1698
+ // ── Gate: require confirmation that the secrets are live before continuing
1188
1699
  let confirmed = Boolean(params.confirmSecretsApplied);
1189
1700
  if (!confirmed && deps.confirmPrompt) {
1190
- confirmed = await deps.confirmPrompt(`Have you applied the ${secretsResult.varNames.length} vars staged at ${secretsResult.path} to ${params.instance}'s environment?`);
1701
+ confirmed = await deps.confirmPrompt(secretsPushed
1702
+ ? isFabricOrigin(params.instance)
1703
+ ? `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you restarted the Fabric instance to load them?`
1704
+ : `The ${secretsResult.varNames.length} secrets were pushed to ${params.instance} and read back. Have you loaded them into the instance's process environment?`
1705
+ : `Have you applied the ${secretsResult.varNames.length} vars staged at ${secretsResult.path} to ${params.instance}'s environment?`);
1191
1706
  }
1192
1707
  if (!confirmed) {
1193
- push(false, `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).`);
1708
+ push(false, secretsPushed
1709
+ ? `not confirmed: the secrets were pushed to ${params.instance} and read back; ${isFabricOrigin(params.instance) ? "restart the Fabric instance" : "load them into the instance's process environment"}, then re-run \`flair mcp enable\` with --confirm-secrets-applied.`
1710
+ : `not applied: pass --confirm-secrets-applied once the staged secrets are live on ${params.instance}, then re-run \`flair mcp enable\` (earlier steps are idempotent and will reuse what's already provisioned).`);
1194
1711
  return { ok: false, dryRun, steps, failedStep: "secrets-provisioning", secretsMechanism: secretsResult.mechanism, secretsPath: secretsResult.path };
1195
1712
  }
1196
1713
  // ── flair#1136: config delivery is now SHIPPED in config.yaml ────────────
1197
- // The @harperfast/oauth block ships uncommented with mcp.enabled: false
1198
- // (inert default). set_configuration is REMOVED — Fabric regenerates
1199
- // harperdb-config.yaml on every container restart, so writing the block
1200
- // there was always a race against the next deploy. Instead:
1714
+ // The @harperfast/oauth block ships uncommented with mcp.enabled:
1715
+ // ${FLAIR_MCP_OAUTH} (flair#1152). set_configuration is REMOVED — Fabric
1716
+ // regenerates harperdb-config.yaml on every container restart, so writing
1717
+ // the block there was always a race against the next deploy. Instead:
1201
1718
  //
1202
- // - Standalone-local: flip mcp.enabled to true in the local config.yaml,
1203
- // restart, self-verify.
1204
- // - Fabric: the operator must set mcp.enabled: true in their deployed
1205
- // component config.yaml. Report the requirement LOUDLY — never report
1206
- // success with /mcp still dark.
1719
+ // - Standalone-local: set mcp.enabled to the env reference in the local
1720
+ // config.yaml (updateLocalConfigMcpEnabled), restart, self-verify.
1721
+ // - Fabric: `enable` does not restart the instance; the operator applies
1722
+ // the environment and restarts. Report the requirement LOUDLY — never
1723
+ // report success with /mcp still dark.
1207
1724
  const isFabric = isFabricOrigin(params.instance);
1208
1725
  if (isFabric) {
1209
1726
  // ── Fabric: operator-deploy requirement ──────────────────────────────
1210
1727
  currentStep = "fabric-operator-deploy";
1211
- const msg = [
1212
- `Fabric deployment detected (${new URL(params.instance).hostname}).`,
1213
- `The @harperfast/oauth block ships in config.yaml with mcp.enabled: \${FLAIR_MCP_OAUTH} (env-referenced, flair#1152) — no config edit is needed.`,
1214
- `To activate: apply the staged secrets (FLAIR_MCP_OAUTH=true among them) to the instance's environment (Fabric env), then restart the instance.`,
1215
- `Deploys can no longer revert the choice — it lives in the environment, not the packed file.`,
1216
- `Then re-run \`flair mcp enable\` — earlier steps are idempotent and will be reused.`,
1217
- ].join(" ");
1728
+ const host = new URL(params.instance).hostname;
1729
+ // flair#2116: this step used to fail unconditionally, so a re-run after
1730
+ // the operator's restart ended here with the same instructions, forever.
1731
+ currentStep = "issuer-target-binding";
1732
+ const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
1733
+ if (!binding.ok) {
1734
+ 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, signingKeyFilePath: keyResult.path, callbackUrl };
1736
+ }
1737
+ currentStep = "fabric-operator-deploy";
1738
+ // The target's metadata names the issuer. Now check the public origin.
1739
+ const live = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
1740
+ if (live.ok) {
1741
+ push(true, `Fabric deployment (${host}): ${binding.detail}; the /mcp OAuth surface already passes self-verify on ${issuer}. ` +
1742
+ `If this run changed a secret value (a new IdP client secret, for example), restart the instance so its process picks the new value up.`);
1743
+ currentStep = "self-verify";
1744
+ push(true, live.detail);
1745
+ const resource = `${issuer}/mcp`;
1746
+ return {
1747
+ ok: true,
1748
+ dryRun: false,
1749
+ steps,
1750
+ issuer,
1751
+ resource,
1752
+ pasteBlock: buildClaudePasteBlock(resource),
1753
+ secretsMechanism: secretsResult.mechanism,
1754
+ secretsPath: secretsResult.path,
1755
+ signingKeyFilePath: keyResult.path,
1756
+ callbackUrl,
1757
+ };
1758
+ }
1759
+ // A request that failed read nothing: it shows neither that the
1760
+ // environment is wrong nor that a restart is needed, so it gets checks
1761
+ // to run instead of the activation instructions (flair#2116).
1762
+ const msg = live.unreachable
1763
+ ? [
1764
+ `Fabric deployment detected (${host}); the public issuer could not be reached (${live.detail}).`,
1765
+ `A failed request does not show that the environment is wrong or that a restart is needed.`,
1766
+ `Check first that the host in that URL resolves in DNS, that this machine can reach it over HTTPS, and that the instance is running in Fabric.`,
1767
+ `Then re-run \`flair mcp enable\` with the same options plus --confirm-secrets-applied: this step checks ${issuer} again, passes once self-verify does, and says what to apply if the surface answers but is not active.`,
1768
+ ].join(" ")
1769
+ : [
1770
+ `Fabric deployment detected (${host}); self-verify on ${issuer} has not passed yet (${live.detail}).`,
1771
+ `The @harperfast/oauth block ships in config.yaml with mcp.enabled: \${FLAIR_MCP_OAUTH} (env-referenced, flair#1152) — no config edit is needed.`,
1772
+ secretsPushed
1773
+ ? `To activate: the secrets were pushed to the instance above (FLAIR_MCP_OAUTH=true among them); restart the instance.`
1774
+ : `To activate: apply the staged secrets (FLAIR_MCP_OAUTH=true among them) to the instance's environment (Fabric env), then restart the instance.`,
1775
+ `Deploys can no longer revert the choice — it lives in the environment, not the packed file.`,
1776
+ `Then re-run \`flair mcp enable\` with the same options plus --confirm-secrets-applied: this step checks ${issuer} again and passes once self-verify does.`,
1777
+ ].join(" ");
1218
1778
  push(false, msg);
1219
1779
  return {
1220
1780
  ok: false,
@@ -1233,6 +1793,32 @@ export async function enableMcp(params, deps = {}) {
1233
1793
  currentStep = "local-config-update";
1234
1794
  const localConfigResult = updateLocalConfigMcpEnabled(true, params.localConfigPath);
1235
1795
  push(localConfigResult.ok, localConfigResult.detail);
1796
+ // flair#2113: ensure --cimd-allowed-hosts (written unless the file already
1797
+ // holds that exact list) and read it back. A failure here stops the flow
1798
+ // before the restart.
1799
+ let writtenCimd;
1800
+ if (cimdAllowedHosts) {
1801
+ const written = updateLocalConfigCimdAllowedHosts(cimdAllowedHosts, params.localConfigPath);
1802
+ if (!written.ok || !written.readBack || !written.path) {
1803
+ push(false, `--cimd-allowed-hosts change could not be confirmed: ${written.detail}. The config.yaml may have changed, ` +
1804
+ `and this command did not restart the instance. ` +
1805
+ `Fix that, or set ${CIMD_ALLOWED_HOSTS_CONFIG_KEY} by hand, then re-run \`flair mcp enable\`.`);
1806
+ return {
1807
+ ok: false,
1808
+ dryRun,
1809
+ steps,
1810
+ failedStep: "local-config-update",
1811
+ issuer,
1812
+ resource: `${issuer}/mcp`,
1813
+ secretsMechanism: secretsResult.mechanism,
1814
+ secretsPath: secretsResult.path,
1815
+ signingKeyFilePath: keyResult.path,
1816
+ callbackUrl,
1817
+ };
1818
+ }
1819
+ writtenCimd = { hosts: written.readBack, path: written.path };
1820
+ push(true, written.detail);
1821
+ }
1236
1822
  // ── Restart ───────────────────────────────────────────────────────────
1237
1823
  currentStep = "restart";
1238
1824
  const preDiscriminator = await captureBootDiscriminator(params.instance, params.adminUser, params.adminPass, { fetchImpl: deps.fetchImpl });
@@ -1246,8 +1832,13 @@ export async function enableMcp(params, deps = {}) {
1246
1832
  pollMs: deps.waitForOpsApiPollMs,
1247
1833
  });
1248
1834
  push(true, `process restarted: pid changed ${preDiscriminator.pid} -> ${postDiscriminator.pid}`);
1249
- // ── Self-verify from the operator's machine, public origin, CIMD-inclusive
1835
+ // ── Match the target's issuer, then self-verify the public origin ────────
1250
1836
  currentStep = "self-verify";
1837
+ const binding = await verifyTargetIssuer(params.instance, issuer, { fetchImpl: deps.fetchImpl });
1838
+ if (!binding.ok) {
1839
+ 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, signingKeyFilePath: keyResult.path, callbackUrl, cimdAllowedHosts: writtenCimd?.hosts, cimdAllowedHostsConfigPath: writtenCimd?.path };
1841
+ }
1251
1842
  const verify = await selfVerifyMcpMetadata(issuer, { fetchImpl: deps.fetchImpl });
1252
1843
  if (!verify.ok) {
1253
1844
  push(false, `${verify.detail} — re-run \`flair mcp status\` to check current state, or \`flair mcp enable\` to retry.`);
@@ -1258,9 +1849,11 @@ export async function enableMcp(params, deps = {}) {
1258
1849
  failedStep: "self-verify",
1259
1850
  issuer,
1260
1851
  resource: `${issuer}/mcp`,
1852
+ cimdAllowedHosts: writtenCimd?.hosts,
1853
+ cimdAllowedHostsConfigPath: writtenCimd?.path,
1261
1854
  };
1262
1855
  }
1263
- push(true, verify.detail);
1856
+ push(true, `${binding.detail}; ${verify.detail}`);
1264
1857
  const resource = `${issuer}/mcp`;
1265
1858
  return {
1266
1859
  ok: true,
@@ -1273,6 +1866,8 @@ export async function enableMcp(params, deps = {}) {
1273
1866
  secretsPath: secretsResult.path,
1274
1867
  signingKeyFilePath: keyResult.path,
1275
1868
  callbackUrl,
1869
+ cimdAllowedHosts: writtenCimd?.hosts,
1870
+ cimdAllowedHostsConfigPath: writtenCimd?.path,
1276
1871
  };
1277
1872
  }
1278
1873
  catch (err) {
@@ -1324,7 +1919,7 @@ export async function disableMcp(params, deps = {}) {
1324
1919
  catch (err) {
1325
1920
  return { ok: false, detail: `restart failed: ${err?.message ?? err}` };
1326
1921
  }
1327
- return { ok: true, detail: `restarted ${params.instance} — /mcp route no longer mounts (byte-identical boot)` };
1922
+ return { ok: true, detail: `restart requested for ${params.instance}` };
1328
1923
  }
1329
1924
  /**
1330
1925
  * Surfaces LIVE state (not a stale local marker): hits the same well-known