@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -40,9 +40,9 @@
40
40
  * remote instance; see `resolveLocalAdminPass`).
41
41
  * 5. THE FLOOR (flair#747, generalizing flair#742's upgrade-only
42
42
  * fallback) — when NOTHING above resolved to anything sendable at
43
- * all, sign the SAME request with every registered key under
44
- * `~/.flair/keys` (sorted, deterministic order), first one the server
45
- * accepts wins. This is the credential every headless/agent machine
43
+ * all, tries candidate key files under `~/.flair/keys` in order (sorted,
44
+ * deterministic) until one succeeds or an answer is final. This is the
45
+ * credential a headless/agent machine
46
46
  * actually has, and is exactly the flair#741 incident's fix: an agent
47
47
  * key existed the whole time, nothing tried it.
48
48
  *
@@ -64,8 +64,11 @@
64
64
  */
65
65
  import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
66
66
  import { join } from "node:path";
67
+ import { Option } from "commander";
67
68
  import { createPrivateKey, randomUUID, sign as nodeCryptoSign } from "node:crypto";
68
69
  import { resolveHome } from "./home.js";
70
+ import { isConnectPhaseFailure } from "./connect-phase.js";
71
+ export { isConnectPhaseFailure, REFUSED_CODES } from "./connect-phase.js";
69
72
  // ─── Failure classification ─────────────────────────────────────────────────
70
73
  /**
71
74
  * Thrown by `sendJsonRequest` for an HTTP-level failure (as opposed to a
@@ -79,16 +82,685 @@ import { resolveHome } from "./home.js";
79
82
  * case — distinguishes "we had nothing to send" from "we sent
80
83
  * something and it was rejected", which is exactly the signal
81
84
  * `authedRequest` uses to decide whether tier 5 (the floor) applies.
85
+ * - `body` (flair#2764): the display form of the response body, set by
86
+ * `fromResponse` (`displayBody`), with the credential values
87
+ * `credentialsInHeader` read from the request's Authorization header: a
88
+ * JSON body re-serialized with every string in it redacted after decoding,
89
+ * or withheld when it cannot be; any other body redacted as text; and any
90
+ * non-empty body withheld when that header names basic, bearer or
91
+ * tps-ed25519 but its credential could not be read (an empty body stays
92
+ * empty, and the message is then the status alone). The message's reason is decided
93
+ * separately (`describeHttpFailure`), from the unredacted text:
94
+ * BODY_WITHHELD for any non-empty body when the header's credential could
95
+ * not be read; otherwise the JSON body's named error, redacted, even when
96
+ * `body` is withheld; otherwise an excerpt of the text, redacted, or
97
+ * BODY_WITHHELD when displayBody withholds the body. Its `HTTP <status>`
98
+ * prefix is not passed through redaction. Classifiers read the unredacted
99
+ * text through `apiErrorRawBody`; the rem formatters that derive display
100
+ * text from it pass that text through `boundErrorText`, which redacts it,
101
+ * or withholds it when the header's credential could not be read and the
102
+ * response text was non-empty (even when the text derived from it is
103
+ * empty). Within
104
+ * the scope below, each of those values becomes `[redacted]` in the
105
+ * server's text as displayed.
106
+ * Scope: redaction removes the request's credential values from the text the
107
+ * server supplied (literal, inside any JSON string, percent-encoded); text the
108
+ * CLI writes itself (the `HTTP <status>: ` prefix, the debug line's labels, a
109
+ * caller's `Error: ` prefix) is never altered, so a credential that matches the
110
+ * CLI's own wording, or matches only once that wording is joined to the
111
+ * server's text, is not covered.
82
112
  */
83
113
  export class ApiHttpError extends Error {
84
114
  status;
85
115
  noCredentials;
86
- constructor(status, message, noCredentials = false) {
116
+ body;
117
+ constructor(status, message, noCredentials = false, body) {
87
118
  super(message);
88
119
  this.name = "ApiHttpError";
89
120
  this.status = status;
90
121
  this.noCredentials = noCredentials;
122
+ this.body = body;
91
123
  }
124
+ /**
125
+ * The error for a non-2xx response whose body text is `body` (flair#2764).
126
+ * `sentValues` are the credential values `credentialsInHeader` read from the
127
+ * request's Authorization header: the message and `body` are redacted with them
128
+ * (within the scope on ApiHttpError). `withhold` is credentialsInHeader's
129
+ * flag: when set, the server's non-empty text is shown as BODY_WITHHELD in the message
130
+ * and `body`. The unredacted text, the values and the flag are kept in a
131
+ * module-private map for apiErrorRawBody and boundErrorText.
132
+ */
133
+ static fromResponse(status, body, sentValues = [], withhold = false) {
134
+ const err = new ApiHttpError(status, describeHttpFailure(status, body, sentValues, withhold), false, displayBody(body, sentValues, withhold));
135
+ privateText.set(err, { raw: body, sentValues: [...sentValues], withhold });
136
+ return err;
137
+ }
138
+ }
139
+ /**
140
+ * The whole-request deadline `sendJsonRequest` enforces when
141
+ * `FLAIR_REQUEST_TIMEOUT_MS` is unset and the caller passes no deadline. Five
142
+ * minutes is above the figures the repo's responsiveness fixture reports for
143
+ * the CLI: a dedup pass at 23.07 s over 403 live vectors, and a
144
+ * 3,065-row repro that exceeded a 60 s client deadline
145
+ * (test/bench/rem-responsiveness.md); the repro's own duration was not
146
+ * measured. A single memory write's server-side embedding provider bound is
147
+ * 20 s (resources/memory-write-lock.ts).
148
+ */
149
+ export const DEFAULT_REQUEST_DEADLINE_MS = 300_000;
150
+ /** The env var that overrides {@link DEFAULT_REQUEST_DEADLINE_MS}. */
151
+ export const REQUEST_DEADLINE_ENV = "FLAIR_REQUEST_TIMEOUT_MS";
152
+ /** Bounds of {@link REQUEST_DEADLINE_ENV}: an integer from 1 ms to one hour. */
153
+ export const REQUEST_DEADLINE_MIN_MS = 1;
154
+ export const REQUEST_DEADLINE_MAX_MS = 3_600_000;
155
+ /** The env var that overrides {@link DEFAULT_REM_REQUEST_DEADLINE_MS}. */
156
+ export const REM_REQUEST_DEADLINE_ENV = "FLAIR_REM_REQUEST_TIMEOUT_MS";
157
+ /**
158
+ * The single whole-request deadline for the REM work routes: POST
159
+ * /MemoryMaintenance, POST /ReflectMemories, POST /MemoryDedupStats and POST
160
+ * /AutoPromoteCandidates. The sizing basis is the dedup sweep: the repo
161
+ * fixture's 23.07 s over 403 live vectors is ~57 ms/memory, and the route
162
+ * scans every Memory row before it selects the capped ANN set of up to 20,000
163
+ * (DEDUP_CLUSTER_MAX_MEMORIES_DEFAULT), so 20,000 x ~57 ms = ~1,140 s and this
164
+ * deadline sits above it. It is a sizing estimate, not a throughput claim, and
165
+ * is within {@link REQUEST_DEADLINE_MAX_MS}. {@link REM_REQUEST_DEADLINE_ENV}
166
+ * overrides it; every other request through the shared REST sender that passes
167
+ * no explicit deadline resolves FLAIR_REQUEST_TIMEOUT_MS, else the shared
168
+ * default.
169
+ */
170
+ export const DEFAULT_REM_REQUEST_DEADLINE_MS = 1_800_000;
171
+ /**
172
+ * One deadline value from `raw`: undefined when the variable is unset, empty or
173
+ * whitespace-only; the number when it is an integer in range; a refusal naming
174
+ * `name` otherwise.
175
+ */
176
+ function parseDeadlineEnv(name, raw) {
177
+ if (raw === undefined || raw.trim() === "")
178
+ return undefined;
179
+ const value = Number(raw);
180
+ if (!Number.isSafeInteger(value) || value < REQUEST_DEADLINE_MIN_MS || value > REQUEST_DEADLINE_MAX_MS) {
181
+ throw new Error(`${name} must be an integer from ${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS} (milliseconds)`);
182
+ }
183
+ return value;
184
+ }
185
+ /**
186
+ * The whole-request deadline in force: `explicit` when given, else the env
187
+ * override, else the default. An explicit deadline is validated and returned
188
+ * before `FLAIR_REQUEST_TIMEOUT_MS` is read, so an invalid value of that
189
+ * variable refuses only the requests it governs — those with no explicit
190
+ * deadline. An out-of-range or non-integer env value is refused here, before
191
+ * any request is sent, naming the variable and the range; it is never
192
+ * silently defaulted. An empty or whitespace-only value is unset.
193
+ */
194
+ export function resolveRequestDeadlineMs(explicit = undefined, env = process.env) {
195
+ if (explicit !== undefined) {
196
+ if (!Number.isSafeInteger(explicit) || explicit < REQUEST_DEADLINE_MIN_MS || explicit > REQUEST_DEADLINE_MAX_MS) {
197
+ throw new Error(`request deadline must be an integer from ${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS} (milliseconds)`);
198
+ }
199
+ return explicit;
200
+ }
201
+ return parseDeadlineEnv(REQUEST_DEADLINE_ENV, env[REQUEST_DEADLINE_ENV]) ?? DEFAULT_REQUEST_DEADLINE_MS;
202
+ }
203
+ /**
204
+ * The REM work deadline in force: {@link REM_REQUEST_DEADLINE_ENV} when set,
205
+ * else {@link DEFAULT_REM_REQUEST_DEADLINE_MS}. An out-of-range or non-integer
206
+ * value is refused here, before the REM work request is sent, naming the
207
+ * variable and the range; an empty or whitespace-only value is unset.
208
+ */
209
+ export function resolveRemRequestDeadlineMs(env = process.env) {
210
+ return parseDeadlineEnv(REM_REQUEST_DEADLINE_ENV, env[REM_REQUEST_DEADLINE_ENV]) ?? DEFAULT_REM_REQUEST_DEADLINE_MS;
211
+ }
212
+ /** The `HTTP <status>` clause for a deadline that fired after a status line. */
213
+ function deadlineStatusClause(status) {
214
+ return status === undefined ? "" : `; the instance answered HTTP ${status} but its response body did not complete`;
215
+ }
216
+ /** The variable, if any, that governs a deadline from `source`. */
217
+ function deadlineEnvName(source) {
218
+ if (source === "env")
219
+ return REQUEST_DEADLINE_ENV;
220
+ if (source === "rem")
221
+ return REM_REQUEST_DEADLINE_ENV;
222
+ return undefined;
223
+ }
224
+ /** The remedy named in an expiry message for a deadline from `source`. */
225
+ function deadlineRemedy(source) {
226
+ const envName = deadlineEnvName(source);
227
+ if (envName === undefined) {
228
+ return `This command sets its own deadline; raise it there if this request legitimately runs longer.`;
229
+ }
230
+ return `Raise ${envName} (${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS}) if this request legitimately runs longer.`;
231
+ }
232
+ /**
233
+ * Thrown when a GET or HEAD crosses the whole-request deadline. The split is by
234
+ * method, not by effect: GET and HEAD that reach the deadline throw this type,
235
+ * and every other method throws {@link ApiRequestOutcomeUnknown}. A GET is not
236
+ * proof of no effect — `GET /FederationInstance` creates the identity row on
237
+ * first boot — so this type reports only that no complete response arrived.
238
+ */
239
+ export class ApiRequestTimeout extends Error {
240
+ method;
241
+ path;
242
+ deadlineMs;
243
+ /** The status line that arrived before the deadline fired, when one did. */
244
+ status;
245
+ constructor(method, path, deadlineMs, status, source) {
246
+ const envName = deadlineEnvName(source);
247
+ super(`${method} ${path} did not complete within ${deadlineMs} ms` +
248
+ (envName === undefined ? "" : ` (${envName})`) +
249
+ deadlineStatusClause(status));
250
+ this.name = "ApiRequestTimeout";
251
+ this.method = method;
252
+ this.path = path;
253
+ this.deadlineMs = deadlineMs;
254
+ this.status = status;
255
+ }
256
+ }
257
+ /**
258
+ * Thrown for a write's deadline expiry, non-connect-phase fetch failure, or
259
+ * failed 2xx body read. No caller may retry the write blindly.
260
+ */
261
+ export class ApiRequestOutcomeUnknown extends Error {
262
+ method;
263
+ path;
264
+ /** The deadline that expired, or undefined for a transport failure. */
265
+ deadlineMs;
266
+ /** The status line that arrived before the deadline expired or the response read failed, when one did. */
267
+ status;
268
+ constructor(method, path, deadlineMs, status, source, detail) {
269
+ const envName = deadlineEnvName(source);
270
+ super(detail ??
271
+ `${method} ${path} may or may not have taken effect: no complete response within ${deadlineMs} ms` +
272
+ (envName === undefined ? "" : ` (${envName})`) +
273
+ `${deadlineStatusClause(status)}. Expiry does not show whether the request was delivered or took effect; do not retry it blindly. ${deadlineRemedy(source)}`);
274
+ this.name = "ApiRequestOutcomeUnknown";
275
+ this.method = method;
276
+ this.path = path;
277
+ this.deadlineMs = deadlineMs;
278
+ this.status = status;
279
+ }
280
+ /** Name the requested origin and warn against retrying. */
281
+ static fromTransportFailure(method, path, url, cause, status) {
282
+ const detail = status === undefined
283
+ ? `${method} ${path} to ${url}: no final response; outcome unknown, write may have been applied. ` +
284
+ `Check the server (or the origin it redirected to) before retrying.`
285
+ : `${method} ${path} to ${url}: the successful response body could not be read (HTTP ${status}); outcome unknown, write may have been applied. ` +
286
+ `Check the server (or the origin it redirected to) before retrying.`;
287
+ const err = new ApiRequestOutcomeUnknown(method, path, undefined, status, "explicit", detail);
288
+ err.cause = cause;
289
+ return err;
290
+ }
291
+ }
292
+ /**
293
+ * An ApiHttpError's unredacted response text and the credential values its
294
+ * request sent (flair#2764), kept for classification and redaction: only
295
+ * apiErrorRawBody (the text) and boundErrorText (which uses the values to
296
+ * redact) read this map. No field of the error holds the sent values; `body`
297
+ * and the message are display forms of the raw text, which may equal it.
298
+ */
299
+ const privateText = new WeakMap();
300
+ /** What a credential value the request sent becomes in the server's text as displayed. */
301
+ export const REDACTED_CREDENTIAL = "[redacted]";
302
+ /**
303
+ * Copy of TPS_ED25519_HEADER_RE in resources/ed25519-auth.ts, the grammar
304
+ * Flair's server parses a TPS-Ed25519 header with. The CLI build cannot import
305
+ * from resources/, so test/unit/http-error-reason-2764.test.ts asserts the two
306
+ * have the same source and flags (flair#2764).
307
+ */
308
+ export const TPS_ED25519_HEADER_GRAMMAR = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)$/i;
309
+ /** Copy of BASIC_AUTH_HEADER_RE in resources/basic-auth-header.ts, held to it by the same test (flair#2764). */
310
+ export const BASIC_HEADER_GRAMMAR = /^Basic /i;
311
+ /** The schemes credentialsInHeader extracts a credential from (lower case). */
312
+ const KNOWN_SCHEMES = new Set(["basic", "bearer", "tps-ed25519"]);
313
+ /**
314
+ * The credential values an Authorization header carries (flair#2764), read
315
+ * from the value Fetch sends: the header with leading and trailing HTTP
316
+ * whitespace (tab, line feed, carriage return, space) removed, as Fetch
317
+ * normalizes it. The scheme is the text before the first run of whitespace
318
+ * (any character the regular expression class for whitespace matches),
319
+ * compared without regard to case. The values are that header value, the
320
+ * part after the scheme (as written and with surrounding whitespace trimmed),
321
+ * and for:
322
+ * - basic: the decoded `user:password` (or the decoded text, without a
323
+ * colon) and the password. When the header matches BASIC_HEADER_GRAMMAR,
324
+ * the server's own grammar, the decoded text is read as the server reads
325
+ * it (the text after its first six characters); otherwise from the part
326
+ * after the scheme;
327
+ * - tps-ed25519: the signature, read with TPS_ED25519_HEADER_GRAMMAR, the
328
+ * server's own grammar.
329
+ * `withhold` is set when the scheme is basic, bearer or tps-ed25519 but no
330
+ * decoded text, token or signature could be extracted that way; the server's
331
+ * text is then withheld rather than shown. Empty values are left out.
332
+ */
333
+ export function credentialsInHeader(authHeader) {
334
+ if (!authHeader)
335
+ return { values: [], withhold: false };
336
+ const sent = authHeader.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
337
+ const scheme = (/^\S+/.exec(sent)?.[0] ?? "").toLowerCase();
338
+ const credential = /^\S+\s+([\s\S]*)$/.exec(sent)?.[1] ?? "";
339
+ const values = [sent, credential, credential.trim()];
340
+ let extracted = false;
341
+ if (scheme === "basic") {
342
+ const encoded = BASIC_HEADER_GRAMMAR.test(sent) ? sent.slice(6) : credential.trim();
343
+ const decoded = Buffer.from(encoded, "base64").toString("utf8");
344
+ if (decoded.length > 0) {
345
+ const colon = decoded.indexOf(":");
346
+ values.push(decoded);
347
+ if (colon !== -1)
348
+ values.push(decoded.slice(colon + 1));
349
+ extracted = true;
350
+ }
351
+ }
352
+ else if (scheme === "tps-ed25519") {
353
+ const parsed = TPS_ED25519_HEADER_GRAMMAR.exec(sent);
354
+ if (parsed) {
355
+ values.push(parsed[4]);
356
+ extracted = true;
357
+ }
358
+ }
359
+ else if (scheme === "bearer") {
360
+ extracted = credential.trim().length > 0;
361
+ }
362
+ return { values: values.filter((value) => value.length > 0), withhold: KNOWN_SCHEMES.has(scheme) && !extracted };
363
+ }
364
+ const HEX2 = /^[0-9A-Fa-f]{2}$/;
365
+ const HEX4 = /^[0-9A-Fa-f]{4}$/;
366
+ /** The character each one-character JSON string escape (backslash, then this character) stands for. */
367
+ const JSON_SHORT_ESCAPES = {
368
+ '"': '"',
369
+ "\\": "\\",
370
+ "/": "/",
371
+ b: "\b",
372
+ f: "\f",
373
+ n: "\n",
374
+ r: "\r",
375
+ t: "\t",
376
+ };
377
+ /**
378
+ * One decoded unit of credentialIntervals' view at `i` in `text`: the string it
379
+ * stands for and how many characters of `text` it spans. A valid %XX escape
380
+ * (either hex case) stands for its byte, given as a one-byte buffer; a JSON
381
+ * string escape (backslash then one of the characters in JSON_SHORT_ESCAPES,
382
+ * or backslash-u with four hex digits, a surrogate pair of two such escapes
383
+ * read as one character) stands for its character; anything else stands for
384
+ * itself.
385
+ */
386
+ function viewUnit(text, i) {
387
+ if (text[i] === "%" && HEX2.test(text.slice(i + 1, i + 3))) {
388
+ return { bytes: Buffer.from([Number.parseInt(text.slice(i + 1, i + 3), 16)]), width: 3 };
389
+ }
390
+ if (text[i] === "\\" && i + 1 < text.length) {
391
+ const next = text[i + 1];
392
+ const short = JSON_SHORT_ESCAPES[next];
393
+ if (short !== undefined)
394
+ return { bytes: Buffer.from(short, "utf8"), width: 2 };
395
+ if (next === "u" && HEX4.test(text.slice(i + 2, i + 6))) {
396
+ const unit = Number.parseInt(text.slice(i + 2, i + 6), 16);
397
+ if (unit >= 0xd800 && unit <= 0xdbff && text.slice(i + 6, i + 8) === "\\u" && HEX4.test(text.slice(i + 8, i + 12))) {
398
+ const low = Number.parseInt(text.slice(i + 8, i + 12), 16);
399
+ if (low >= 0xdc00 && low <= 0xdfff) {
400
+ return { bytes: Buffer.from(String.fromCharCode(unit, low), "utf8"), width: 12 };
401
+ }
402
+ }
403
+ if (unit < 0xd800 || unit > 0xdfff)
404
+ return { bytes: Buffer.from(String.fromCharCode(unit), "utf8"), width: 6 };
405
+ }
406
+ }
407
+ const width = (text.codePointAt(i) ?? 0) > 0xffff ? 2 : 1;
408
+ return { bytes: Buffer.from(text.slice(i, i + width), "utf8"), width };
409
+ }
410
+ /**
411
+ * Every occurrence in `text` of each value in `sentValues`, overlapping ones
412
+ * included, as merged [start, end) intervals of `text` (flair#2764): intervals
413
+ * that overlap or touch become one. A value is found where `text` holds it
414
+ * literally, and, when `text` contains a "%" or a backslash, where `text`
415
+ * spells it with %XX escapes (either hex case) or JSON string escapes, for all
416
+ * or some of its characters: that search runs over a view of `text` with each
417
+ * such escape decoded (viewUnit), and maps each match back to the characters
418
+ * it came from. This holds whether or not `text` as a whole is valid JSON.
419
+ */
420
+ function credentialIntervals(text, sentValues) {
421
+ const found = [];
422
+ const values = sentValues.filter((value) => value.length > 0);
423
+ if (values.length === 0 || text.length === 0)
424
+ return found;
425
+ for (const value of values) {
426
+ for (let at = text.indexOf(value); at !== -1; at = text.indexOf(value, at + 1)) {
427
+ found.push([at, at + value.length]);
428
+ }
429
+ }
430
+ if (text.includes("%") || text.includes("\\")) {
431
+ // bytes: the decoded view; from/to: the [start, end) of `text` each byte came from.
432
+ const bytes = [];
433
+ const from = [];
434
+ const to = [];
435
+ for (let i = 0; i < text.length;) {
436
+ const unit = viewUnit(text, i);
437
+ for (const byte of unit.bytes) {
438
+ bytes.push(byte);
439
+ from.push(i);
440
+ to.push(i + unit.width);
441
+ }
442
+ i += unit.width;
443
+ }
444
+ const view = Buffer.from(bytes);
445
+ for (const value of values) {
446
+ const needle = Buffer.from(value, "utf8");
447
+ for (let at = view.indexOf(needle); at !== -1; at = view.indexOf(needle, at + 1)) {
448
+ found.push([from[at], to[at + needle.length - 1]]);
449
+ }
450
+ }
451
+ }
452
+ found.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
453
+ const merged = [];
454
+ for (const [start, end] of found) {
455
+ const last = merged[merged.length - 1];
456
+ if (last && start <= last[1])
457
+ last[1] = Math.max(last[1], end);
458
+ else
459
+ merged.push([start, end]);
460
+ }
461
+ return merged;
462
+ }
463
+ /** `text` with each interval replaced by `marker`. */
464
+ function replaceIntervals(text, intervals, marker) {
465
+ if (intervals.length === 0)
466
+ return text;
467
+ let out = "";
468
+ let at = 0;
469
+ for (const [start, end] of intervals) {
470
+ out += text.slice(at, start) + marker;
471
+ at = end;
472
+ }
473
+ return out + text.slice(at);
474
+ }
475
+ /** `text` when credentialIntervals finds no sent value in it, else `fallback` (flair#2764). */
476
+ function withoutOccurrence(text, sentValues, fallback) {
477
+ return credentialIntervals(text, sentValues).length === 0 ? text : fallback;
478
+ }
479
+ /**
480
+ * Server-supplied `text` with each merged interval of credentialIntervals
481
+ * replaced once by REDACTED_CREDENTIAL (flair#2764), in one pass: the server's
482
+ * text left in the result holds no occurrence credentialIntervals finds. The
483
+ * marker, and anything the CLI writes around the result, is not checked. The
484
+ * scope is the one on ApiHttpError.
485
+ */
486
+ export function redactSentCredentials(text, sentValues) {
487
+ return replaceIntervals(text, credentialIntervals(text, sentValues), REDACTED_CREDENTIAL);
488
+ }
489
+ /**
490
+ * A parsed JSON value with every string in it, object keys included, redacted,
491
+ * and every number, boolean or null whose JSON text holds a sent value replaced
492
+ * by the string REDACTED_CREDENTIAL (flair#2764).
493
+ */
494
+ function redactJsonValues(value, sentValues) {
495
+ if (typeof value === "string")
496
+ return redactSentCredentials(value, sentValues);
497
+ if (Array.isArray(value))
498
+ return value.map((item) => redactJsonValues(item, sentValues));
499
+ if (value && typeof value === "object") {
500
+ const out = Object.create(null);
501
+ for (const [key, item] of Object.entries(value)) {
502
+ out[redactSentCredentials(key, sentValues)] = redactJsonValues(item, sentValues);
503
+ }
504
+ return out;
505
+ }
506
+ return credentialIntervals(JSON.stringify(value), sentValues).length === 0 ? value : REDACTED_CREDENTIAL;
507
+ }
508
+ /** What displayBody shows for a body it cannot show: see displayBody. */
509
+ export const BODY_WITHHELD = "[body withheld]";
510
+ /**
511
+ * A response body for display (flair#2764). A body JSON.parse rejects with a
512
+ * SyntaxError (not JSON) is shown as received, redacted as text. A JSON body
513
+ * is shown re-serialized, with every string in it (keys included) redacted
514
+ * after JSON decoding and any other value whose JSON text holds a sent value
515
+ * replaced; or as BODY_WITHHELD when it cannot be: when parsing fails any
516
+ * other way (for example a nesting too deep to parse), when its redaction or
517
+ * re-serialization fails, or when the re-serialized JSON still holds a sent
518
+ * value (for example a value that occurs in JSON syntax). With `withhold` set
519
+ * (credentialsInHeader), a non-empty body is shown as BODY_WITHHELD.
520
+ */
521
+ function displayBody(body, sentValues, withhold = false) {
522
+ if (withhold && body.length > 0)
523
+ return BODY_WITHHELD;
524
+ let parsed;
525
+ try {
526
+ parsed = JSON.parse(body);
527
+ }
528
+ catch (err) {
529
+ if (err instanceof SyntaxError)
530
+ return redactSentCredentials(body, sentValues);
531
+ return BODY_WITHHELD;
532
+ }
533
+ try {
534
+ return withoutOccurrence(JSON.stringify(redactJsonValues(parsed, sentValues)), sentValues, BODY_WITHHELD);
535
+ }
536
+ catch {
537
+ return BODY_WITHHELD;
538
+ }
539
+ }
540
+ /** What displayPath shows for a path it cannot show. */
541
+ export const PATH_WITHHELD = "[path withheld]";
542
+ /** C0 controls, DEL, C1 controls and the Unicode line and paragraph separators. */
543
+ const CONTROL_CHARACTER = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/;
544
+ /**
545
+ * A request path for display (flair#2764): percent-decoded, then redacted.
546
+ * PATH_WITHHELD when it does not decode or the decoded path holds a
547
+ * CONTROL_CHARACTER.
548
+ */
549
+ function displayPath(path, sentValues) {
550
+ let decoded;
551
+ try {
552
+ decoded = decodeURIComponent(path);
553
+ }
554
+ catch {
555
+ return PATH_WITHHELD;
556
+ }
557
+ if (CONTROL_CHARACTER.test(decoded))
558
+ return PATH_WITHHELD;
559
+ return redactSentCredentials(decoded, sentValues);
560
+ }
561
+ /** The most characters boundServerText keeps before it cuts the text and appends "..." (flair#2764). */
562
+ export const SERVER_TEXT_MAX_CHARS = 200;
563
+ /**
564
+ * Server text as one line: control characters that are not whitespace are
565
+ * removed, each run of whitespace (line breaks included) becomes one space,
566
+ * and the ends are trimmed.
567
+ */
568
+ function oneLine(text) {
569
+ return text
570
+ .replace(/[\u0000-\u0008\u000E-\u001F\u007F-\u0084\u0086-\u009F]/g, "")
571
+ .replace(/[\s\u0085]+/g, " ")
572
+ .trim();
573
+ }
574
+ /** `line` cut after SERVER_TEXT_MAX_CHARS characters, ending in "...", when it is longer. */
575
+ function cutToBound(line) {
576
+ let count = 0;
577
+ let index = 0;
578
+ for (const ch of line) {
579
+ if (count === SERVER_TEXT_MAX_CHARS)
580
+ return `${line.slice(0, index).trimEnd()}...`;
581
+ count++;
582
+ index += ch.length;
583
+ }
584
+ return line;
585
+ }
586
+ /**
587
+ * Server text as one line: control characters that are not whitespace are
588
+ * removed, each run of whitespace (line breaks included) becomes one space and
589
+ * the ends are trimmed, and text longer than SERVER_TEXT_MAX_CHARS characters
590
+ * is cut there and ends in "...".
591
+ */
592
+ export function boundServerText(text) {
593
+ return cutToBound(oneLine(text));
594
+ }
595
+ /**
596
+ * A private-use character no value in `sentValues` contains, standing in for
597
+ * REDACTED_CREDENTIAL while boundAndRedact works: line-making leaves it alone
598
+ * and no sent value can match it, so the second pass does not alter the marker.
599
+ * The private-use ranges hold over 137,000 characters, more than an
600
+ * Authorization header the transport sends can contain; were none free, the
601
+ * marker itself would stand in.
602
+ */
603
+ function standInFor(sentValues) {
604
+ for (const [first, last] of [[0xe000, 0xf8ff], [0xf0000, 0xffffd], [0x100000, 0x10fffd]]) {
605
+ for (let cp = first; cp <= last; cp++) {
606
+ const ch = String.fromCodePoint(cp);
607
+ if (!sentValues.some((value) => value.includes(ch)))
608
+ return ch;
609
+ }
610
+ }
611
+ return REDACTED_CREDENTIAL;
612
+ }
613
+ /**
614
+ * The text of `line` (holding stand-ins `standIn`, each displayed as
615
+ * REDACTED_CREDENTIAL) that fits SERVER_TEXT_MAX_CHARS displayed characters,
616
+ * ending before a stand-in that does not fit and never inside a %XX or JSON
617
+ * string escape credentialIntervals decodes (viewUnit), with trailing
618
+ * whitespace trimmed; null when all of `line` fits (flair#2764).
619
+ */
620
+ function keptBeforeCut(line, standIn) {
621
+ let count = 0;
622
+ let index = 0;
623
+ let cut = -1;
624
+ for (const ch of line) {
625
+ const width = ch === standIn ? REDACTED_CREDENTIAL.length : 1;
626
+ if (count + width > SERVER_TEXT_MAX_CHARS) {
627
+ cut = index;
628
+ break;
629
+ }
630
+ count += width;
631
+ index += ch.length;
632
+ }
633
+ if (cut === -1)
634
+ return null;
635
+ let boundary = cut;
636
+ if (line.includes("%") || line.includes("\\")) {
637
+ for (let i = 0; i < cut;) {
638
+ const width = viewUnit(line, i).width;
639
+ if (i + width > cut) {
640
+ boundary = i;
641
+ break;
642
+ }
643
+ i += width;
644
+ }
645
+ }
646
+ return line.slice(0, boundary).trimEnd();
647
+ }
648
+ /**
649
+ * boundServerText for output, with `sentValues` redacted from the server's
650
+ * text (flair#2764). Order: redact, make one line, redact again, cut. Each
651
+ * occurrence is replaced by a stand-in character (standInFor) while this
652
+ * works; the first pass catches a credential before line-making can change it
653
+ * (a whitespace run collapsed, a control character removed), and the second
654
+ * catches one that line-making forms. The cut (keptBeforeCut) counts each
655
+ * stand-in as the marker's length and falls between view units, so it splits
656
+ * neither the marker nor an occurrence; then the stand-ins become
657
+ * REDACTED_CREDENTIAL and "..." is appended to a cut text. Neither the marker
658
+ * nor "..." is passed through redaction.
659
+ */
660
+ function boundAndRedact(text, sentValues) {
661
+ if (sentValues.length === 0)
662
+ return boundServerText(text);
663
+ const standIn = standInFor(sentValues);
664
+ let line = oneLine(replaceIntervals(text, credentialIntervals(text, sentValues), standIn));
665
+ line = replaceIntervals(line, credentialIntervals(line, sentValues), standIn);
666
+ const shown = (t) => t.split(standIn).join(REDACTED_CREDENTIAL);
667
+ const kept = keptBeforeCut(line, standIn);
668
+ return kept === null ? shown(line) : `${shown(kept)}...`;
669
+ }
670
+ /**
671
+ * The message of an ApiHttpError built from a response body (flair#2764):
672
+ * `HTTP <status>`, then the body's named error when the body is a JSON object
673
+ * with an `error`, else `code`, else `message` string that is non-empty once
674
+ * bounded; otherwise an excerpt of the body, or BODY_WITHHELD when displayBody
675
+ * withholds the body. The named error and the excerpt are read from the
676
+ * unredacted body and go through boundAndRedact with `sentValues`. The
677
+ * `HTTP <status>` prefix and BODY_WITHHELD are written by this function and
678
+ * are not passed through redaction. With `withhold` set (credentialsInHeader),
679
+ * the reason for a non-empty body is BODY_WITHHELD.
680
+ */
681
+ export function describeHttpFailure(status, body, sentValues = [], withhold = false) {
682
+ if (withhold && body.length > 0)
683
+ return `HTTP ${status}: ${BODY_WITHHELD}`;
684
+ let reason = "";
685
+ let parsed;
686
+ try {
687
+ parsed = JSON.parse(body);
688
+ }
689
+ catch {
690
+ parsed = undefined;
691
+ }
692
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
693
+ for (const key of ["error", "code", "message"]) {
694
+ const value = parsed[key];
695
+ if (typeof value === "string")
696
+ reason = boundAndRedact(value, sentValues);
697
+ if (reason)
698
+ break;
699
+ }
700
+ }
701
+ if (!reason) {
702
+ reason = displayBody(body, sentValues) === BODY_WITHHELD ? BODY_WITHHELD : boundAndRedact(body, sentValues);
703
+ }
704
+ return reason ? `HTTP ${status}: ${reason}` : `HTTP ${status}`;
705
+ }
706
+ /**
707
+ * The display form of the response body an ApiHttpError carries (`body`):
708
+ * when fromResponse built the error, displayBody's form of the server's text,
709
+ * redacted with the values credentialsInHeader read from its request's
710
+ * Authorization header (within the scope on ApiHttpError), or withheld.
711
+ * Undefined for any other error (flair#2764).
712
+ */
713
+ export function apiErrorBody(err) {
714
+ return err instanceof ApiHttpError ? err.body : undefined;
715
+ }
716
+ /**
717
+ * The unredacted response text, for code that classifies a failure by the
718
+ * server's text (flair#2764). It may hold a credential the request sent:
719
+ * classifiers read it, and text displayed from it goes through boundErrorText,
720
+ * which redacts it within the scope on ApiHttpError or withholds it. For an
721
+ * ApiHttpError not built by fromResponse it is `body`; undefined for any other
722
+ * error.
723
+ */
724
+ export function apiErrorRawBody(err) {
725
+ if (!(err instanceof ApiHttpError))
726
+ return undefined;
727
+ return privateText.get(err)?.raw ?? err.body;
728
+ }
729
+ /**
730
+ * `text` (taken from apiErrorRawBody) as one bounded line for output, with
731
+ * the credential values credentialsInHeader read from `err`'s request header
732
+ * redacted from it (boundAndRedact, within the scope on ApiHttpError), or
733
+ * BODY_WITHHELD when credentialsInHeader set `withhold` for that header and
734
+ * the response text `err` was built from is non-empty, whatever `text` is
735
+ * (an empty `text` derived from it, such as an empty `error` string, included).
736
+ * When that response text is empty nothing is withheld. For an error that has
737
+ * no sent values, boundServerText(text) (flair#2764).
738
+ */
739
+ export function boundErrorText(err, text) {
740
+ const kept = err instanceof ApiHttpError ? privateText.get(err) : undefined;
741
+ if (kept?.withhold && kept.raw.length > 0)
742
+ return BODY_WITHHELD;
743
+ return boundAndRedact(text, kept?.sentValues ?? []);
744
+ }
745
+ /**
746
+ * With FLAIR_DEBUG set (any non-empty value), write the display form of a
747
+ * failed response's body to stderr as one JSON string (flair#2764). The path
748
+ * is shown by displayPath (percent-decoded, then redacted, or withheld) and
749
+ * the body by displayBody (a JSON body re-serialized, or withheld; any
750
+ * non-empty body withheld when `withhold` is set, an empty one shown as ""),
751
+ * each redacted within the scope on
752
+ * ApiHttpError; the labels, method, status and the JSON encoding of the body
753
+ * are written by this function and are not passed through redaction. In the
754
+ * JSON-encoded body, DEL, C1 control characters and the Unicode line and
755
+ * paragraph separators are escaped as well, so the line holds no
756
+ * CONTROL_CHARACTER but its final newline. `sendJsonRequest` calls it where it
757
+ * builds the error from the body. `env` and `write` are injectable for tests.
758
+ */
759
+ export function emitHttpErrorBodyDebug(method, path, status, body, sentValues = [], withhold = false, env = process.env, write = (s) => { process.stderr.write(s); }) {
760
+ if (!env.FLAIR_DEBUG)
761
+ return;
762
+ const shownBody = JSON.stringify(displayBody(body, sentValues, withhold)).replace(/[\u007F-\u009F\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
763
+ write(`[flair] ${method} ${displayPath(path, sentValues)} answered HTTP ${status}; response body: ${shownBody}\n`);
92
764
  }
93
765
  // ─── Admin-pass file handling ───────────────────────────────────────────────
94
766
  /**
@@ -131,6 +803,9 @@ export function readAdminPassFileSecure(path) {
131
803
  /** Thrown by `resolveAdminPassFromSources` when two credential sources are given at once. */
132
804
  export class AdminPassSourceError extends Error {
133
805
  }
806
+ export class AdminPassEmptyError extends Error {
807
+ name = "AdminPassEmptyError";
808
+ }
134
809
  /**
135
810
  * Resolve an admin password from the credential sources a command exposes, in
136
811
  * the precedence its usage text states: an explicit option — `--admin-pass-file`
@@ -144,20 +819,24 @@ export class AdminPassSourceError extends Error {
144
819
  * with a message naming the path and its mode.
145
820
  *
146
821
  * Returns "" when no source is set, so the caller owns its own "credential
147
- * required" message; throws `AdminPassSourceError` on a conflict, or
148
- * `readAdminPassFileSecure`'s error when the file is missing, empty or too
149
- * open. Neither message carries the password value.
822
+ * required" message.
150
823
  */
151
824
  export function resolveAdminPassFromSources(input) {
152
825
  const { adminPassFile, adminPass, envPass } = input;
153
- if (adminPassFile && adminPass) {
826
+ if (adminPassFile !== undefined && adminPass !== undefined) {
154
827
  throw new AdminPassSourceError("--admin-pass and --admin-pass-file cannot be combined; pass exactly one. " +
155
828
  "Prefer --admin-pass-file: it keeps the password out of shell history and the process list.");
156
829
  }
157
- if (adminPassFile)
830
+ if (adminPassFile !== undefined) {
831
+ if (adminPassFile === "")
832
+ throw new AdminPassEmptyError("--admin-pass-file must not be empty");
158
833
  return readAdminPassFileSecure(adminPassFile);
159
- if (adminPass)
834
+ }
835
+ if (adminPass !== undefined) {
836
+ if (adminPass === "")
837
+ throw new AdminPassEmptyError("--admin-pass must not be empty");
160
838
  return adminPass;
839
+ }
161
840
  return envPass ?? "";
162
841
  }
163
842
  export function defaultAdminPassPath() {
@@ -173,10 +852,71 @@ export function defaultAdminPassPath() {
173
852
  // these strings locally, flair#1873) and the shared credential-option helper
174
853
  // every sibling command uses.
175
854
  export const ADMIN_PASS_FILE_FLAG = "--admin-pass-file <path>";
176
- export const ADMIN_PASS_FILE_HELP = "Read the admin password from an owner-only file (mode 0600 enforced), keeping it out of shell history and the process list. " +
855
+ export const ADMIN_PASS_FILE_HELP = "Read the admin password from an owner-only file (group and world permission bits are refused; an owner-only mode such as 0600 or 0400 is accepted), keeping it out of shell history and the process list. " +
177
856
  "An explicit option (this or --admin-pass) overrides FLAIR_ADMIN_PASS; combining it with --admin-pass is a usage error.";
178
857
  export const ADMIN_PASS_FLAG = "--admin-pass <pass>";
179
858
  export const ADMIN_PASS_HELP = "Admin password (legacy: lands in shell history and the process list — prefer --admin-pass-file or FLAIR_ADMIN_PASS)";
859
+ /** Commands whose admin-password pair `addAdminPassOptions` wired. A test walks
860
+ * the registered tree and asserts every command that declares `--admin-pass`
861
+ * is in it, and every command that declares `--admin-pass-file` except
862
+ * `rem nightly enable`, which declares that flag itself as path-only. Inherited
863
+ * leaves are not in this set: `federation sync enable` stores the path in the
864
+ * unit it installs, and `sync status`/`disable` apply the pair in their own
865
+ * hooks. */
866
+ export const adminPassFileWired = new WeakSet();
867
+ /**
868
+ * Declare the admin-password pair on `cmd`: the argv form and the file form
869
+ * together, in that order, and apply it in a preAction hook. For a command that
870
+ * declares the pair, the hook runs after option parsing and before the action
871
+ * body, so a refused file exits before any request the action makes. A
872
+ * subcommand that inherits the pair from `cmd` stores the values on `cmd`; the
873
+ * leaves that apply them (`federation sync status`/`disable`) do so in their
874
+ * own hooks.
875
+ */
876
+ export function addAdminPassOptions(cmd, adminPassHelp = ADMIN_PASS_HELP, opts = {}) {
877
+ const adminPassFile = new Option(ADMIN_PASS_FILE_FLAG, opts.adminPassFileHelp ?? ADMIN_PASS_FILE_HELP);
878
+ cmd.option(ADMIN_PASS_FLAG, adminPassHelp).addOption(adminPassFile);
879
+ adminPassFileWired.add(cmd);
880
+ cmd.hook("preAction", (_thisCommand, actionCommand) => {
881
+ // A subcommand that inherits the pair (`federation sync status`) stores the
882
+ // values on this command, not on itself; the leaves that read an inherited
883
+ // pair apply it in their own hook. Reading only the leaf's opts() would ignore
884
+ // the inherited pair, leaving `status` able to send its request with the
885
+ // ambient admin password.
886
+ if (!actionCommand.options.some((o) => o.long === "--admin-pass-file"))
887
+ return;
888
+ const actionOpts = actionCommand.opts();
889
+ // Recorded before the file is applied: the warning keys on whether
890
+ // --admin-pass itself was given, not on the value that ends up in the slot.
891
+ actionOpts.inlineAdminPass =
892
+ actionCommand.getOptionValueSource("adminPass") === "cli" ? actionOpts.adminPass : undefined;
893
+ applyAdminPassFile(actionOpts, opts.onAdminPassRefusal
894
+ ? (err) => opts.onAdminPassRefusal(err, actionCommand)
895
+ : undefined);
896
+ });
897
+ return cmd;
898
+ }
899
+ /**
900
+ * Copy a nonempty explicit password into `opts.adminPass`; callers own environment fallback.
901
+ * Refuse combined options and missing, empty or group-/world-accessible files.
902
+ * Group/world permission refusals name the path and mode; missing and empty file errors name only the path.
903
+ */
904
+ export function applyAdminPassFile(opts, onRefusal) {
905
+ try {
906
+ const pass = resolveAdminPassFromSources({
907
+ adminPassFile: opts.adminPassFile,
908
+ adminPass: opts.adminPass,
909
+ });
910
+ if (pass)
911
+ opts.adminPass = pass;
912
+ }
913
+ catch (err) {
914
+ if (onRefusal)
915
+ onRefusal(err);
916
+ console.error(`Error: ${err.message}`);
917
+ process.exit(1);
918
+ }
919
+ }
180
920
  /** The admin username Harper's bootstrap creates and every Basic-auth path
181
921
  * historically hardcoded. Kept as the default; overridable per call via
182
922
  * `resolveAdminUser` (flair#1345). */
@@ -270,8 +1010,12 @@ export function resolveKeyPath(agentId) {
270
1010
  ].filter(Boolean);
271
1011
  return candidates.find((p) => existsSync(p)) ?? null;
272
1012
  }
273
- /** Build a TPS-Ed25519 auth header from a raw 32-byte seed on disk. */
274
- export function buildEd25519Auth(agentId, method, path, keyPath) {
1013
+ /**
1014
+ * Load a signing key from disk: read the file, decode it (raw 32-byte seed,
1015
+ * base64 seed, full PKCS8 DER or PEM), and require an Ed25519 key. A throw here
1016
+ * is a failure of THIS key file; nothing has been sent for it.
1017
+ */
1018
+ function loadEd25519SigningKey(keyPath) {
275
1019
  const raw = readFileSync(keyPath);
276
1020
  const pkcs8Header = Buffer.from("302e020100300506032b657004220420", "hex");
277
1021
  let privKey;
@@ -296,12 +1040,37 @@ export function buildEd25519Auth(agentId, method, path, keyPath) {
296
1040
  }
297
1041
  }
298
1042
  }
1043
+ if (privKey.asymmetricKeyType !== "ed25519") {
1044
+ throw new Error(`signing key ${keyPath} is not an Ed25519 private key`);
1045
+ }
1046
+ return privKey;
1047
+ }
1048
+ /** Build a TPS-Ed25519 auth header from an already-loaded Ed25519 key. */
1049
+ function buildEd25519AuthFromKey(agentId, method, path, privKey) {
299
1050
  const ts = Date.now().toString();
300
1051
  const nonce = randomUUID();
301
1052
  const payload = `${agentId}:${ts}:${nonce}:${method}:${path}`;
302
1053
  const sig = nodeCryptoSign(null, Buffer.from(payload), privKey).toString("base64");
303
1054
  return `TPS-Ed25519 ${agentId}:${ts}:${nonce}:${sig}`;
304
1055
  }
1056
+ /** Build a TPS-Ed25519 auth header from the key file at `keyPath`. */
1057
+ export function buildEd25519Auth(agentId, method, path, keyPath) {
1058
+ return buildEd25519AuthFromKey(agentId, method, path, loadEd25519SigningKey(keyPath));
1059
+ }
1060
+ /** Join a Flair route to an optional base path before signing or sending it. */
1061
+ export function requestUrl(baseUrl, path) {
1062
+ const base = new URL(baseUrl);
1063
+ if (base.search || base.hash || /[?#]$/.test(baseUrl)) {
1064
+ throw new Error("Flair base URL must not contain a query or fragment");
1065
+ }
1066
+ const route = new URL(path, base.origin);
1067
+ base.pathname = `${base.pathname.replace(/\/+$/, "")}${route.pathname}`;
1068
+ base.search = route.search;
1069
+ return base;
1070
+ }
1071
+ export function requestTarget(url) {
1072
+ return `${url.pathname}${url.search}`;
1073
+ }
305
1074
  /**
306
1075
  * Classify a throw from `buildEd25519Auth`.
307
1076
  *
@@ -378,12 +1147,25 @@ export function describeKeyLoadFailure(keyPath, kind, underlying) {
378
1147
  *
379
1148
  * Throws {@link KeyLoadError} if the key could not be loaded — a failure that
380
1149
  * provably happened BEFORE any byte hit the network, so no caller need guess
381
- * whether the instance is reachable. Anything else thrown here is transport.
1150
+ * whether the instance is reachable. A URL that cannot be built is refused
1151
+ * before signing or sending. `fetch` can fail before transport (for example,
1152
+ * request construction can reject an invalid header) or during transport;
1153
+ * failures are not classified here.
382
1154
  */
383
1155
  export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
1156
+ return (await authFetchWithSentCredentials(baseUrl, agentId, keyPath, method, path, body)).res;
1157
+ }
1158
+ /**
1159
+ * `authFetch`'s request, with the credentials it sent: a caller that renders a
1160
+ * non-ok response needs them to redact a body that echoes the Authorization
1161
+ * header (flair#2889). `sent` is `credentialsInHeader`'s reading of the header
1162
+ * this request sent.
1163
+ */
1164
+ export async function authFetchWithSentCredentials(baseUrl, agentId, keyPath, method, path, body) {
1165
+ const url = requestUrl(baseUrl, path);
384
1166
  let auth;
385
1167
  try {
386
- auth = buildEd25519Auth(agentId, method, path, keyPath);
1168
+ auth = buildEd25519Auth(agentId, method, requestTarget(url), keyPath);
387
1169
  }
388
1170
  catch (err) {
389
1171
  throw KeyLoadError.from(keyPath, err);
@@ -391,11 +1173,12 @@ export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
391
1173
  const headers = { Authorization: auth };
392
1174
  if (body !== undefined)
393
1175
  headers["Content-Type"] = "application/json";
394
- return fetch(`${baseUrl}${path}`, {
1176
+ const res = await fetch(url.href, {
395
1177
  method,
396
1178
  headers,
397
1179
  body: body !== undefined ? JSON.stringify(body) : undefined,
398
1180
  });
1181
+ return { res, sent: credentialsInHeader(auth) };
399
1182
  }
400
1183
  export function isLocalBase(base) {
401
1184
  try {
@@ -406,7 +1189,19 @@ export function isLocalBase(base) {
406
1189
  return !base;
407
1190
  }
408
1191
  }
409
- // ─── HTTP + response handling ───────────────────────────────────────────────
1192
+ function noCredentialsHint(isLocal, signedOnly) {
1193
+ if (signedOnly) {
1194
+ // No admin password leaves a signedOnly request, so only an agent key helps.
1195
+ const remedy = signedOnly.agentId
1196
+ ? `Provide the key of agent '${signedOnly.agentId}' at ${join(defaultKeysDir(), `${signedOnly.agentId}.key`)} ` +
1197
+ `(or set FLAIR_KEY_DIR to a directory containing ${signedOnly.agentId}.key).`
1198
+ : `Provide the key of an agent registered on the target instance at ${join(signedOnly.keysDir, "<agent-id>.key")}.`;
1199
+ return `This request can send only an Ed25519 agent signature; the admin password is not sent on this path. ${remedy}`;
1200
+ }
1201
+ return isLocal
1202
+ ? "Set FLAIR_ADMIN_PASS, or run `flair init` to provision ~/.flair/admin-pass or an agent key."
1203
+ : "Set FLAIR_ADMIN_PASS (remote targets have no local admin-pass fallback).";
1204
+ }
410
1205
  /**
411
1206
  * Perform the actual Flair REST call with an already-resolved Authorization
412
1207
  * header (or none) and classify the response. Shared by the primary
@@ -414,47 +1209,203 @@ export function isLocalBase(base) {
414
1209
  * agree on 204/empty-body handling, JSON parsing, and the no-credentials
415
1210
  * 403 hint text.
416
1211
  */
417
- export async function sendJsonRequest(baseUrl, method, path, body, authHeader, isLocal) {
418
- const res = await fetch(`${baseUrl}${path}`, {
419
- method,
420
- headers: {
421
- "content-type": "application/json",
422
- ...(authHeader ? { authorization: authHeader } : {}),
423
- },
424
- body: body ? JSON.stringify(body) : undefined,
425
- });
426
- // Handle 204 No Content (e.g., PUT upsert returns empty body)
427
- if (res.status === 204 || res.headers.get("content-length") === "0") {
428
- if (!res.ok)
429
- throw new ApiHttpError(res.status, `HTTP ${res.status}`);
430
- return { ok: true };
431
- }
432
- const text = await res.text();
433
- if (!res.ok) {
1212
+ export async function sendJsonRequest(url, method, body, authHeader, isLocal, transport = {}) {
1213
+ // The deadline covers the request AND the response body read: a server that
1214
+ // sends headers and then stalls the body is bounded too. Resolved before the
1215
+ // request, so an invalid FLAIR_REQUEST_TIMEOUT_MS sends nothing for a request
1216
+ // that resolves that variable (one with no explicit deadline).
1217
+ const deadlineSource = transport.deadlineSource ?? (transport.deadlineMs === undefined ? "env" : "explicit");
1218
+ const deadlineMs = resolveRequestDeadlineMs(transport.deadlineMs);
1219
+ const readOnly = method.toUpperCase() === "GET" || method.toUpperCase() === "HEAD";
1220
+ // Serialize before the transport call: a body that cannot be serialized was
1221
+ // never sent, so it is a serialization failure, not a delivery failure.
1222
+ // Every supplied body is checked (a falsy one such as 0n can still fail to
1223
+ // serialize); a falsy body that does serialize is still omitted, as before.
1224
+ let serializedBody;
1225
+ if (body !== undefined) {
1226
+ try {
1227
+ const serialized = JSON.stringify(body);
1228
+ if (serialized === undefined)
1229
+ throw new Error("JSON.stringify returned undefined");
1230
+ if (body)
1231
+ serializedBody = serialized;
1232
+ }
1233
+ catch (err) {
1234
+ const reason = err instanceof Error ? err.message : String(err);
1235
+ throw new Error(`${method} ${url.pathname} was not sent: the request body could not be serialized to JSON (${reason}).`);
1236
+ }
1237
+ }
1238
+ const controller = new AbortController();
1239
+ let timedOut = false;
1240
+ const timer = setTimeout(() => {
1241
+ timedOut = true;
1242
+ controller.abort();
1243
+ }, deadlineMs);
1244
+ let res;
1245
+ let fetchRejected = false;
1246
+ let bodyReadFailed = false;
1247
+ const readBody = async () => {
1248
+ try {
1249
+ return await res.text();
1250
+ }
1251
+ catch (err) {
1252
+ bodyReadFailed = true;
1253
+ throw err;
1254
+ }
1255
+ };
1256
+ try {
1257
+ try {
1258
+ res = await fetch(url.href, {
1259
+ method,
1260
+ headers: {
1261
+ "content-type": "application/json",
1262
+ ...(authHeader ? { authorization: authHeader } : {}),
1263
+ },
1264
+ body: serializedBody,
1265
+ signal: controller.signal,
1266
+ // "manual" hands back the 3xx itself, so the refusal can name its status;
1267
+ // the location it names is never requested.
1268
+ ...(transport.refuseRedirects ? { redirect: "manual" } : {}),
1269
+ });
1270
+ }
1271
+ catch (err) {
1272
+ fetchRejected = true;
1273
+ throw err;
1274
+ }
1275
+ if (transport.refuseRedirects && res.status >= 300 && res.status < 400) {
1276
+ throw new ApiHttpError(res.status, `HTTP ${res.status}: the instance answered with a redirect, which this request does not follow`);
1277
+ }
434
1278
  // 403 with no credentials sent at all is the flair#634 case: a gated
435
1279
  // resource rejected a credential-less call. Name the fix instead of
436
- // surfacing the raw "forbidden" body — never a stack trace.
1280
+ // surfacing the raw "forbidden" body — never a stack trace. Classified
1281
+ // before the empty-body shortcut below, so a zero-length 403 gets the same
1282
+ // hint and noCredentials as one with a body (flair#2749).
437
1283
  if (res.status === 403 && !authHeader) {
438
- const hint = isLocal
439
- ? "Set FLAIR_ADMIN_PASS, or run `flair init` to provision ~/.flair/admin-pass or an agent key."
440
- : "Set FLAIR_ADMIN_PASS (remote targets have no local admin-pass fallback).";
1284
+ await readBody();
1285
+ const hint = noCredentialsHint(isLocal, transport.signedOnly);
441
1286
  throw new ApiHttpError(403, `HTTP 403: no credentials sent. ${hint}`, /* noCredentials */ true);
442
1287
  }
443
- throw new ApiHttpError(res.status, text || `HTTP ${res.status}`);
1288
+ // Handle 204 No Content (e.g., PUT upsert returns empty body)
1289
+ if (res.status === 204 || res.headers.get("content-length") === "0") {
1290
+ if (!res.ok)
1291
+ throw ApiHttpError.fromResponse(res.status, "");
1292
+ return { ok: true };
1293
+ }
1294
+ const text = await readBody();
1295
+ if (!res.ok) {
1296
+ // The FLAIR_DEBUG line's path and body, the message's reason and `body`
1297
+ // are redacted with the credential values credentialsInHeader reads from
1298
+ // this request's Authorization header, within the scope on ApiHttpError,
1299
+ // and the server's text is withheld when it sets `withhold`; classifiers
1300
+ // read the unredacted text through apiErrorRawBody.
1301
+ const sent = credentialsInHeader(authHeader);
1302
+ emitHttpErrorBodyDebug(method, url.pathname, res.status, text, sent.values, sent.withhold || transport.withholdResponseBodyDebug === true);
1303
+ throw ApiHttpError.fromResponse(res.status, text, sent.values, sent.withhold);
1304
+ }
1305
+ if (!text)
1306
+ return { ok: true };
1307
+ try {
1308
+ return JSON.parse(text);
1309
+ }
1310
+ catch (err) {
1311
+ if (transport.tolerateUnparsedSuccessBody)
1312
+ return { ok: true };
1313
+ throw err;
1314
+ }
1315
+ }
1316
+ catch (err) {
1317
+ // A fired deadline is reported by the deadline, not by the abort error
1318
+ // fetch raised: a non-GET/HEAD request may have committed, so it is an
1319
+ // unknown outcome, and a GET or HEAD is a plain timeout.
1320
+ if (timedOut) {
1321
+ const status = res?.status;
1322
+ if (readOnly)
1323
+ throw new ApiRequestTimeout(method, url.pathname, deadlineMs, status, deadlineSource);
1324
+ throw new ApiRequestOutcomeUnknown(method, url.pathname, deadlineMs, status, deadlineSource);
1325
+ }
1326
+ // A connect-phase code identifies failure of the current connection attempt;
1327
+ // it proves unsent delivery only if no earlier redirect was followed.
1328
+ if (fetchRejected && !readOnly && !isConnectPhaseFailure(err)) {
1329
+ throw ApiRequestOutcomeUnknown.fromTransportFailure(method, url.pathname, url.origin, err);
1330
+ }
1331
+ // The status line arrived but the body could not be read. A write's 2xx
1332
+ // response leaves the outcome unknown, and the message names the status
1333
+ // received; a non-2xx status is reported by that status.
1334
+ if (bodyReadFailed && res !== undefined && !readOnly) {
1335
+ if (res.ok)
1336
+ throw ApiRequestOutcomeUnknown.fromTransportFailure(method, url.pathname, url.origin, err, res.status);
1337
+ throw ApiHttpError.fromResponse(res.status, "");
1338
+ }
1339
+ throw err;
1340
+ }
1341
+ finally {
1342
+ clearTimeout(timer);
1343
+ }
1344
+ }
1345
+ /**
1346
+ * The 401 error codes the Ed25519 authentication middleware in
1347
+ * resources/auth-middleware.ts returns when it refuses the credential: an
1348
+ * unparseable header, a timestamp outside the replay window, an unknown agent,
1349
+ * a deactivated principal, or a signature that does not verify. The
1350
+ * middleware's catch around signature verification also covers key import
1351
+ * errors.
1352
+ * A 401 carrying one of these codes moves the tier-5 floor to the next key.
1353
+ * `nonce_replay_detected` is an answer about the REQUEST (a reused nonce) and
1354
+ * `replay_store_unavailable` is a server-side failure; neither is a credential
1355
+ * rejection, so both are final.
1356
+ */
1357
+ export const CREDENTIAL_REJECTION_CODES = new Set([
1358
+ "invalid_authorization_header",
1359
+ "timestamp_out_of_window",
1360
+ "unknown_agent",
1361
+ "principal_deactivated",
1362
+ "invalid_signature",
1363
+ "signature_verification_failed",
1364
+ ]);
1365
+ /** True when the server answered 401 with one of its Ed25519 credential-rejection codes. */
1366
+ function isEd25519CredentialRejection(err) {
1367
+ if (!(err instanceof ApiHttpError) || err.status !== 401)
1368
+ return false;
1369
+ const raw = apiErrorRawBody(err);
1370
+ if (raw === undefined)
1371
+ return false;
1372
+ try {
1373
+ const parsed = JSON.parse(raw);
1374
+ const code = parsed && typeof parsed === "object" ? parsed.error : undefined;
1375
+ return typeof code === "string" && CREDENTIAL_REJECTION_CODES.has(code);
1376
+ }
1377
+ catch {
1378
+ return false;
444
1379
  }
445
- if (!text)
446
- return { ok: true };
447
- return JSON.parse(text);
448
1380
  }
449
1381
  /**
450
1382
  * Tier 5, the floor (flair#747, generalizing flair#742's `verifyAuthedGet`
451
- * GET-only fallback to any method/body): try every registered key in
452
- * `keysDir` in sorted (deterministic) filename order, first one that
453
- * authenticates wins. Returns `undefined` — never throws — when every key
454
- * fails or none exist, so the caller can rethrow its ORIGINAL
455
- * no-credentials error rather than a floor-specific one.
1383
+ * GET-only fallback to any method/body): tries candidate key files in
1384
+ * `keysDir` in sorted (deterministic) filename order until one authenticates
1385
+ * or an answer is final. Returns `undefined` when there are no candidate key
1386
+ * files, or when no candidate authenticated: every attempt was skipped for a
1387
+ * key file that cannot be read or decoded as an Ed25519 key, credential-rejected,
1388
+ * or a connect failure; a final answer throws. That lets the caller rethrow its
1389
+ * ORIGINAL no-credentials error rather than a floor-specific one.
1390
+ *
1391
+ * Every request the floor sends refuses redirects (flair#2955), whatever the
1392
+ * caller asked for: the location a 3xx names receives no request, and the 3xx
1393
+ * is thrown as itself — a final answer, never a reason to try another key.
1394
+ *
1395
+ * The floor moves to the next key ONLY when the server refused the Ed25519
1396
+ * credential itself (the 401 codes in `CREDENTIAL_REJECTION_CODES`), when an
1397
+ * attempt that does not follow redirects fails in the connect phase (the
1398
+ * existing network-blip case), or when that candidate's key file cannot be read
1399
+ * or decoded as an Ed25519 key (nothing was sent for it). Failures after a key
1400
+ * is loaded (nonce, signing) are final. Every other response is final too: a
1401
+ * failed HTTP response whose body was read is thrown as itself with its status
1402
+ * and any error code its body names, and a refused redirect is thrown as itself
1403
+ * with its status before any body is read. When
1404
+ * every candidate is refused as a credential, the floor returns `undefined`, so
1405
+ * the caller rethrows its original no-credentials hint, which carries the
1406
+ * operator's remedy.
456
1407
  */
457
- export async function tryAgentKeyFloor(baseUrl, method, path, body, keysDir) {
1408
+ export async function tryAgentKeyFloor(url, method, body, keysDir, transport = {}) {
458
1409
  let keyFiles = [];
459
1410
  try {
460
1411
  keyFiles = readdirSync(keysDir).filter((f) => f.endsWith(".key")).sort();
@@ -462,19 +1413,52 @@ export async function tryAgentKeyFloor(baseUrl, method, path, body, keysDir) {
462
1413
  catch {
463
1414
  // No keys dir at all — nothing to fall back to.
464
1415
  }
465
- const isLocal = isLocalBase(baseUrl);
1416
+ const isLocal = isLocalBase(url.origin);
1417
+ // The signed target is identical for every candidate, so build it once,
1418
+ // before any key is loaded. A failure here is about the request itself, not
1419
+ // about any one candidate, so it is final.
1420
+ const target = requestTarget(url);
466
1421
  for (const kf of keyFiles) {
467
1422
  const agentId = kf.replace(/\.key$/, "");
468
1423
  const keyPath = join(keysDir, kf);
1424
+ let privKey;
469
1425
  try {
470
- const authHeader = buildEd25519Auth(agentId, method, path, keyPath);
471
- return await sendJsonRequest(baseUrl, method, path, body, authHeader, isLocal);
1426
+ privKey = loadEd25519SigningKey(keyPath);
472
1427
  }
473
1428
  catch {
474
- // This key didn't work (unregistered, bad signature, network blip on
475
- // this one attempt) — try the next one.
1429
+ // This candidate's key file could not be loaded as an Ed25519 key.
1430
+ // Nothing was sent for it, and every other candidate is exactly as
1431
+ // usable as it was before this file was read, so skip this one.
1432
+ continue;
1433
+ }
1434
+ // The key loaded: a failure from here (nonce, signing) is not about this
1435
+ // key file and is thrown as itself, with no later key sent.
1436
+ const authHeader = buildEd25519AuthFromKey(agentId, method, target, privKey);
1437
+ try {
1438
+ return await sendJsonRequest(url, method, body, authHeader, isLocal, { ...transport, refuseRedirects: true });
1439
+ }
1440
+ catch (err) {
1441
+ // A write whose outcome is unknown stops the floor. Trying the next key
1442
+ // would send the same write again — a blind replay of a request that may
1443
+ // have committed.
1444
+ if (err instanceof ApiRequestOutcomeUnknown)
1445
+ throw err;
1446
+ // The server rejected THIS credential (unregistered agent, bad
1447
+ // signature, expired timestamp, deactivated principal): another key may
1448
+ // authenticate.
1449
+ if (isEd25519CredentialRejection(err))
1450
+ continue;
1451
+ // A connect-phase failure on an attempt that refuses redirects is the
1452
+ // existing network-blip case: another key may connect.
1453
+ if (isConnectPhaseFailure(err))
1454
+ continue;
1455
+ // A server answer is final — resending it as a different agent would hide
1456
+ // what the server said. Local request failures are rethrown as they are.
1457
+ throw err;
476
1458
  }
477
1459
  }
1460
+ // No key authenticated. Returning `undefined` lets the caller rethrow its
1461
+ // original no-credentials hint, which carries the operator's remedy.
478
1462
  return undefined;
479
1463
  }
480
1464
  /**
@@ -515,6 +1499,8 @@ export function emitIdentityOverrideNotice(message, write = (s) => { process.std
515
1499
  export function resetIdentityOverrideNotices() {
516
1500
  emittedIdentityOverrides.clear();
517
1501
  }
1502
+ /** The Authorization scheme of an Ed25519 agent signature (buildEd25519Auth). */
1503
+ const ED25519_SCHEME = "TPS-Ed25519 ";
518
1504
  /**
519
1505
  * The shared resolver: given a Flair REST call and whatever credential
520
1506
  * material the caller already knows about, resolve auth across all 5 tiers
@@ -522,6 +1508,8 @@ export function resetIdentityOverrideNotices() {
522
1508
  * any non-2xx response (after the tier-5 floor has also been exhausted).
523
1509
  */
524
1510
  export async function authedRequest(method, path, body, opts) {
1511
+ const url = requestUrl(opts.baseUrl, path);
1512
+ const signedPath = requestTarget(url);
525
1513
  const isLocal = opts.isLocal ?? isLocalBase(opts.baseUrl);
526
1514
  const keysDir = opts.keysDir ?? defaultKeysDir();
527
1515
  // One username for every Basic tier: flag > FLAIR_ADMIN_USER env > "admin"
@@ -531,6 +1519,10 @@ export async function authedRequest(method, path, body, opts) {
531
1519
  // Which tier supplied authHeader — drives the never-silent override notice
532
1520
  // below (see describeIdentityOverride).
533
1521
  let credSource;
1522
+ if (opts.signedOnly && opts.explicitAdminPass) {
1523
+ throw new Error("refusing to send an admin password to a target that may receive only an Ed25519 signature or no Authorization header " +
1524
+ "(its instance is not proven); pass --agent <a registered agent id> instead");
1525
+ }
534
1526
  // Tier 1: explicit — caller-resolved flag material always wins.
535
1527
  if (opts.explicitAdminPass) {
536
1528
  authHeader = `Basic ${Buffer.from(`${adminUser}:${opts.explicitAdminPass}`).toString("base64")}`;
@@ -538,7 +1530,7 @@ export async function authedRequest(method, path, body, opts) {
538
1530
  }
539
1531
  else if (opts.explicitKeyPath && opts.agentId) {
540
1532
  try {
541
- authHeader = buildEd25519Auth(opts.agentId, method, path, opts.explicitKeyPath);
1533
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, opts.explicitKeyPath);
542
1534
  credSource = "explicit-key";
543
1535
  }
544
1536
  catch (err) {
@@ -559,11 +1551,12 @@ export async function authedRequest(method, path, body, opts) {
559
1551
  `to a directory containing it). Refusing to fall back to FLAIR_ADMIN_PASS ` +
560
1552
  `or the local admin-pass file.`);
561
1553
  }
562
- authHeader = buildEd25519Auth(opts.agentId, method, path, keyPath);
1554
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, keyPath);
563
1555
  credSource = "flag-agent";
564
1556
  }
565
1557
  // Tier 2: env — FLAIR_TOKEN (Bearer), else FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD (Basic).
566
- if (!authHeader) {
1558
+ // Skipped when only a signature may be sent.
1559
+ if (!authHeader && !opts.signedOnly) {
567
1560
  if (process.env.FLAIR_TOKEN) {
568
1561
  authHeader = `Bearer ${process.env.FLAIR_TOKEN}`;
569
1562
  credSource = "env-token";
@@ -581,7 +1574,7 @@ export async function authedRequest(method, path, body, opts) {
581
1574
  const keyPath = resolveKeyPath(opts.agentId);
582
1575
  if (keyPath) {
583
1576
  try {
584
- authHeader = buildEd25519Auth(opts.agentId, method, path, keyPath);
1577
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, keyPath);
585
1578
  credSource = "pinned-agent";
586
1579
  }
587
1580
  catch (err) {
@@ -591,7 +1584,8 @@ export async function authedRequest(method, path, body, opts) {
591
1584
  }
592
1585
  }
593
1586
  // Tier 4: LOCAL TARGETS ONLY — the secure ~/.flair/admin-pass file.
594
- if (!authHeader) {
1587
+ // Skipped when only a signature may be sent.
1588
+ if (!authHeader && !opts.signedOnly) {
595
1589
  try {
596
1590
  const filePass = resolveLocalAdminPass(undefined, !isLocal);
597
1591
  if (filePass) {
@@ -621,15 +1615,30 @@ export async function authedRequest(method, path, body, opts) {
621
1615
  if (notice)
622
1616
  emitIdentityOverrideNotice(notice);
623
1617
  }
1618
+ // The last word for signedOnly: whatever resolved above, nothing but an
1619
+ // agent signature leaves (flair#2526).
1620
+ if (opts.signedOnly && authHeader !== undefined && !authHeader.startsWith(ED25519_SCHEME)) {
1621
+ throw new Error("refusing to send a Basic or Bearer credential to a target that may receive only an Ed25519 signature or no Authorization header");
1622
+ }
624
1623
  try {
625
- return await sendJsonRequest(opts.baseUrl, method, path, body, authHeader, isLocal);
1624
+ return await sendJsonRequest(url, method, body, authHeader, isLocal, {
1625
+ refuseRedirects: opts.refuseRedirects,
1626
+ deadlineMs: opts.deadlineMs,
1627
+ deadlineSource: opts.deadlineSource,
1628
+ tolerateUnparsedSuccessBody: opts.tolerateUnparsedSuccessBody,
1629
+ ...(opts.signedOnly ? { signedOnly: { agentId: opts.agentId, keysDir } } : {}),
1630
+ });
626
1631
  }
627
1632
  catch (err) {
628
1633
  // Tier 5 — the floor. Only engages when NOTHING above resolved to
629
1634
  // anything sendable (see module header for why a rejected credential
630
1635
  // does not retry here).
631
1636
  if (err instanceof ApiHttpError && err.noCredentials) {
632
- const floorResult = await tryAgentKeyFloor(opts.baseUrl, method, path, body, keysDir);
1637
+ const floorResult = await tryAgentKeyFloor(url, method, body, keysDir, {
1638
+ deadlineMs: opts.deadlineMs,
1639
+ deadlineSource: opts.deadlineSource,
1640
+ tolerateUnparsedSuccessBody: opts.tolerateUnparsedSuccessBody,
1641
+ });
633
1642
  if (floorResult !== undefined)
634
1643
  return floorResult;
635
1644
  }