@tpsdev-ai/flair 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -2,7 +2,7 @@ import nacl from "tweetnacl";
2
2
  import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, unlinkSync, realpathSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import * as render from "../render.js";
5
- import { resolveAdminPassFromSources, defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, resolveKeyPath, authFetch, } from "../lib/auth-resolve.js";
5
+ import { addAdminPassOptions, credentialsInHeader, defaultKeysDir, describeHttpFailure, resolveLocalAdminPass, resolveAdminUser, resolveKeyPath, authFetch, authFetchWithSentCredentials, } from "../lib/auth-resolve.js";
6
6
  import { encodeRecordId } from "../lib/record-id-path.js";
7
7
  import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
8
8
  import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
@@ -206,13 +206,13 @@ async function readStoredAgent(opsPortOrUrl, id, adminUser, adminPass) {
206
206
  export function register(program) {
207
207
  // ─── flair agent ─────────────────────────────────────────────────────────────
208
208
  const agent = program.command("agent").description("Manage Flair agents");
209
- agent
209
+ addAdminPassOptions(agent
210
210
  .command("add <id>")
211
211
  .description("Register a new agent. Refuses an id whose Agent record already exists")
212
212
  .option("--name <name>", "Display name (defaults to id)")
213
- .option("--port <port>", "Harper HTTP port")
214
- .option("--admin-pass <pass>", "Admin password for registration")
215
- .option("--admin-pass-file <path>", "Read the admin password from a file (chmod 600 enforced). Preferred over inline --admin-pass — keeps the secret out of ps and shell history; works for remote targets too (an explicit flag is operator intent).")
213
+ .option("--port <port>", "Harper HTTP port"), "Admin password for registration", {
214
+ adminPassFileHelp: "Read the admin password from a file (owner-only permissions enforced). Preferred over inline --admin-pass — keeps the secret out of ps and shell history; works for remote targets too (an explicit flag is operator intent).",
215
+ })
216
216
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
217
217
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
218
218
  .option("--ops-port <port>", "Harper operations API port")
@@ -236,29 +236,13 @@ export function register(program) {
236
236
  // `flair import`: explicit --ops-target > derive from --target > localhost.
237
237
  const seedOpsTarget = resolveEffectiveOpsUrl({ target: opts.target, opsTarget: opts.opsTarget }) ?? opsPort;
238
238
  const isRemoteTarget = typeof seedOpsTarget === "string";
239
- // flair#1259 / #1910 — --admin-pass-file and --admin-pass resolve through
240
- // the ONE resolver (resolveAdminPassFromSources), the file read in-process
241
- // via readAdminPassFileSecure so the secret never appears in ps or shell
242
- // history. Combining the file and the flag is a usage error (the flag used
243
- // to silently win). This does NOT weaken the #1085 remote guard below: an
244
- // explicit flag naming a file IS operator intent toward this target,
245
- // exactly like an explicit inline --admin-pass — what the guard blocks is
246
- // the AMBIENT env/local-file fallbacks silently traveling to a third-party
247
- // host.
248
- let explicitPass;
249
- try {
250
- explicitPass =
251
- resolveAdminPassFromSources({
252
- adminPassFile: opts.adminPassFile,
253
- adminPass: opts.adminPass,
254
- envPass: undefined,
255
- }) || undefined;
256
- }
257
- catch (err) {
258
- console.error(`Error: ${err.message}`);
259
- process.exit(1);
260
- }
261
- opts.adminPass = explicitPass;
239
+ // flair#1259 / #1910 — the pair is resolved by addAdminPassOptions' preAction
240
+ // hook, before this action runs. This does NOT weaken the #1085 remote guard
241
+ // below: an explicit flag naming a file IS operator intent toward this
242
+ // target, exactly like an explicit inline --admin-pass — what the guard
243
+ // blocks is the AMBIENT env/local-file fallbacks silently traveling to a
244
+ // third-party host.
245
+ //
262
246
  // #590 — local convenience fallback: FLAIR_ADMIN_PASS env, then the secure
263
247
  // ~/.flair/admin-pass file `flair init` already writes (mode 0600). Never
264
248
  // applied for a remote target — see resolveLocalAdminPass.
@@ -330,10 +314,7 @@ export function register(program) {
330
314
  console.log(` Note: an OAuth /mcp connector maps its own IdP subject to an Agent (distinct from '${id}' by default).\n` +
331
315
  ` To point a connector at '${id}': flair mcp enable --principal ${id} --idp-subject <your-idp-login>`);
332
316
  });
333
- agent
334
- .command("list")
335
- .description("List all agents")
336
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
317
+ addAdminPassOptions(agent.command("list").description("List all agents"), "Admin password (or set FLAIR_ADMIN_PASS env)")
337
318
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
338
319
  .option("--agent <id>", "Agent ID to authenticate as via Ed25519 (or FLAIR_AGENT_ID env) when no admin pass")
339
320
  .option("--keys-dir <dir>", "Directory holding the agent's Ed25519 key")
@@ -341,9 +322,7 @@ export function register(program) {
341
322
  .option("--json", "Emit raw JSON array (also: pipe + FLAIR_OUTPUT=json)")
342
323
  .action(async (opts) => {
343
324
  const port = resolveHttpPort(opts);
344
- // fromEnv is true ONLY when the resolved value came from env (no inline override).
345
- const adminPassFromEnv = !opts.adminPass && (!!process.env.FLAIR_ADMIN_PASS || !!process.env.HDB_ADMIN_PASSWORD);
346
- if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
325
+ if (shouldShowInlineSecretWarning(opts.inlineAdminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
347
326
  console.error(INLINE_ADMIN_PASS_WARNING);
348
327
  }
349
328
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
@@ -365,7 +344,8 @@ export function register(program) {
365
344
  });
366
345
  if (!res.ok) {
367
346
  const text = await res.text().catch(() => "");
368
- console.error(`${render.icons.error} ${res.status} ${text}`);
347
+ const sent = credentialsInHeader(`Basic ${auth}`);
348
+ console.error(`${render.icons.error} ${describeHttpFailure(res.status, text, sent.values, sent.withhold)}`);
369
349
  process.exit(1);
370
350
  }
371
351
  agents = await res.json();
@@ -380,13 +360,14 @@ export function register(program) {
380
360
  const agentId = opts.agent ?? process.env.FLAIR_AGENT_ID;
381
361
  const keysDir = opts.keysDir ?? process.env.FLAIR_KEY_DIR ?? defaultKeysDir();
382
362
  let res;
363
+ let sent = { values: [], withhold: false };
383
364
  if (agentId) {
384
365
  const keyPath = resolveKeyPath(agentId) ?? join(keysDir, `${agentId}.key`);
385
366
  if (!existsSync(keyPath)) {
386
367
  console.error(`${render.icons.error} no key for agent '${agentId}' (looked in ${keysDir}). Pass --admin-pass, --keys-dir, or a registered --agent.`);
387
368
  process.exit(1);
388
369
  }
389
- res = await authFetch(baseUrl, agentId, keyPath, "GET", "/Agent");
370
+ ({ res, sent } = await authFetchWithSentCredentials(baseUrl, agentId, keyPath, "GET", "/Agent"));
390
371
  }
391
372
  else {
392
373
  // No agent identity available either. Try anonymously, but if it 403s
@@ -402,7 +383,7 @@ export function register(program) {
402
383
  console.error(` or ${render.wrap(render.c.cyan, "--admin-pass")} / FLAIR_ADMIN_PASS for the admin view.`);
403
384
  }
404
385
  else {
405
- console.error(`${render.icons.error} ${res.status} ${text}`);
386
+ console.error(`${render.icons.error} ${describeHttpFailure(res.status, text, sent.values, sent.withhold)}`);
406
387
  }
407
388
  process.exit(1);
408
389
  }
@@ -465,20 +446,17 @@ export function register(program) {
465
446
  console.log(render.kv("updated", `${render.relativeTime(out.updatedAt)} ${render.wrap(render.c.dim, `(${out.updatedAt})`)}`));
466
447
  }
467
448
  });
468
- agent
449
+ addAdminPassOptions(agent
469
450
  .command("rotate-key <id>")
470
451
  .description("Rotate an agent's Ed25519 keypair")
471
452
  .option("--port <port>", "Harper HTTP port")
472
- .option("--ops-port <port>", "Harper operations API port")
473
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
453
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
474
454
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
475
455
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
476
456
  .action(async (id, opts) => {
477
457
  const httpPort = resolveHttpPort(opts);
478
458
  const opsPort = resolveOpsPort(opts);
479
- // fromEnv is true ONLY when the resolved value came from env (no inline override).
480
- const adminPassFromEnv = !opts.adminPass && !!process.env.FLAIR_ADMIN_PASS;
481
- if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
459
+ if (shouldShowInlineSecretWarning(opts.inlineAdminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
482
460
  console.error(INLINE_ADMIN_PASS_WARNING);
483
461
  }
484
462
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
@@ -548,13 +526,12 @@ export function register(program) {
548
526
  console.log(` Old key backup: ${backupPrivPath}`);
549
527
  });
550
528
  // ─── flair agent remove ──────────────────────────────────────────────────────
551
- agent
529
+ addAdminPassOptions(agent
552
530
  .command("remove <id>")
553
531
  .description("Remove an agent and all its data from Flair")
554
532
  .option("--keep-keys", "Do not delete key files from disk")
555
533
  .option("--port <port>", "Harper HTTP port")
556
- .option("--ops-port <port>", "Harper operations API port")
557
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
534
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
558
535
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
559
536
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
560
537
  .option("--force", "Skip interactive confirmation (required when stdin is not a TTY)")
@@ -707,13 +684,11 @@ export function register(program) {
707
684
  }
708
685
  console.log(`\n✅ Agent '${id}' removed successfully`);
709
686
  });
710
- agent
687
+ addAdminPassOptions(agent
711
688
  .command("stamp-home")
712
689
  .description("Back-fill the home instance (originatorInstanceId) on home-less Agent rows with no federation-sync provenance")
713
690
  .option("--port <port>", "Harper HTTP port")
714
- .option("--ops-port <port>", "Harper operations API port")
715
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
716
- .option("--admin-pass-file <path>", "Read the admin password from a file (chmod 600 enforced)")
691
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS)", { adminPassFileHelp: "Read the admin password from a file (owner-only permissions enforced)" })
717
692
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
718
693
  .option("--apply", "Write the home; without it the command is a dry run and writes nothing")
719
694
  .action(async (opts) => {
@@ -731,22 +706,9 @@ export function register(program) {
731
706
  }
732
707
  const opsPort = target.opsPort;
733
708
  const adminUser = resolveAdminUser(opts.adminUser);
734
- let explicitPass;
735
- try {
736
- explicitPass =
737
- resolveAdminPassFromSources({
738
- adminPassFile: opts.adminPassFile,
739
- adminPass: opts.adminPass,
740
- envPass: undefined,
741
- }) || undefined;
742
- }
743
- catch (err) {
744
- console.error(`Error: ${err.message}`);
745
- process.exit(1);
746
- }
747
709
  let adminPass;
748
710
  try {
749
- adminPass = resolveLocalAdminPass(explicitPass);
711
+ adminPass = resolveLocalAdminPass(opts.adminPass);
750
712
  }
751
713
  catch (err) {
752
714
  console.error(`Error: ${err.message}`);
@@ -0,0 +1,218 @@
1
+ import { basename } from "node:path";
2
+ import { resolveAdminUser } from "../lib/auth-resolve.js";
3
+ import { backupDigestPath, readBackupArtifact } from "../lib/backup-artifact.js";
4
+ import { approveArchive, ApprovalStoreError, defaultApprovalStoreRoot, listApprovals, readImportFile, revokeApproval, } from "../lib/backup-approval-store.js";
5
+ import { parseRestoreArchive } from "../lib/restore-archive.js";
6
+ import * as render from "../render.js";
7
+ let cli;
8
+ /** Bind the cli-locals this module depends on. */
9
+ export function bindCli(fns) {
10
+ cli = fns;
11
+ }
12
+ const NOTHING_APPROVED = "nothing was approved";
13
+ const NOTHING_REVOKED = "nothing was revoked";
14
+ /** A refusal: print it and set a non-zero exit code. */
15
+ class Refusal extends Error {
16
+ }
17
+ /** A short, secret-free label for a failed fetch. */
18
+ function fetchFailure(error) {
19
+ const cause = error?.cause?.code;
20
+ const code = error?.code;
21
+ if (typeof cause === "string")
22
+ return cause;
23
+ if (typeof code === "string")
24
+ return code;
25
+ return error instanceof Error ? error.name : "connection failed";
26
+ }
27
+ function errnoCode(error) {
28
+ const code = error?.code;
29
+ return typeof code === "string" ? code : "error";
30
+ }
31
+ /**
32
+ * Verify the operator credentials against this host's operations API and
33
+ * return the operator name to record. Throws a Refusal naming what did not
34
+ * hold; never prints the password.
35
+ */
36
+ async function verifyOperator(opts, action, nothing = NOTHING_APPROVED) {
37
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
38
+ const adminUser = resolveAdminUser(opts.adminUser);
39
+ if (!adminPass) {
40
+ throw new Refusal(`${action} needs operator credentials: pass --admin-pass-file (preferred), --admin-pass, or set FLAIR_ADMIN_PASS; ${nothing}`);
41
+ }
42
+ // The repo's ops-port ladder (src/cli.ts resolveOpsPort): --ops-port, then
43
+ // FLAIR_OPS_PORT, then the local config's opsPort, then the resolved HTTP
44
+ // port minus one. Always loopback: the credentials are checked on this host.
45
+ const opsUrl = `http://127.0.0.1:${cli.resolveOpsPort(opts)}`;
46
+ let res;
47
+ try {
48
+ res = await fetch(`${opsUrl}/`, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/json", Authorization: `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}` },
51
+ body: JSON.stringify({ operation: "user_info" }),
52
+ signal: AbortSignal.timeout(10_000),
53
+ });
54
+ }
55
+ catch (error) {
56
+ throw new Refusal(`could not reach this host's operations API at ${opsUrl} to verify the operator credentials ` +
57
+ `(${fetchFailure(error)}); check that Flair is running on this host and name its operations port with ` +
58
+ `--ops-port (or FLAIR_OPS_PORT); ${nothing}`);
59
+ }
60
+ if (res.status === 401 || res.status === 403) {
61
+ throw new Refusal(`the operator credentials were refused by this host's operations API (HTTP ${res.status}); ${nothing}`);
62
+ }
63
+ if (!res.ok)
64
+ throw new Refusal(`this host's operations API answered HTTP ${res.status} to user_info; ${nothing}`);
65
+ const info = (await res.json().catch(() => null));
66
+ if (info?.role?.permission?.super_user !== true) {
67
+ throw new Refusal(`the credentials for ${adminUser} are not a super_user on this host, so they are not operator credentials; ${nothing}`);
68
+ }
69
+ return typeof info.username === "string" && info.username.length > 0 ? info.username : adminUser;
70
+ }
71
+ /** Read an import file, turning a refusal or read error into a Refusal. */
72
+ function importFile(path, describe) {
73
+ try {
74
+ return readImportFile(path, describe);
75
+ }
76
+ catch (error) {
77
+ if (error instanceof ApprovalStoreError)
78
+ throw new Refusal(`${error.message}; ${NOTHING_APPROVED}`);
79
+ throw new Refusal(`cannot read ${describe} ${path} (${errnoCode(error)}); ${NOTHING_APPROVED}`);
80
+ }
81
+ }
82
+ function printRecord(heading, record) {
83
+ console.log(`${render.icons.ok} ${render.wrap(render.c.green, heading)}`);
84
+ console.log(render.kv("SHA-256", record.sha256));
85
+ console.log(render.kv("Admission", record.admission));
86
+ console.log(render.kv("Approved", `${record.approvedAt} by ${record.approvedBy}`));
87
+ if (record.revokedAt !== null)
88
+ console.log(render.kv("Revoked", `${record.revokedAt} by ${record.revokedBy}`));
89
+ console.log(render.kv("Store", defaultApprovalStoreRoot()));
90
+ }
91
+ /** Run an action; a Refusal or store error prints one error line and exits non-zero. */
92
+ async function run(action, nothing = NOTHING_APPROVED) {
93
+ try {
94
+ await action();
95
+ }
96
+ catch (error) {
97
+ if (error instanceof Refusal)
98
+ console.error(`Error: ${error.message}`);
99
+ else if (error instanceof ApprovalStoreError)
100
+ console.error(`Error: ${error.message}; ${nothing}`);
101
+ else
102
+ console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
103
+ process.exitCode = 1;
104
+ }
105
+ }
106
+ export function register(program) {
107
+ const group = program
108
+ .command("backup-approval")
109
+ .description("Approve backup archives for restore on this host (a local store no REST route can reach)");
110
+ cli.addSharedCredentialOptions(group
111
+ .command("approve <archive>")
112
+ .description("Verify an archive against its .sha256 sidecar, store its exact bytes and record your approval")
113
+ .option("--port <port>", "Harper HTTP port of this host's Flair")
114
+ .option("--ops-port <port>", "Harper operations API port of this host's Flair, which verifies the credentials (default: FLAIR_OPS_PORT, local config, or HTTP port minus one)")).action((archivePath, opts) => run(async () => {
115
+ const archiveBytes = importFile(archivePath, "archive");
116
+ const digestPath = backupDigestPath(archivePath);
117
+ let sidecarBytes;
118
+ try {
119
+ sidecarBytes = readImportFile(digestPath, "archive digest sidecar");
120
+ }
121
+ catch (error) {
122
+ if (!(error instanceof ApprovalStoreError) && errnoCode(error) === "ENOENT") {
123
+ throw new Refusal(`archive digest sidecar ${digestPath} not found; ${NOTHING_APPROVED}. Put the .sha256 file written with this ` +
124
+ `archive beside it, or, for an archive written before flair backup published digests, use ` +
125
+ `flair backup-approval legacy-admit ${archivePath}`);
126
+ }
127
+ if (error instanceof ApprovalStoreError)
128
+ throw new Refusal(`${error.message}; ${NOTHING_APPROVED}`);
129
+ throw new Refusal(`cannot read archive digest sidecar ${digestPath} (${errnoCode(error)}); ${NOTHING_APPROVED}`);
130
+ }
131
+ // The same verification restore runs, over the two buffers just read.
132
+ const served = new Map([[archivePath, archiveBytes], [digestPath, sidecarBytes]]);
133
+ const verified = readBackupArtifact(archivePath, {
134
+ stopped: NOTHING_APPROVED,
135
+ readFile: (path) => {
136
+ const bytes = served.get(path);
137
+ if (bytes === undefined)
138
+ throw Object.assign(new Error("unexpected read"), { code: "EINVAL" });
139
+ return bytes;
140
+ },
141
+ });
142
+ if (verified.ok === false)
143
+ throw new Refusal(verified.reason);
144
+ const operator = await verifyOperator(opts, "approval");
145
+ const record = approveArchive({
146
+ bytes: archiveBytes, sha256: verified.sha256, admission: "sidecar", operator, archiveName: basename(archivePath),
147
+ });
148
+ printRecord(`Approved ${archivePath} on this host`, record);
149
+ }));
150
+ cli.addSharedCredentialOptions(group
151
+ .command("legacy-admit <archive>")
152
+ .description("Approve an archive that has no .sha256 sidecar: prints its SHA-256; repeat it with --confirm-digest to approve")
153
+ .option("--confirm-digest <sha256>", "The archive's SHA-256, as printed by a first run, confirming you approve exactly these bytes")
154
+ .option("--port <port>", "Harper HTTP port of this host's Flair")
155
+ .option("--ops-port <port>", "Harper operations API port of this host's Flair, which verifies the credentials (default: FLAIR_OPS_PORT, local config, or HTTP port minus one)")).action((archivePath, opts) => run(async () => {
156
+ const bytes = importFile(archivePath, "archive");
157
+ const digestPath = backupDigestPath(archivePath);
158
+ let sidecarPresent = false;
159
+ try {
160
+ readImportFile(digestPath, "archive digest sidecar");
161
+ sidecarPresent = true;
162
+ }
163
+ catch (error) {
164
+ if (error instanceof ApprovalStoreError || errnoCode(error) !== "ENOENT")
165
+ sidecarPresent = true;
166
+ }
167
+ if (sidecarPresent) {
168
+ throw new Refusal(`${archivePath} has a digest sidecar at ${digestPath}, so it is not a legacy archive; ${NOTHING_APPROVED}. ` +
169
+ `Use flair backup-approval approve ${archivePath}`);
170
+ }
171
+ const parsed = parseRestoreArchive(bytes);
172
+ if (parsed.ok === false) {
173
+ const location = parsed.location === "" ? "/" : parsed.location;
174
+ throw new Refusal(`${archivePath} is not a restorable archive: ${parsed.reason} (${parsed.code} at ${location}); ${NOTHING_APPROVED}`);
175
+ }
176
+ console.log(render.kv("Archive", archivePath));
177
+ console.log(render.kv("SHA-256", parsed.sha256));
178
+ console.log(render.kv("Size", `${bytes.length} bytes`));
179
+ console.log("An archive without a sidecar carries no record of the digest it was written with. Approving it authorizes " +
180
+ "these exact bytes on this host until revoked; it does not show where they came from or that they are " +
181
+ "unchanged since the backup.");
182
+ const confirmed = opts.confirmDigest;
183
+ if (confirmed === undefined) {
184
+ throw new Refusal(`legacy admission needs you to confirm the digest above; ${NOTHING_APPROVED}. Compare it with a record you ` +
185
+ `trust, then run flair backup-approval legacy-admit ${archivePath} --confirm-digest ${parsed.sha256}`);
186
+ }
187
+ if (confirmed !== parsed.sha256) {
188
+ throw new Refusal(`--confirm-digest does not match the archive's SHA-256 ${parsed.sha256}; ${NOTHING_APPROVED}`);
189
+ }
190
+ const operator = await verifyOperator(opts, "legacy admission");
191
+ const record = approveArchive({ bytes, sha256: parsed.sha256, admission: "legacy", operator, archiveName: basename(archivePath) });
192
+ printRecord(`Approved ${archivePath} on this host (legacy admission)`, record);
193
+ }));
194
+ group
195
+ .command("list")
196
+ .description("List the archive approvals on this host and check each stored copy")
197
+ .action(() => run(async () => {
198
+ const listed = listApprovals();
199
+ if (listed.length === 0) {
200
+ console.log(`No archive approvals on this host (${defaultApprovalStoreRoot()}).`);
201
+ return;
202
+ }
203
+ for (const { record, stored } of listed) {
204
+ const status = record.revokedAt === null ? "approved" : `revoked ${record.revokedAt} by ${record.revokedBy}`;
205
+ console.log(`${record.sha256} ${status} ${record.admission} approved ${record.approvedAt} by ${record.approvedBy} ` +
206
+ `${record.archiveName} stored copy ${stored}`);
207
+ }
208
+ }, "nothing was listed"));
209
+ cli.addSharedCredentialOptions(group
210
+ .command("revoke <sha256>")
211
+ .description("Revoke the approval of an archive digest on this host")
212
+ .option("--port <port>", "Harper HTTP port of this host's Flair")
213
+ .option("--ops-port <port>", "Harper operations API port of this host's Flair, which verifies the credentials (default: FLAIR_OPS_PORT, local config, or HTTP port minus one)")).action((sha256, opts) => run(async () => {
214
+ const operator = await verifyOperator(opts, "revocation", NOTHING_REVOKED);
215
+ const record = revokeApproval(sha256, operator);
216
+ printRecord(`Revoked the approval of ${sha256} on this host`, record);
217
+ }, NOTHING_REVOKED));
218
+ }
@@ -1,9 +1,8 @@
1
1
  import { readExactTableCount } from "../lib/ops-table-count.js";
2
2
  import { resolveAdminUser } from "../lib/auth-resolve.js";
3
3
  import { flairBackupOutputPath } from "../lib/flair-paths.js";
4
+ import { publishBackupArtifact } from "../lib/backup-artifact.js";
4
5
  import * as render from "../render.js";
5
- import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
- import { join } from "node:path";
7
6
  let cli;
8
7
  /** Bind the cli-locals this module depends on. */
9
8
  export function bindCli(fns) {
@@ -12,9 +11,6 @@ export function bindCli(fns) {
12
11
  function addSharedCredentialOptions(...args) {
13
12
  return cli.addSharedCredentialOptions(...args);
14
13
  }
15
- function applyAdminPassFile(...args) {
16
- return cli.applyAdminPassFile(...args);
17
- }
18
14
  function resolveHttpPort(...args) {
19
15
  return cli.resolveHttpPort(...args);
20
16
  }
@@ -37,7 +33,6 @@ export function register(program) {
37
33
  .option("--ops-timeout-ms <ms>", "Operations request timeout, 1–600000 ms (env: FLAIR_BACKUP_OPS_TIMEOUT_MS; default: 10000)")
38
34
  .option("--url <url>", "Flair base URL (overrides --port)")).action(async (opts) => {
39
35
  const baseUrl = opts.url ?? `http://127.0.0.1:${resolveHttpPort(opts)}`;
40
- applyAdminPassFile(opts);
41
36
  // Env is a second-class fallback after the explicit flags (same order
42
37
  // backup used before the shared helper). FLAIR_ADMIN_PASS is still
43
38
  // accepted so existing scripts keep working.
@@ -240,44 +235,53 @@ export function register(program) {
240
235
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
241
236
  const defaultOutput = flairBackupOutputPath(timestamp);
242
237
  const outputPath = opts.output ?? defaultOutput;
243
- let stagingDir;
238
+ const serialized = JSON.stringify(backup, null, 2) + "\n";
239
+ // flair#2664: the archive is published together with `<output>.sha256`,
240
+ // the SHA-256 of exactly these bytes as read back from disk. The previous
241
+ // sidecar is removed before the archive changes and the new one is written
242
+ // after it is in place, so a crash of this backup never leaves the sidecar
243
+ // it wrote beside other bytes. Concurrent backups to one output path are
244
+ // not serialized; a mismatched pair they leave is refused at restore
245
+ // (src/lib/backup-artifact.ts).
246
+ let sha256;
247
+ let digestPath;
248
+ let stagingLeft;
244
249
  try {
245
- mkdirSync(join(outputPath, ".."), { recursive: true });
246
- stagingDir = mkdtempSync(join(outputPath, "..", ".flair-backup-"));
247
- const tmp = join(stagingDir, "archive.json");
248
- const serialized = JSON.stringify(backup, null, 2) + "\n";
249
- writeFileSync(tmp, serialized, { encoding: "utf-8", flag: "wx", mode: 0o600 });
250
- const written = readFileSync(tmp, "utf-8");
251
- const archive = JSON.parse(written);
252
- for (const table of ["agents", "memories", "souls"]) {
253
- if (!Array.isArray(archive[table]) || archive[table].length !== backup[table].length) {
254
- throw new Error(`${table}: archive count does not match fetched count ${backup[table].length}`);
255
- }
256
- for (const [index, row] of backup[table].entries()) {
257
- if (archive[table][index]?.id !== row.id) {
258
- throw new Error(`${table} row ${row.id}: archive id does not match fetched id`);
250
+ ({ sha256, digestPath, stagingLeft } = publishBackupArtifact({
251
+ outputPath,
252
+ serialized,
253
+ verify(written) {
254
+ const archive = JSON.parse(written);
255
+ for (const table of ["agents", "memories", "souls"]) {
256
+ if (!Array.isArray(archive[table]) || archive[table].length !== backup[table].length) {
257
+ throw new Error(`${table}: archive count does not match fetched count ${backup[table].length}`);
258
+ }
259
+ for (const [index, row] of backup[table].entries()) {
260
+ if (archive[table][index]?.id !== row.id) {
261
+ throw new Error(`${table} row ${row.id}: archive id does not match fetched id`);
262
+ }
263
+ if (JSON.stringify(archive[table][index]) !== JSON.stringify(row)) {
264
+ throw new Error(`${table} row ${row.id}: archive contents do not match fetched row`);
265
+ }
266
+ }
259
267
  }
260
- if (JSON.stringify(archive[table][index]) !== JSON.stringify(row)) {
261
- throw new Error(`${table} row ${row.id}: archive contents do not match fetched row`);
262
- }
263
- }
264
- }
265
- if (written !== serialized)
266
- throw new Error("archive contents do not match fetched data");
267
- renameSync(tmp, outputPath);
268
+ if (written !== serialized)
269
+ throw new Error("archive contents do not match fetched data");
270
+ },
271
+ }));
268
272
  }
269
273
  catch (error) {
270
274
  throw new Error(`Backup archive ${outputPath}: ${error instanceof Error ? error.message : String(error)}`);
271
275
  }
272
- finally {
273
- if (stagingDir)
274
- rmSync(stagingDir, { recursive: true, force: true });
275
- }
276
276
  log(`\n${render.icons.ok} ${render.wrap(render.c.green, "Backup complete")}`);
277
277
  log("Collections are read separately and can reflect different moments.");
278
278
  log(render.kv("Agents", render.wrap(render.c.bold, String(agents.length))));
279
279
  log(render.kv("Memories", render.wrap(render.c.bold, String(memories.length))));
280
280
  log(render.kv("Souls", render.wrap(render.c.bold, String(souls.length))));
281
281
  log(render.kv("Output", render.wrap(render.c.dim, outputPath)));
282
+ log(render.kv("SHA-256", render.wrap(render.c.dim, `${sha256} (${digestPath})`)));
283
+ if (stagingLeft) {
284
+ console.error(`Warning: the staging directory ${stagingLeft.path} could not be removed (${stagingLeft.reason}); remove it by hand.`);
285
+ }
282
286
  });
283
287
  }
@@ -1,4 +1,4 @@
1
- import { authedRequest } from "../lib/auth-resolve.js";
1
+ import { ApiRequestOutcomeUnknown, authedRequest } from "../lib/auth-resolve.js";
2
2
  import * as render from "../render.js";
3
3
  let cli;
4
4
  /** Bind the cli-locals this module depends on. */
@@ -84,6 +84,8 @@ export function register(program) {
84
84
  console.error(`${tokenIcon} budget ${tokensUsed}/${maxTokens} tokens (${tokenPct.toFixed(0)}%) ${render.icons.bullet} ${render.icons.ok} ${included} included ${render.icons.bullet} ${truncIcon} ${truncated} truncated`);
85
85
  }
86
86
  catch (err) {
87
+ if (err instanceof ApiRequestOutcomeUnknown)
88
+ throw err;
87
89
  console.error(`${render.icons.error} Bootstrap failed: ${err.message}`);
88
90
  process.exit(1);
89
91
  }