@tpsdev-ai/flair 0.63.0 → 0.63.1

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 (63) hide show
  1. package/README.md +8 -7
  2. package/SECURITY.md +55 -33
  3. package/dist/bridges/runtime/import-runner.js +4 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +243 -83
  6. package/dist/commands/agent.js +298 -72
  7. package/dist/commands/attention.js +2 -0
  8. package/dist/commands/bootstrap.js +2 -0
  9. package/dist/commands/bridge.js +10 -0
  10. package/dist/commands/doctor.js +87 -42
  11. package/dist/commands/export.js +141 -11
  12. package/dist/commands/import.js +36 -15
  13. package/dist/commands/init.js +373 -157
  14. package/dist/commands/keys.js +12 -8
  15. package/dist/commands/mcp.js +146 -62
  16. package/dist/commands/memory.js +5 -2
  17. package/dist/commands/migrate-harness-memory.js +9 -3
  18. package/dist/commands/principal.js +19 -14
  19. package/dist/commands/quality.js +23 -3
  20. package/dist/commands/reembed.js +468 -111
  21. package/dist/commands/search.js +2 -0
  22. package/dist/commands/service.js +25 -0
  23. package/dist/commands/status.js +130 -107
  24. package/dist/doctor-client.js +2 -23
  25. package/dist/federation/scheduler.js +148 -12
  26. package/dist/keystore.js +77 -10
  27. package/dist/lib/agent-key-file.js +509 -0
  28. package/dist/lib/agent-rotation-lock.js +249 -0
  29. package/dist/lib/atomic-write.js +2 -2
  30. package/dist/lib/auth-resolve.js +14 -14
  31. package/dist/lib/key-dir.js +203 -0
  32. package/dist/lib/launchd-management.js +7 -3
  33. package/dist/lib/local-instance-pair.js +8 -1
  34. package/dist/lib/node-alias-path.js +50 -2
  35. package/dist/lib/remote-admin-pass.js +157 -0
  36. package/dist/lib/scheduler-platform.js +13 -0
  37. package/dist/lib/service-repoint.js +13 -4
  38. package/dist/lib/skill-seed.js +35 -3
  39. package/dist/lib/terminal-text.js +32 -0
  40. package/dist/mcp-client-assertion.js +5 -4
  41. package/dist/resources/Memory.js +47 -3
  42. package/dist/resources/health.js +39 -22
  43. package/dist/resources/in-process-api.js +74 -11
  44. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  45. package/dist/resources/mcp-handler.js +40 -1
  46. package/dist/resources/mcp-oauth.js +17 -1
  47. package/dist/resources/mcp-tool-scopes.js +69 -0
  48. package/dist/resources/mcp-tools.js +10 -0
  49. package/dist/resources/skill-version-write.js +16 -0
  50. package/dist/src/keystore.js +77 -10
  51. package/dist/src/lib/atomic-write.js +2 -2
  52. package/dist/src/lib/key-dir.js +203 -0
  53. package/dist/src/lib/scheduler-platform.js +13 -0
  54. package/docs/access-control.md +21 -12
  55. package/docs/api-reference.md +35 -24
  56. package/docs/auth.md +31 -22
  57. package/docs/deploying-on-fabric.md +10 -2
  58. package/docs/embedding-in-a-harper-app.md +7 -7
  59. package/docs/entity-vocabulary.md +4 -5
  60. package/docs/hosted-on-fabric.md +1 -1
  61. package/docs/secrets-and-keys.md +8 -13
  62. package/docs/upgrade.md +15 -5
  63. package/package.json +1 -1
@@ -5,10 +5,11 @@ import { claudeCodeMcpEntry, detectClients, renderWiringSummary, wireAntigravity
5
5
  import { DEFAULT_ADMIN_USER, ApiRequestOutcomeUnknown, addAdminPassOptions, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
6
6
  import { INIT_RESET_ADMIN_PASS_COMMAND, detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
7
7
  import { canonicalLexicalPath } from "../lib/daemon-liveness.js";
8
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
8
9
  import { encodeRecordId } from "../lib/record-id-path.js";
9
10
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
10
11
  import { planRedirectMigration, renderRedirectMigration } from "../lib/mcp-oauth-env.js";
11
- import { seedUsingFlairSkill } from "../lib/skill-seed.js";
12
+ import { checkUsingFlairSkill, seedUsingFlairSkill } from "../lib/skill-seed.js";
12
13
  import { clearSkillSeedPending, markSkillSeedPending } from "../lib/skill-seed-pending.js";
13
14
  import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
14
15
  import * as render from "../render.js";
@@ -16,7 +17,9 @@ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
16
17
  import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
17
18
  import { spawn } from "node:child_process";
18
19
  import { randomBytes, randomUUID } from "node:crypto";
19
- import { chmodSync, closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";
21
+ import { ensureAgentKeysDir, readOrCreateAgentKey } from "../lib/agent-key-file.js";
22
+ import { stageRemoteAdminPassword } from "../lib/remote-admin-pass.js";
20
23
  import { join, resolve } from "node:path";
21
24
  import { localPortState } from "../lib/init-tcp-probe.js";
22
25
  import { trackInitChild } from "../lib/init-spawn-attribution.js";
@@ -25,6 +28,11 @@ import { httpCorsAccessList } from "../lib/http-bind.js";
25
28
  import { resolveHome } from "../lib/home.js";
26
29
  import { foreignOccupiedListenerDetail, } from "../lib/init-occupied-listener.js";
27
30
  let cli;
31
+ function remoteAdminPasswordRecovery(clusterAdminUser) {
32
+ return clusterAdminUser === DEFAULT_ADMIN_USER
33
+ ? ` The cluster password for '${clusterAdminUser}' may already have changed. Remedy: recover with a separate administrator credential or Harper's out-of-band administrator recovery before re-running remote init.`
34
+ : " Remedy: re-run the same remote init command.";
35
+ }
28
36
  function ownedInitPidfilePid(dataDir) {
29
37
  let fd;
30
38
  try {
@@ -104,8 +112,8 @@ function persistDefaultInstallCoordinates(...args) {
104
112
  function privKeyPath(...args) {
105
113
  return cli.privKeyPath(...args);
106
114
  }
107
- function provisionFabric(...args) {
108
- return cli.provisionFabric(...args);
115
+ function provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass, hooks) {
116
+ return cli.provisionFabric(target, opsTarget, clusterAdminUser, clusterAdminPass, flairAdminPass, hooks);
109
117
  }
110
118
  function pubKeyPath(...args) {
111
119
  return cli.pubKeyPath(...args);
@@ -174,6 +182,51 @@ async function seedUsingFlairSkillViaRest(baseUrl, adminUser, adminPass) {
174
182
  }
175
183
  console.log(`using-flair skill: ${outcome.message}`);
176
184
  }
185
+ /**
186
+ * flair#3126 — run the seed's reads and refusals with no write. A refusal
187
+ * detected by the preflight prevents the role, shared-user and Agent writes in
188
+ * `finishRemoteInit`. Fabric deployment and administrator provisioning may
189
+ * already have occurred; a later seed refusal can follow those writes.
190
+ */
191
+ async function preflightUsingFlairSkillViaRest(baseUrl, adminUser, adminPass) {
192
+ const outcome = await checkUsingFlairSkill({ baseUrl, user: adminUser, pass: adminPass });
193
+ if (outcome.kind === "refused") {
194
+ console.error(`Error: the using-flair skill seed was refused — ${outcome.message}`);
195
+ process.exit(1);
196
+ }
197
+ }
198
+ /**
199
+ * Refuse the reserved shared agent account as an administrator input on either
200
+ * remote-init leg, before any filesystem or cluster write. `role` and `flag`
201
+ * name the leg's input, so the remedy points at the operator's own flag.
202
+ */
203
+ function refuseReservedPrincipal(name, role, flag) {
204
+ if (name.trim().toLowerCase() !== cli.FLAIR_AGENT_USERNAME)
205
+ return;
206
+ console.error(`Error: '${cli.FLAIR_AGENT_USERNAME}' is a reserved Flair account and cannot be the ${role}.`);
207
+ console.error(` Use a different ${role} (${flag}).`);
208
+ process.exit(1);
209
+ }
210
+ /**
211
+ * Refuse an `--agent-id` that violates the shared agent-ID rule, or that names
212
+ * an administrator username reserved by this init path, before the keys
213
+ * directory or any key file is created or written, and before any `fetch` call made by the command action.
214
+ */
215
+ function refuseOperatorAgentId(agentId, administratorNames) {
216
+ // Only an OMITTED id means "no agent ID supplied". A supplied id,
217
+ // including the empty string, goes through the shared rule below.
218
+ if (agentId === undefined)
219
+ return;
220
+ if (!isValidAgentId(agentId)) {
221
+ console.error(`Error: ${invalidAgentIdMessage(agentId)}`);
222
+ process.exit(1);
223
+ }
224
+ if (!administratorNames.includes(agentId))
225
+ return;
226
+ console.error(`Error: --agent-id "${agentId}" is an administrator username reserved by this init path.`);
227
+ console.error(" Choose another --agent-id.");
228
+ process.exit(1);
229
+ }
177
230
  function readOccupiedListener(port) {
178
231
  return cli.readOccupiedListener(port);
179
232
  }
@@ -213,6 +266,167 @@ function initLaunchdExitCode(kind) {
213
266
  function repointMainServiceUnit(...args) {
214
267
  return cli.repointMainServiceUnit(...args);
215
268
  }
269
+ /**
270
+ * The `flair init` summary's password line, which must name the password the
271
+ * principal actually has: the chosen Flair admin password that init wrote to
272
+ * `adminPassPath` when provisioning created or updated `admin`, otherwise the
273
+ * cluster administrator password this run supplied. `principal.created` decides,
274
+ * never the username: a reused super_user may itself be named `admin`.
275
+ */
276
+ export function adminPasswordHintLine(principal, adminPassPath) {
277
+ if (principal.created) {
278
+ return ` Admin password: the chosen Flair admin password, written to ${adminPassPath}`;
279
+ }
280
+ return " Admin password: the cluster administrator password this run supplied";
281
+ }
282
+ /**
283
+ * The calls a `flair init` run makes after provisioning. On the provisioning
284
+ * leg they are the flair_agent role and shared agent user (plus the
285
+ * flair_pair_initiator role and the federation-instance reconcile with
286
+ * `--remote`), the agent seed with `--agent-id`, the org-wide skill seed and
287
+ * the verification read; every one authenticates as the `principal`
288
+ * provisioning returned. On the already-running-instance leg only the
289
+ * `/Health` connectivity check sends no Authorization header; the other calls
290
+ * authenticate as that principal too.
291
+ */
292
+ export async function finishRemoteInit(principal, opts) {
293
+ const { baseUrl, opsUrl, remote, provisioningLeg, agentId } = opts;
294
+ const adminUser = principal.username;
295
+ const adminPass = principal.password;
296
+ const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
297
+ const role = remote ? "hub" : undefined;
298
+ // flair#3126 — run the seed's checks before this function's role, user and
299
+ // Agent writes.
300
+ await preflightUsingFlairSkillViaRest(baseUrl, adminUser, adminPass);
301
+ if (provisioningLeg) {
302
+ // Hub instances (--remote) receive federation pair requests and need
303
+ // the flair_pair_initiator role so bootstrap credentials can pass
304
+ // platform auth before reaching the FederationPair resource handler.
305
+ if (remote) {
306
+ await ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass);
307
+ }
308
+ // Every flair instance has agents, so provision the least-privilege
309
+ // flair_agent role (idempotent, harmless until a user is assigned to it).
310
+ await ensureFlairAgentRole(opsUrl, adminUser, adminPass);
311
+ // THE FLIP (auth-rbac): provision the shared least-privilege flair-agent user.
312
+ // This ACTIVATES the gate's per-agent de-elevation (verified non-admin agents
313
+ // resolve to flair-agent instead of admin super_user). Safe now: #487 gave
314
+ // every agent-facing resource its own allow* + resolveAgentAuth, so they no
315
+ // longer rely on the admin super_user bypass. The gate also falls back to
316
+ // admin if this user is ever absent, so de-elevation degrades gracefully.
317
+ await ensureFlairAgentUser(opsUrl, adminUser, adminPass);
318
+ }
319
+ // Generate or reuse keypair (only if --agent-id provided, or --remote needs
320
+ // a public key for the FederationInstance row)
321
+ let pubKeyB64url;
322
+ let privPath;
323
+ let instanceId;
324
+ // Reconcile the federation Instance identity row if --remote (hub role).
325
+ // flair#1883: this used to INSERT a row with a fresh random id on every
326
+ // run, so a hub that had already answered a `GET /FederationInstance`
327
+ // (which find-or-creates a `spoke` row) ended up with TWO rows and no
328
+ // canonical identity. Reconciling keeps the row peers already know.
329
+ // It runs before the agent seed so the agent's home is the hub's id.
330
+ const reconcileHubInstance = async (publicKey) => {
331
+ instanceId = randomUUID();
332
+ console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
333
+ let reconciled;
334
+ try {
335
+ reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey }, adminUser, adminPass);
336
+ }
337
+ catch (err) {
338
+ // A refusal (two rows) or an unreachable ops API — both are this
339
+ // command failing, and both already name what to do.
340
+ console.error(`Error: ${err?.message ?? err}`);
341
+ process.exit(1);
342
+ }
343
+ instanceId = reconciled.id;
344
+ if (reconciled.action === "created") {
345
+ console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
346
+ }
347
+ else if (reconciled.action === "updated") {
348
+ console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
349
+ }
350
+ else {
351
+ console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
352
+ }
353
+ };
354
+ if (agentId || role) {
355
+ const keysDir = opts.keysDir ?? defaultKeysDir();
356
+ if (agentId) {
357
+ const agentPrivPath = privKeyPath(agentId, keysDir);
358
+ privPath = agentPrivPath;
359
+ const pubPath = pubKeyPath(agentId, keysDir);
360
+ try {
361
+ ensureAgentKeysDir(keysDir);
362
+ const keyFile = readOrCreateAgentKey(agentPrivPath, () => {
363
+ console.log("Generating Ed25519 keypair...");
364
+ const kp = nacl.sign.keyPair();
365
+ return Buffer.from(kp.secretKey.slice(0, 32));
366
+ });
367
+ const kp = nacl.sign.keyPair.fromSeed(new Uint8Array(keyFile.bytes));
368
+ pubKeyB64url = b64url(kp.publicKey);
369
+ if (keyFile.created) {
370
+ writeFileSync(pubPath, Buffer.from(kp.publicKey));
371
+ console.log(`Keypair written: ${privPath} ✓`);
372
+ }
373
+ else {
374
+ console.log(`Reusing existing key: ${privPath}`);
375
+ }
376
+ }
377
+ catch (err) {
378
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
379
+ process.exit(1);
380
+ }
381
+ if (role)
382
+ await reconcileHubInstance(pubKeyB64url);
383
+ // Seed agent via remote ops API
384
+ console.log(`Seeding agent '${agentId}' on ${baseUrl}...`);
385
+ await seedAgentWithLocalHome(opsUrl, agentId, pubKeyB64url, adminUser, adminPass);
386
+ console.log(`Agent '${agentId}' registered on remote instance ✓`);
387
+ }
388
+ else {
389
+ // No agentId -- generate throwaway keypair for FederationInstance row
390
+ console.log("Generating federation instance keypair...");
391
+ const kp = nacl.sign.keyPair();
392
+ pubKeyB64url = b64url(kp.publicKey);
393
+ if (role)
394
+ await reconcileHubInstance(pubKeyB64url);
395
+ }
396
+ }
397
+ else {
398
+ console.log("No --agent-id provided -- skipping agent registration");
399
+ }
400
+ // flair#2141 S2 — seed the org-wide using-flair skill on the remote
401
+ // instance, as the operator. Idempotent; a refusal fails this run.
402
+ await seedUsingFlairSkillViaRest(baseUrl, adminUser, adminPass);
403
+ // Verify connectivity
404
+ if (provisioningLeg) {
405
+ // Use /FederationInstance with Basic auth (not /Health which false-401s on Fabric)
406
+ console.log("Verifying remote connectivity...");
407
+ const verifyRes = await fetch(`${baseUrl}/FederationInstance`, {
408
+ headers: { Authorization: auth },
409
+ signal: AbortSignal.timeout(5000),
410
+ });
411
+ if (!verifyRes.ok) {
412
+ const body = await verifyRes.text().catch(() => "");
413
+ console.error(`Remote verification failed (${verifyRes.status}): ${body}`);
414
+ process.exit(1);
415
+ }
416
+ console.log("✓ Hub ready at " + baseUrl);
417
+ }
418
+ else {
419
+ // Existing behavior: /Health check (already-running Flair)
420
+ console.log("Verifying remote connectivity...");
421
+ const verifyRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(5000) });
422
+ if (!verifyRes.ok) {
423
+ console.error(`Remote health check failed: ${verifyRes.status}`);
424
+ process.exit(1);
425
+ }
426
+ console.log("Remote Flair instance healthy ✓");
427
+ }
428
+ return { instanceId, privPath };
429
+ }
216
430
  export function register(program) {
217
431
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
218
432
  const STARTUP_TIMEOUT_MS = cli.STARTUP_TIMEOUT_MS;
@@ -232,7 +446,7 @@ export function register(program) {
232
446
  .option("--ops-bind <addr>", "Harper ops API bind address (env: FLAIR_OPS_BIND; default: 127.0.0.1 loopback-only for single-host — pass e.g. 0.0.0.0 for multi-host/Fabric remote admin)")
233
447
  .option("--http-bind <addr>", "Harper HTTP bind address (env: FLAIR_HTTP_BIND; default: 127.0.0.1 loopback-only). The listener MUST include IPv4 loopback (Flair's self-calls hardcode 127.0.0.1), so only 127.0.0.1 or a wildcard (0.0.0.0 / ::) is accepted; a specific non-loopback host is refused."), "Admin password (generated if omitted)", { adminPassFileHelp: "Read admin password from file (chmod 600 recommended)" })
234
448
  .option("--reset-admin-pass", "Rotate Harper's persisted admin hash via the operations socket, then write ~/.flair/admin-pass")
235
- .option("--admin-user <name>", "Admin username when authenticating to an already-running instance via --target/--ops-target (env: FLAIR_ADMIN_USER; default: admin — local bootstrap and Fabric provisioning always create 'admin')")
449
+ .option("--admin-user <name>", "Admin username when authenticating to an already-running instance via --target/--ops-target (env: FLAIR_ADMIN_USER; default: admin — local bootstrap creates 'admin'; Fabric provisioning reuses an existing super_user cluster administrator, and otherwise creates or updates 'admin')")
236
450
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
237
451
  .option("--data-dir <dir>", "Harper data directory")
238
452
  .option("--skip-start", "Do not start Harper; with --agent, defer registration (ignored with --target/--ops-target)")
@@ -269,8 +483,21 @@ export function register(program) {
269
483
  const clusterAdminPass = opts.clusterAdminPass || process.env.FLAIR_CLUSTER_ADMIN_PASS;
270
484
  let flairAdminPass = opts.flairAdminPass || process.env.FLAIR_ADMIN_PASS;
271
485
  let didProvision = false;
486
+ let provisionedPrincipal;
272
487
  if (clusterAdminUser && clusterAdminPass) {
273
488
  // ── New provisioning path: deploy Flair to Fabric, wait, provision super_user ──
489
+ // The reserved shared agent account must never be used as this run's
490
+ // administrator input on either leg: init authenticates its later calls
491
+ // as the run's principal, and without this guard provisioning could
492
+ // change that account through add_user or alter_user on
493
+ // FLAIR_AGENT_USERNAME (ensureFlairAgentUser), out from under the agent
494
+ // gate. Refuse it first, before the agent-ID check and every filesystem
495
+ // or cluster write.
496
+ refuseReservedPrincipal(clusterAdminUser, "cluster administrator", "--cluster-admin-user");
497
+ // Provisioning either reuses an existing super_user cluster admin or
498
+ // creates or updates DEFAULT_ADMIN_USER, so both names are known before
499
+ // provisionFabric runs. Refuse either one here, before any write.
500
+ refuseOperatorAgentId(agentId, [clusterAdminUser, DEFAULT_ADMIN_USER]);
274
501
  if (!opts.force) {
275
502
  console.error("Error: --force is required with --target/--ops-target (remote init provisions a live Fabric instance)");
276
503
  console.error(" Pass --force to confirm this is intended.");
@@ -280,34 +507,102 @@ export function register(program) {
280
507
  if (!flairAdminPass) {
281
508
  flairAdminPass = randomBytes(24).toString("base64url");
282
509
  }
283
- // Write the flair admin pass to secrets directory
284
- const secretsDir = join(resolveHome(), ".tps", "secrets");
285
- mkdirSync(secretsDir, { recursive: true });
286
- const secretPath = join(secretsDir, "flair-fabric-hdb");
287
- writeFileSync(secretPath, flairAdminPass + "\n", { mode: 0o600 });
288
- console.log(`Admin password written to ${secretPath}`);
289
- // Atomic provisioning: deploy + wait + provision user
290
- await provisionFabric(baseUrl, opsUrl, clusterAdminUser, clusterAdminPass, flairAdminPass);
510
+ // Provisioning: save unless reusing a super_user, deploy + wait, provision user.
511
+ // The returned principal is the one this run set up: the existing
512
+ // super_user cluster administrator when list_users reports the
513
+ // operator's cluster admin as a super_user, else the `admin` user this
514
+ // run created (or updated).
515
+ const secretPath = join(resolveHome(), ".tps", "secrets", "flair-fabric-hdb");
516
+ let stagedAdminPass;
517
+ let saveAttempted = false;
518
+ let saveApplied = false;
519
+ let requestSent = false;
520
+ try {
521
+ provisionedPrincipal = await provisionFabric(baseUrl, opsUrl, clusterAdminUser, clusterAdminPass, flairAdminPass, {
522
+ // Before the first cluster write, when this run attempts to set
523
+ // `admin`'s password. A throw here leaves the cluster unchanged.
524
+ beforeAdminPasswordApplied: () => {
525
+ saveAttempted = true;
526
+ stagedAdminPass = stageRemoteAdminPassword(secretPath, flairAdminPass, writeAdminPassFile);
527
+ },
528
+ adminPasswordRequestSent: () => {
529
+ requestSent = true;
530
+ },
531
+ afterAdminPasswordApplied: () => {
532
+ saveApplied = true;
533
+ stagedAdminPass.confirm();
534
+ },
535
+ });
536
+ }
537
+ catch (err) {
538
+ const message = err instanceof Error ? err.message : String(err);
539
+ if (saveAttempted && !stagedAdminPass) {
540
+ console.error(`Error: could not save the Flair administrator password to ${secretPath}: ${message}`);
541
+ console.error(` Remedy: make ${secretPath} a writable regular file you own (mode 0600), then run init again.`);
542
+ console.error(" The cluster was not changed.");
543
+ process.exit(1);
544
+ }
545
+ if (saveApplied) {
546
+ const held = stagedAdminPass.stagedPath;
547
+ // Recheck the stage before advising a move: it may have changed since confirm().
548
+ if (held !== null && stagedAdminPass.stagedFileVerified && stagedAdminPass.stillValid()) {
549
+ console.error(`Error: the cluster accepted the Flair administrator password, but ${held} could not be moved into place: ${message}`);
550
+ console.error(` The cluster now holds the password in ${held}.`);
551
+ console.error(` Remedy: move ${held} over ${secretPath} with mode 0600.`);
552
+ }
553
+ else {
554
+ console.error(`Error: the cluster accepted the Flair administrator password, but the saved credential at ${held ?? secretPath} could not be confirmed: ${message}`);
555
+ console.error(remoteAdminPasswordRecovery(clusterAdminUser));
556
+ }
557
+ process.exit(1);
558
+ }
559
+ if (stagedAdminPass && requestSent) {
560
+ const held = stagedAdminPass.stagedPath;
561
+ console.error(`Error: Fabric provisioning failed after attempting the add/alter request, so the outcome is uncertain: ${message}`);
562
+ if (held !== null) {
563
+ console.error(` The cluster may hold the password in ${held}.`);
564
+ console.error(` If that password logs in, move ${held} over ${secretPath} with mode 0600; if it does not, delete ${held}.`);
565
+ }
566
+ else {
567
+ console.error(` The cluster may hold the password saved at ${secretPath}.`);
568
+ }
569
+ process.exit(1);
570
+ }
571
+ if (stagedAdminPass) {
572
+ const stage = stagedAdminPass;
573
+ try {
574
+ stage.abort();
575
+ }
576
+ catch (cleanupErr) {
577
+ const cleanupMessage = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr);
578
+ console.error(`Error: Fabric provisioning failed after the Flair administrator password was saved: ${message}`);
579
+ console.error(`Error: could not remove the staged credential ${stage.stagedPath}: ${cleanupMessage}`);
580
+ process.exit(1);
581
+ }
582
+ console.error(`Error: Fabric provisioning failed after the Flair administrator password was saved: ${message}`);
583
+ if (stage.hadExistingFile) {
584
+ console.error(` The existing credential file at ${secretPath} was left unchanged.`);
585
+ }
586
+ else {
587
+ console.error(` The saved password is kept at ${secretPath}; reuse it on the next run.`);
588
+ }
589
+ }
590
+ throw err;
591
+ }
291
592
  didProvision = true;
292
- // Hub instances (--remote) receive federation pair requests and need
293
- // the flair_pair_initiator role so bootstrap credentials can pass
294
- // platform auth before reaching the FederationPair resource handler.
295
- if (opts.remote) {
296
- await ensureFlairPairInitiatorRole(opsUrl, DEFAULT_ADMIN_USER, flairAdminPass);
593
+ if (!provisionedPrincipal.created && existsSync(secretPath)) {
594
+ console.warn(`⚠ ${secretPath} already exists, but this run reused an existing super_user cluster administrator and neither changed nor verified that file. Verify it by authenticating to the instance with the password it holds before relying on it.`);
595
+ }
596
+ if (provisionedPrincipal.created) {
597
+ console.log(`Admin password written to ${secretPath}`);
297
598
  }
298
- // Every flair instance has agents, so provision the least-privilege
299
- // flair_agent role (idempotent, harmless until a user is assigned to it).
300
- await ensureFlairAgentRole(opsUrl, DEFAULT_ADMIN_USER, flairAdminPass);
301
- // THE FLIP (auth-rbac): provision the shared least-privilege flair-agent user.
302
- // This ACTIVATES the gate's per-agent de-elevation (verified non-admin agents
303
- // resolve to flair-agent instead of admin super_user). Safe now: #487 gave
304
- // every agent-facing resource its own allow* + resolveAgentAuth, so they no
305
- // longer rely on the admin super_user bypass. The gate also falls back to
306
- // admin if this user is ever absent, so de-elevation degrades gracefully.
307
- await ensureFlairAgentUser(opsUrl, DEFAULT_ADMIN_USER, flairAdminPass);
308
599
  }
309
600
  else {
310
601
  // ── Existing behavior: --admin-pass required for already-running Flair ──
602
+ // On this leg the run's principal is --admin-user (or its default), so
603
+ // the reserved-principal refusal must cover that name too, before any
604
+ // filesystem or cluster write.
605
+ refuseReservedPrincipal(resolveAdminUser(opts.adminUser), "admin user", "--admin-user");
311
606
  if (!opts.adminPass) {
312
607
  console.error("Error: --admin-pass is required with --target/--ops-target (remote init without --cluster-admin-user/--cluster-admin-pass)");
313
608
  console.error(" Use --cluster-admin-user and --cluster-admin-pass for automated Fabric provisioning.");
@@ -320,127 +615,37 @@ export function register(program) {
320
615
  process.exit(1);
321
616
  }
322
617
  flairAdminPass = opts.adminPass;
618
+ // flair#1345: only the already-running-instance leg honors --admin-user /
619
+ // FLAIR_ADMIN_USER; provisioning uses the returned principal.
620
+ provisionedPrincipal = {
621
+ username: resolveAdminUser(opts.adminUser),
622
+ password: opts.adminPass,
623
+ created: false,
624
+ };
323
625
  }
324
- // flair#1345: only the already-running-instance leg honors --admin-user /
325
- // FLAIR_ADMIN_USER — the provisioning leg just CREATED the superuser as
326
- // DEFAULT_ADMIN_USER via provisionFabric, so that name is ground truth.
327
- const adminUser = didProvision ? DEFAULT_ADMIN_USER : resolveAdminUser(opts.adminUser);
328
- const auth = `Basic ${Buffer.from(`${adminUser}:${flairAdminPass}`).toString("base64")}`;
329
- const role = opts.remote ? "hub" : undefined;
330
- // Generate or reuse keypair (only if --agent-id provided, or --remote needs
331
- // a public key for the FederationInstance row)
332
- let pubKeyB64url;
333
- let privPath;
334
- let instanceId;
335
- // Reconcile the federation Instance identity row if --remote (hub role).
336
- // flair#1883: this used to INSERT a row with a fresh random id on every
337
- // run, so a hub that had already answered a `GET /FederationInstance`
338
- // (which find-or-creates a `spoke` row) ended up with TWO rows and no
339
- // canonical identity. Reconciling keeps the row peers already know.
340
- // It runs before the agent seed so the agent's home is the hub's id.
341
- const reconcileHubInstance = async (publicKey) => {
342
- instanceId = randomUUID();
343
- console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
344
- let reconciled;
345
- try {
346
- reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey }, adminUser, flairAdminPass);
347
- }
348
- catch (err) {
349
- // A refusal (two rows) or an unreachable ops API — both are this
350
- // command failing, and both already name what to do.
351
- console.error(`Error: ${err?.message ?? err}`);
352
- process.exit(1);
353
- }
354
- instanceId = reconciled.id;
355
- if (reconciled.action === "created") {
356
- console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
357
- }
358
- else if (reconciled.action === "updated") {
359
- console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
360
- }
361
- else {
362
- console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
363
- }
364
- };
365
- if (agentId || role) {
366
- const keysDir = opts.keysDir ?? defaultKeysDir();
367
- mkdirSync(keysDir, { recursive: true });
368
- if (agentId) {
369
- privPath = privKeyPath(agentId, keysDir);
370
- const pubPath = pubKeyPath(agentId, keysDir);
371
- if (existsSync(privPath)) {
372
- console.log(`Reusing existing key: ${privPath}`);
373
- const seed = new Uint8Array(readFileSync(privPath));
374
- const kp = nacl.sign.keyPair.fromSeed(seed);
375
- pubKeyB64url = b64url(kp.publicKey);
376
- }
377
- else {
378
- console.log("Generating Ed25519 keypair...");
379
- const kp = nacl.sign.keyPair();
380
- const seed = kp.secretKey.slice(0, 32);
381
- writeFileSync(privPath, Buffer.from(seed));
382
- chmodSync(privPath, 0o600);
383
- writeFileSync(pubPath, Buffer.from(kp.publicKey));
384
- pubKeyB64url = b64url(kp.publicKey);
385
- console.log(`Keypair written: ${privPath} ✓`);
386
- }
387
- if (role)
388
- await reconcileHubInstance(pubKeyB64url);
389
- // Seed agent via remote ops API
390
- console.log(`Seeding agent '${agentId}' on ${baseUrl}...`);
391
- await seedAgentWithLocalHome(opsUrl, agentId, pubKeyB64url, adminUser, flairAdminPass);
392
- console.log(`Agent '${agentId}' registered on remote instance ✓`);
393
- }
394
- else {
395
- // No agentId -- generate throwaway keypair for FederationInstance row
396
- console.log("Generating federation instance keypair...");
397
- const kp = nacl.sign.keyPair();
398
- pubKeyB64url = b64url(kp.publicKey);
399
- if (role)
400
- await reconcileHubInstance(pubKeyB64url);
401
- }
402
- }
403
- else {
404
- console.log("No --agent-id provided -- skipping agent registration");
405
- }
406
- // flair#2141 S2 — seed the org-wide using-flair skill on the remote
407
- // instance, as the operator. Idempotent; a refusal fails this run.
408
- await seedUsingFlairSkillViaRest(baseUrl, adminUser, flairAdminPass);
409
- // Verify connectivity
410
- if (didProvision) {
411
- // Use /FederationInstance with Basic auth (not /Health which false-401s on Fabric)
412
- console.log("Verifying remote connectivity...");
413
- const verifyRes = await fetch(`${baseUrl}/FederationInstance`, {
414
- headers: { Authorization: auth },
415
- signal: AbortSignal.timeout(5000),
416
- });
417
- if (!verifyRes.ok) {
418
- const body = await verifyRes.text().catch(() => "");
419
- console.error(`Remote verification failed (${verifyRes.status}): ${body}`);
420
- process.exit(1);
421
- }
422
- console.log("✓ Hub ready at " + baseUrl);
423
- }
424
- else {
425
- // Existing behavior: /Health check (already-running Flair)
426
- console.log("Verifying remote connectivity...");
427
- const verifyRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(5000) });
428
- if (!verifyRes.ok) {
429
- console.error(`Remote health check failed: ${verifyRes.status}`);
430
- process.exit(1);
431
- }
432
- console.log("Remote Flair instance healthy ✓");
433
- }
626
+ const principal = provisionedPrincipal;
627
+ if (!didProvision)
628
+ refuseOperatorAgentId(agentId, [principal.username]);
629
+ const { instanceId, privPath } = await finishRemoteInit(principal, {
630
+ baseUrl,
631
+ opsUrl,
632
+ remote: !!opts.remote,
633
+ provisioningLeg: didProvision,
634
+ agentId,
635
+ keysDir: opts.keysDir,
636
+ });
434
637
  // Print summary
435
638
  if (didProvision) {
436
639
  const pkg = JSON.parse(readFileSync(join(process.cwd(), "package.json"), "utf-8"));
437
640
  const flavor = pkg.version || "(unknown)";
438
641
  const displayTarget = target || opsTarget;
642
+ const adminPassPath = join(resolveHome(), ".tps", "secrets", "flair-fabric-hdb");
439
643
  console.log(`\n✓ Flair hub deployed to ${displayTarget}`);
440
644
  console.log(` Component: flair@${flavor}`);
441
- console.log(` Admin user: ${adminUser} (pass written to ${join(resolveHome(), ".tps", "secrets", "flair-fabric-hdb")})`);
645
+ console.log(` Admin user: ${principal.username}`);
646
+ console.log(adminPasswordHintLine(principal, adminPassPath));
442
647
  if (instanceId)
443
- console.log(` Instance: ${instanceId} (role=${role})`);
648
+ console.log(` Instance: ${instanceId} (role=hub)`);
444
649
  console.log(` Federation: ready — run \`flair federation token\` to mint a pairing token`);
445
650
  }
446
651
  else {
@@ -450,13 +655,16 @@ export function register(program) {
450
655
  console.log(` Target: ${baseUrl}`);
451
656
  if (agentId)
452
657
  console.log(` Private key: ${privPath}`);
453
- if (role)
454
- console.log(` Role: ${role}`);
658
+ if (opts.remote)
659
+ console.log(` Role: hub`);
455
660
  console.log(`\n Export: FLAIR_URL=${baseUrl}`);
456
661
  }
457
662
  return;
458
663
  }
459
664
  // ── Local init (full one-command setup) ──
665
+ // Local init uses DEFAULT_ADMIN_USER, so the
666
+ // check runs here, before any key or Agent write.
667
+ refuseOperatorAgentId(agentId, [DEFAULT_ADMIN_USER]);
460
668
  const keysDir = opts.keysDir ?? defaultKeysDir();
461
669
  // Resolve ONCE, here: the operator means "relative to my shell's cwd", but
462
670
  // Harper is spawned with cwd = the flair package directory, so a raw
@@ -1250,29 +1458,37 @@ export function register(program) {
1250
1458
  };
1251
1459
  if (agentId) {
1252
1460
  // Generate or reuse keypair
1253
- mkdirSync(keysDir, { recursive: true });
1254
1461
  const privPath = privKeyPath(agentId, keysDir);
1255
1462
  const pubPath = pubKeyPath(agentId, keysDir);
1256
1463
  let pubKeyB64url;
1257
- if (existsSync(privPath)) {
1258
- console.log(`Reusing existing key: ${privPath}`);
1259
- const seed = new Uint8Array(readFileSync(privPath));
1260
- const kp = nacl.sign.keyPair.fromSeed(seed);
1464
+ try {
1465
+ ensureAgentKeysDir(keysDir);
1466
+ const keyFile = readOrCreateAgentKey(privPath, () => {
1467
+ console.log("Generating Ed25519 keypair...");
1468
+ const kp = nacl.sign.keyPair();
1469
+ // Store only the 32-byte seed (first 32 bytes of secretKey)
1470
+ return Buffer.from(kp.secretKey.slice(0, 32));
1471
+ });
1472
+ const kp = nacl.sign.keyPair.fromSeed(new Uint8Array(keyFile.bytes));
1261
1473
  pubKeyB64url = b64url(kp.publicKey);
1474
+ if (keyFile.created) {
1475
+ writeFileSync(pubPath, Buffer.from(kp.publicKey));
1476
+ console.log(`Keypair written: ${privPath} ✓`);
1477
+ }
1478
+ else {
1479
+ console.log(`Reusing existing key: ${privPath}`);
1480
+ }
1262
1481
  }
1263
- else {
1264
- console.log("Generating Ed25519 keypair...");
1265
- const kp = nacl.sign.keyPair();
1266
- // Store only the 32-byte seed (first 32 bytes of secretKey)
1267
- const seed = kp.secretKey.slice(0, 32);
1268
- writeFileSync(privPath, Buffer.from(seed));
1269
- chmodSync(privPath, 0o600);
1270
- writeFileSync(pubPath, Buffer.from(kp.publicKey));
1271
- pubKeyB64url = b64url(kp.publicKey);
1272
- console.log(`Keypair written: ${privPath} ✓`);
1482
+ catch (err) {
1483
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
1484
+ process.exit(1);
1273
1485
  }
1274
1486
  const httpUrl = `http://127.0.0.1:${httpPort}`;
1275
1487
  if (!opts.skipStart) {
1488
+ // flair#3126 — check the seed before the agent write, so a refusal
1489
+ // leaves no Agent row behind.
1490
+ await attributeBeforeCredential(httpPort, httpBind.host);
1491
+ await preflightUsingFlairSkillViaRest(httpUrl, adminUser, adminPass);
1276
1492
  console.log(`Seeding agent '${agentId}' via operations API...`);
1277
1493
  const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1278
1494
  await attributeBeforeCredential(opsPort, opsBindHost);