@tpsdev-ai/flair 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. 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
  *
@@ -63,9 +63,14 @@
63
63
  * conflict (`--admin-pass` + `--agent`) is never quiet either.
64
64
  */
65
65
  import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
66
- import { join } from "node:path";
66
+ import { basename, 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 { agentKeyLocations, agentKeyPath, defaultKeysDir, keyPathIn } from "./key-dir.js";
71
+ import { isConnectPhaseFailure } from "./connect-phase.js";
72
+ export { isConnectPhaseFailure, REFUSED_CODES } from "./connect-phase.js";
73
+ export { defaultKeysDir };
69
74
  // ─── Failure classification ─────────────────────────────────────────────────
70
75
  /**
71
76
  * Thrown by `sendJsonRequest` for an HTTP-level failure (as opposed to a
@@ -79,16 +84,685 @@ import { resolveHome } from "./home.js";
79
84
  * case — distinguishes "we had nothing to send" from "we sent
80
85
  * something and it was rejected", which is exactly the signal
81
86
  * `authedRequest` uses to decide whether tier 5 (the floor) applies.
87
+ * - `body` (flair#2764): the display form of the response body, set by
88
+ * `fromResponse` (`displayBody`), with the credential values
89
+ * `credentialsInHeader` read from the request's Authorization header: a
90
+ * JSON body re-serialized with every string in it redacted after decoding,
91
+ * or withheld when it cannot be; any other body redacted as text; and any
92
+ * non-empty body withheld when that header names basic, bearer or
93
+ * tps-ed25519 but its credential could not be read (an empty body stays
94
+ * empty, and the message is then the status alone). The message's reason is decided
95
+ * separately (`describeHttpFailure`), from the unredacted text:
96
+ * BODY_WITHHELD for any non-empty body when the header's credential could
97
+ * not be read; otherwise the JSON body's named error, redacted, even when
98
+ * `body` is withheld; otherwise an excerpt of the text, redacted, or
99
+ * BODY_WITHHELD when displayBody withholds the body. Its `HTTP <status>`
100
+ * prefix is not passed through redaction. Classifiers read the unredacted
101
+ * text through `apiErrorRawBody`; the rem formatters that derive display
102
+ * text from it pass that text through `boundErrorText`, which redacts it,
103
+ * or withholds it when the header's credential could not be read and the
104
+ * response text was non-empty (even when the text derived from it is
105
+ * empty). Within
106
+ * the scope below, each of those values becomes `[redacted]` in the
107
+ * server's text as displayed.
108
+ * Scope: redaction removes the request's credential values from the text the
109
+ * server supplied (literal, inside any JSON string, percent-encoded); text the
110
+ * CLI writes itself (the `HTTP <status>: ` prefix, the debug line's labels, a
111
+ * caller's `Error: ` prefix) is never altered, so a credential that matches the
112
+ * CLI's own wording, or matches only once that wording is joined to the
113
+ * server's text, is not covered.
82
114
  */
83
115
  export class ApiHttpError extends Error {
84
116
  status;
85
117
  noCredentials;
86
- constructor(status, message, noCredentials = false) {
118
+ body;
119
+ constructor(status, message, noCredentials = false, body) {
87
120
  super(message);
88
121
  this.name = "ApiHttpError";
89
122
  this.status = status;
90
123
  this.noCredentials = noCredentials;
124
+ this.body = body;
91
125
  }
126
+ /**
127
+ * The error for a non-2xx response whose body text is `body` (flair#2764).
128
+ * `sentValues` are the credential values `credentialsInHeader` read from the
129
+ * request's Authorization header: the message and `body` are redacted with them
130
+ * (within the scope on ApiHttpError). `withhold` is credentialsInHeader's
131
+ * flag: when set, the server's non-empty text is shown as BODY_WITHHELD in the message
132
+ * and `body`. The unredacted text, the values and the flag are kept in a
133
+ * module-private map for apiErrorRawBody and boundErrorText.
134
+ */
135
+ static fromResponse(status, body, sentValues = [], withhold = false) {
136
+ const err = new ApiHttpError(status, describeHttpFailure(status, body, sentValues, withhold), false, displayBody(body, sentValues, withhold));
137
+ privateText.set(err, { raw: body, sentValues: [...sentValues], withhold });
138
+ return err;
139
+ }
140
+ }
141
+ /**
142
+ * The whole-request deadline `sendJsonRequest` enforces when
143
+ * `FLAIR_REQUEST_TIMEOUT_MS` is unset and the caller passes no deadline. Five
144
+ * minutes is above the figures the repo's responsiveness fixture reports for
145
+ * the CLI: a dedup pass at 23.07 s over 403 live vectors, and a
146
+ * 3,065-row repro that exceeded a 60 s client deadline
147
+ * (test/bench/rem-responsiveness.md); the repro's own duration was not
148
+ * measured. A single memory write's server-side embedding provider bound is
149
+ * 20 s (resources/memory-write-lock.ts).
150
+ */
151
+ export const DEFAULT_REQUEST_DEADLINE_MS = 300_000;
152
+ /** The env var that overrides {@link DEFAULT_REQUEST_DEADLINE_MS}. */
153
+ export const REQUEST_DEADLINE_ENV = "FLAIR_REQUEST_TIMEOUT_MS";
154
+ /** Bounds of {@link REQUEST_DEADLINE_ENV}: an integer from 1 ms to one hour. */
155
+ export const REQUEST_DEADLINE_MIN_MS = 1;
156
+ export const REQUEST_DEADLINE_MAX_MS = 3_600_000;
157
+ /** The env var that overrides {@link DEFAULT_REM_REQUEST_DEADLINE_MS}. */
158
+ export const REM_REQUEST_DEADLINE_ENV = "FLAIR_REM_REQUEST_TIMEOUT_MS";
159
+ /**
160
+ * The single whole-request deadline for the REM work routes: POST
161
+ * /MemoryMaintenance, POST /ReflectMemories, POST /MemoryDedupStats and POST
162
+ * /AutoPromoteCandidates. The sizing basis is the dedup sweep: the repo
163
+ * fixture's 23.07 s over 403 live vectors is ~57 ms/memory, and the route
164
+ * scans every Memory row before it selects the capped ANN set of up to 20,000
165
+ * (DEDUP_CLUSTER_MAX_MEMORIES_DEFAULT), so 20,000 x ~57 ms = ~1,140 s and this
166
+ * deadline sits above it. It is a sizing estimate, not a throughput claim, and
167
+ * is within {@link REQUEST_DEADLINE_MAX_MS}. {@link REM_REQUEST_DEADLINE_ENV}
168
+ * overrides it; every other request through the shared REST sender that passes
169
+ * no explicit deadline resolves FLAIR_REQUEST_TIMEOUT_MS, else the shared
170
+ * default.
171
+ */
172
+ export const DEFAULT_REM_REQUEST_DEADLINE_MS = 1_800_000;
173
+ /**
174
+ * One deadline value from `raw`: undefined when the variable is unset, empty or
175
+ * whitespace-only; the number when it is an integer in range; a refusal naming
176
+ * `name` otherwise.
177
+ */
178
+ function parseDeadlineEnv(name, raw) {
179
+ if (raw === undefined || raw.trim() === "")
180
+ return undefined;
181
+ const value = Number(raw);
182
+ if (!Number.isSafeInteger(value) || value < REQUEST_DEADLINE_MIN_MS || value > REQUEST_DEADLINE_MAX_MS) {
183
+ throw new Error(`${name} must be an integer from ${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS} (milliseconds)`);
184
+ }
185
+ return value;
186
+ }
187
+ /**
188
+ * The whole-request deadline in force: `explicit` when given, else the env
189
+ * override, else the default. An explicit deadline is validated and returned
190
+ * before `FLAIR_REQUEST_TIMEOUT_MS` is read, so an invalid value of that
191
+ * variable refuses only the requests it governs — those with no explicit
192
+ * deadline. An out-of-range or non-integer env value is refused here, before
193
+ * any request is sent, naming the variable and the range; it is never
194
+ * silently defaulted. An empty or whitespace-only value is unset.
195
+ */
196
+ export function resolveRequestDeadlineMs(explicit = undefined, env = process.env) {
197
+ if (explicit !== undefined) {
198
+ if (!Number.isSafeInteger(explicit) || explicit < REQUEST_DEADLINE_MIN_MS || explicit > REQUEST_DEADLINE_MAX_MS) {
199
+ throw new Error(`request deadline must be an integer from ${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS} (milliseconds)`);
200
+ }
201
+ return explicit;
202
+ }
203
+ return parseDeadlineEnv(REQUEST_DEADLINE_ENV, env[REQUEST_DEADLINE_ENV]) ?? DEFAULT_REQUEST_DEADLINE_MS;
204
+ }
205
+ /**
206
+ * The REM work deadline in force: {@link REM_REQUEST_DEADLINE_ENV} when set,
207
+ * else {@link DEFAULT_REM_REQUEST_DEADLINE_MS}. An out-of-range or non-integer
208
+ * value is refused here, before the REM work request is sent, naming the
209
+ * variable and the range; an empty or whitespace-only value is unset.
210
+ */
211
+ export function resolveRemRequestDeadlineMs(env = process.env) {
212
+ return parseDeadlineEnv(REM_REQUEST_DEADLINE_ENV, env[REM_REQUEST_DEADLINE_ENV]) ?? DEFAULT_REM_REQUEST_DEADLINE_MS;
213
+ }
214
+ /** The `HTTP <status>` clause for a deadline that fired after a status line. */
215
+ function deadlineStatusClause(status) {
216
+ return status === undefined ? "" : `; the instance answered HTTP ${status} but its response body did not complete`;
217
+ }
218
+ /** The variable, if any, that governs a deadline from `source`. */
219
+ function deadlineEnvName(source) {
220
+ if (source === "env")
221
+ return REQUEST_DEADLINE_ENV;
222
+ if (source === "rem")
223
+ return REM_REQUEST_DEADLINE_ENV;
224
+ return undefined;
225
+ }
226
+ /** The remedy named in an expiry message for a deadline from `source`. */
227
+ function deadlineRemedy(source) {
228
+ const envName = deadlineEnvName(source);
229
+ if (envName === undefined) {
230
+ return `This command sets its own deadline; raise it there if this request legitimately runs longer.`;
231
+ }
232
+ return `Raise ${envName} (${REQUEST_DEADLINE_MIN_MS} to ${REQUEST_DEADLINE_MAX_MS}) if this request legitimately runs longer.`;
233
+ }
234
+ /**
235
+ * Thrown when a GET or HEAD crosses the whole-request deadline. The split is by
236
+ * method, not by effect: GET and HEAD that reach the deadline throw this type,
237
+ * and every other method throws {@link ApiRequestOutcomeUnknown}. A GET is not
238
+ * proof of no effect — `GET /FederationInstance` creates the identity row on
239
+ * first boot — so this type reports only that no complete response arrived.
240
+ */
241
+ export class ApiRequestTimeout extends Error {
242
+ method;
243
+ path;
244
+ deadlineMs;
245
+ /** The status line that arrived before the deadline fired, when one did. */
246
+ status;
247
+ constructor(method, path, deadlineMs, status, source) {
248
+ const envName = deadlineEnvName(source);
249
+ super(`${method} ${path} did not complete within ${deadlineMs} ms` +
250
+ (envName === undefined ? "" : ` (${envName})`) +
251
+ deadlineStatusClause(status));
252
+ this.name = "ApiRequestTimeout";
253
+ this.method = method;
254
+ this.path = path;
255
+ this.deadlineMs = deadlineMs;
256
+ this.status = status;
257
+ }
258
+ }
259
+ /**
260
+ * Thrown for a write's deadline expiry, non-connect-phase fetch failure, or
261
+ * failed 2xx body read. No caller may retry the write blindly.
262
+ */
263
+ export class ApiRequestOutcomeUnknown extends Error {
264
+ method;
265
+ path;
266
+ /** The deadline that expired, or undefined for a transport failure. */
267
+ deadlineMs;
268
+ /** The status line that arrived before the deadline expired or the response read failed, when one did. */
269
+ status;
270
+ constructor(method, path, deadlineMs, status, source, detail) {
271
+ const envName = deadlineEnvName(source);
272
+ super(detail ??
273
+ `${method} ${path} may or may not have taken effect: no complete response within ${deadlineMs} ms` +
274
+ (envName === undefined ? "" : ` (${envName})`) +
275
+ `${deadlineStatusClause(status)}. Expiry does not show whether the request was delivered or took effect; do not retry it blindly. ${deadlineRemedy(source)}`);
276
+ this.name = "ApiRequestOutcomeUnknown";
277
+ this.method = method;
278
+ this.path = path;
279
+ this.deadlineMs = deadlineMs;
280
+ this.status = status;
281
+ }
282
+ /** Name the requested origin and warn against retrying. */
283
+ static fromTransportFailure(method, path, url, cause, status) {
284
+ const detail = status === undefined
285
+ ? `${method} ${path} to ${url}: no final response; outcome unknown, write may have been applied. ` +
286
+ `Check the server (or the origin it redirected to) before retrying.`
287
+ : `${method} ${path} to ${url}: the successful response body could not be read (HTTP ${status}); outcome unknown, write may have been applied. ` +
288
+ `Check the server (or the origin it redirected to) before retrying.`;
289
+ const err = new ApiRequestOutcomeUnknown(method, path, undefined, status, "explicit", detail);
290
+ err.cause = cause;
291
+ return err;
292
+ }
293
+ }
294
+ /**
295
+ * An ApiHttpError's unredacted response text and the credential values its
296
+ * request sent (flair#2764), kept for classification and redaction: only
297
+ * apiErrorRawBody (the text) and boundErrorText (which uses the values to
298
+ * redact) read this map. No field of the error holds the sent values; `body`
299
+ * and the message are display forms of the raw text, which may equal it.
300
+ */
301
+ const privateText = new WeakMap();
302
+ /** What a credential value the request sent becomes in the server's text as displayed. */
303
+ export const REDACTED_CREDENTIAL = "[redacted]";
304
+ /**
305
+ * Copy of TPS_ED25519_HEADER_RE in resources/ed25519-auth.ts, the grammar
306
+ * Flair's server parses a TPS-Ed25519 header with. The CLI build cannot import
307
+ * from resources/, so test/unit/http-error-reason-2764.test.ts asserts the two
308
+ * have the same source and flags (flair#2764).
309
+ */
310
+ export const TPS_ED25519_HEADER_GRAMMAR = /^TPS-Ed25519\s+([^:\s]+):(\d+):([^:\s]+):(.+)$/i;
311
+ /** Copy of BASIC_AUTH_HEADER_RE in resources/basic-auth-header.ts, held to it by the same test (flair#2764). */
312
+ export const BASIC_HEADER_GRAMMAR = /^Basic /i;
313
+ /** The schemes credentialsInHeader extracts a credential from (lower case). */
314
+ const KNOWN_SCHEMES = new Set(["basic", "bearer", "tps-ed25519"]);
315
+ /**
316
+ * The credential values an Authorization header carries (flair#2764), read
317
+ * from the value Fetch sends: the header with leading and trailing HTTP
318
+ * whitespace (tab, line feed, carriage return, space) removed, as Fetch
319
+ * normalizes it. The scheme is the text before the first run of whitespace
320
+ * (any character the regular expression class for whitespace matches),
321
+ * compared without regard to case. The values are that header value, the
322
+ * part after the scheme (as written and with surrounding whitespace trimmed),
323
+ * and for:
324
+ * - basic: the decoded `user:password` (or the decoded text, without a
325
+ * colon) and the password. When the header matches BASIC_HEADER_GRAMMAR,
326
+ * the server's own grammar, the decoded text is read as the server reads
327
+ * it (the text after its first six characters); otherwise from the part
328
+ * after the scheme;
329
+ * - tps-ed25519: the signature, read with TPS_ED25519_HEADER_GRAMMAR, the
330
+ * server's own grammar.
331
+ * `withhold` is set when the scheme is basic, bearer or tps-ed25519 but no
332
+ * decoded text, token or signature could be extracted that way; the server's
333
+ * text is then withheld rather than shown. Empty values are left out.
334
+ */
335
+ export function credentialsInHeader(authHeader) {
336
+ if (!authHeader)
337
+ return { values: [], withhold: false };
338
+ const sent = authHeader.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
339
+ const scheme = (/^\S+/.exec(sent)?.[0] ?? "").toLowerCase();
340
+ const credential = /^\S+\s+([\s\S]*)$/.exec(sent)?.[1] ?? "";
341
+ const values = [sent, credential, credential.trim()];
342
+ let extracted = false;
343
+ if (scheme === "basic") {
344
+ const encoded = BASIC_HEADER_GRAMMAR.test(sent) ? sent.slice(6) : credential.trim();
345
+ const decoded = Buffer.from(encoded, "base64").toString("utf8");
346
+ if (decoded.length > 0) {
347
+ const colon = decoded.indexOf(":");
348
+ values.push(decoded);
349
+ if (colon !== -1)
350
+ values.push(decoded.slice(colon + 1));
351
+ extracted = true;
352
+ }
353
+ }
354
+ else if (scheme === "tps-ed25519") {
355
+ const parsed = TPS_ED25519_HEADER_GRAMMAR.exec(sent);
356
+ if (parsed) {
357
+ values.push(parsed[4]);
358
+ extracted = true;
359
+ }
360
+ }
361
+ else if (scheme === "bearer") {
362
+ extracted = credential.trim().length > 0;
363
+ }
364
+ return { values: values.filter((value) => value.length > 0), withhold: KNOWN_SCHEMES.has(scheme) && !extracted };
365
+ }
366
+ const HEX2 = /^[0-9A-Fa-f]{2}$/;
367
+ const HEX4 = /^[0-9A-Fa-f]{4}$/;
368
+ /** The character each one-character JSON string escape (backslash, then this character) stands for. */
369
+ const JSON_SHORT_ESCAPES = {
370
+ '"': '"',
371
+ "\\": "\\",
372
+ "/": "/",
373
+ b: "\b",
374
+ f: "\f",
375
+ n: "\n",
376
+ r: "\r",
377
+ t: "\t",
378
+ };
379
+ /**
380
+ * One decoded unit of credentialIntervals' view at `i` in `text`: the string it
381
+ * stands for and how many characters of `text` it spans. A valid %XX escape
382
+ * (either hex case) stands for its byte, given as a one-byte buffer; a JSON
383
+ * string escape (backslash then one of the characters in JSON_SHORT_ESCAPES,
384
+ * or backslash-u with four hex digits, a surrogate pair of two such escapes
385
+ * read as one character) stands for its character; anything else stands for
386
+ * itself.
387
+ */
388
+ function viewUnit(text, i) {
389
+ if (text[i] === "%" && HEX2.test(text.slice(i + 1, i + 3))) {
390
+ return { bytes: Buffer.from([Number.parseInt(text.slice(i + 1, i + 3), 16)]), width: 3 };
391
+ }
392
+ if (text[i] === "\\" && i + 1 < text.length) {
393
+ const next = text[i + 1];
394
+ const short = JSON_SHORT_ESCAPES[next];
395
+ if (short !== undefined)
396
+ return { bytes: Buffer.from(short, "utf8"), width: 2 };
397
+ if (next === "u" && HEX4.test(text.slice(i + 2, i + 6))) {
398
+ const unit = Number.parseInt(text.slice(i + 2, i + 6), 16);
399
+ if (unit >= 0xd800 && unit <= 0xdbff && text.slice(i + 6, i + 8) === "\\u" && HEX4.test(text.slice(i + 8, i + 12))) {
400
+ const low = Number.parseInt(text.slice(i + 8, i + 12), 16);
401
+ if (low >= 0xdc00 && low <= 0xdfff) {
402
+ return { bytes: Buffer.from(String.fromCharCode(unit, low), "utf8"), width: 12 };
403
+ }
404
+ }
405
+ if (unit < 0xd800 || unit > 0xdfff)
406
+ return { bytes: Buffer.from(String.fromCharCode(unit), "utf8"), width: 6 };
407
+ }
408
+ }
409
+ const width = (text.codePointAt(i) ?? 0) > 0xffff ? 2 : 1;
410
+ return { bytes: Buffer.from(text.slice(i, i + width), "utf8"), width };
411
+ }
412
+ /**
413
+ * Every occurrence in `text` of each value in `sentValues`, overlapping ones
414
+ * included, as merged [start, end) intervals of `text` (flair#2764): intervals
415
+ * that overlap or touch become one. A value is found where `text` holds it
416
+ * literally, and, when `text` contains a "%" or a backslash, where `text`
417
+ * spells it with %XX escapes (either hex case) or JSON string escapes, for all
418
+ * or some of its characters: that search runs over a view of `text` with each
419
+ * such escape decoded (viewUnit), and maps each match back to the characters
420
+ * it came from. This holds whether or not `text` as a whole is valid JSON.
421
+ */
422
+ function credentialIntervals(text, sentValues) {
423
+ const found = [];
424
+ const values = sentValues.filter((value) => value.length > 0);
425
+ if (values.length === 0 || text.length === 0)
426
+ return found;
427
+ for (const value of values) {
428
+ for (let at = text.indexOf(value); at !== -1; at = text.indexOf(value, at + 1)) {
429
+ found.push([at, at + value.length]);
430
+ }
431
+ }
432
+ if (text.includes("%") || text.includes("\\")) {
433
+ // bytes: the decoded view; from/to: the [start, end) of `text` each byte came from.
434
+ const bytes = [];
435
+ const from = [];
436
+ const to = [];
437
+ for (let i = 0; i < text.length;) {
438
+ const unit = viewUnit(text, i);
439
+ for (const byte of unit.bytes) {
440
+ bytes.push(byte);
441
+ from.push(i);
442
+ to.push(i + unit.width);
443
+ }
444
+ i += unit.width;
445
+ }
446
+ const view = Buffer.from(bytes);
447
+ for (const value of values) {
448
+ const needle = Buffer.from(value, "utf8");
449
+ for (let at = view.indexOf(needle); at !== -1; at = view.indexOf(needle, at + 1)) {
450
+ found.push([from[at], to[at + needle.length - 1]]);
451
+ }
452
+ }
453
+ }
454
+ found.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
455
+ const merged = [];
456
+ for (const [start, end] of found) {
457
+ const last = merged[merged.length - 1];
458
+ if (last && start <= last[1])
459
+ last[1] = Math.max(last[1], end);
460
+ else
461
+ merged.push([start, end]);
462
+ }
463
+ return merged;
464
+ }
465
+ /** `text` with each interval replaced by `marker`. */
466
+ function replaceIntervals(text, intervals, marker) {
467
+ if (intervals.length === 0)
468
+ return text;
469
+ let out = "";
470
+ let at = 0;
471
+ for (const [start, end] of intervals) {
472
+ out += text.slice(at, start) + marker;
473
+ at = end;
474
+ }
475
+ return out + text.slice(at);
476
+ }
477
+ /** `text` when credentialIntervals finds no sent value in it, else `fallback` (flair#2764). */
478
+ function withoutOccurrence(text, sentValues, fallback) {
479
+ return credentialIntervals(text, sentValues).length === 0 ? text : fallback;
480
+ }
481
+ /**
482
+ * Server-supplied `text` with each merged interval of credentialIntervals
483
+ * replaced once by REDACTED_CREDENTIAL (flair#2764), in one pass: the server's
484
+ * text left in the result holds no occurrence credentialIntervals finds. The
485
+ * marker, and anything the CLI writes around the result, is not checked. The
486
+ * scope is the one on ApiHttpError.
487
+ */
488
+ export function redactSentCredentials(text, sentValues) {
489
+ return replaceIntervals(text, credentialIntervals(text, sentValues), REDACTED_CREDENTIAL);
490
+ }
491
+ /**
492
+ * A parsed JSON value with every string in it, object keys included, redacted,
493
+ * and every number, boolean or null whose JSON text holds a sent value replaced
494
+ * by the string REDACTED_CREDENTIAL (flair#2764).
495
+ */
496
+ function redactJsonValues(value, sentValues) {
497
+ if (typeof value === "string")
498
+ return redactSentCredentials(value, sentValues);
499
+ if (Array.isArray(value))
500
+ return value.map((item) => redactJsonValues(item, sentValues));
501
+ if (value && typeof value === "object") {
502
+ const out = Object.create(null);
503
+ for (const [key, item] of Object.entries(value)) {
504
+ out[redactSentCredentials(key, sentValues)] = redactJsonValues(item, sentValues);
505
+ }
506
+ return out;
507
+ }
508
+ return credentialIntervals(JSON.stringify(value), sentValues).length === 0 ? value : REDACTED_CREDENTIAL;
509
+ }
510
+ /** What displayBody shows for a body it cannot show: see displayBody. */
511
+ export const BODY_WITHHELD = "[body withheld]";
512
+ /**
513
+ * A response body for display (flair#2764). A body JSON.parse rejects with a
514
+ * SyntaxError (not JSON) is shown as received, redacted as text. A JSON body
515
+ * is shown re-serialized, with every string in it (keys included) redacted
516
+ * after JSON decoding and any other value whose JSON text holds a sent value
517
+ * replaced; or as BODY_WITHHELD when it cannot be: when parsing fails any
518
+ * other way (for example a nesting too deep to parse), when its redaction or
519
+ * re-serialization fails, or when the re-serialized JSON still holds a sent
520
+ * value (for example a value that occurs in JSON syntax). With `withhold` set
521
+ * (credentialsInHeader), a non-empty body is shown as BODY_WITHHELD.
522
+ */
523
+ function displayBody(body, sentValues, withhold = false) {
524
+ if (withhold && body.length > 0)
525
+ return BODY_WITHHELD;
526
+ let parsed;
527
+ try {
528
+ parsed = JSON.parse(body);
529
+ }
530
+ catch (err) {
531
+ if (err instanceof SyntaxError)
532
+ return redactSentCredentials(body, sentValues);
533
+ return BODY_WITHHELD;
534
+ }
535
+ try {
536
+ return withoutOccurrence(JSON.stringify(redactJsonValues(parsed, sentValues)), sentValues, BODY_WITHHELD);
537
+ }
538
+ catch {
539
+ return BODY_WITHHELD;
540
+ }
541
+ }
542
+ /** What displayPath shows for a path it cannot show. */
543
+ export const PATH_WITHHELD = "[path withheld]";
544
+ /** C0 controls, DEL, C1 controls and the Unicode line and paragraph separators. */
545
+ const CONTROL_CHARACTER = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/;
546
+ /**
547
+ * A request path for display (flair#2764): percent-decoded, then redacted.
548
+ * PATH_WITHHELD when it does not decode or the decoded path holds a
549
+ * CONTROL_CHARACTER.
550
+ */
551
+ function displayPath(path, sentValues) {
552
+ let decoded;
553
+ try {
554
+ decoded = decodeURIComponent(path);
555
+ }
556
+ catch {
557
+ return PATH_WITHHELD;
558
+ }
559
+ if (CONTROL_CHARACTER.test(decoded))
560
+ return PATH_WITHHELD;
561
+ return redactSentCredentials(decoded, sentValues);
562
+ }
563
+ /** The most characters boundServerText keeps before it cuts the text and appends "..." (flair#2764). */
564
+ export const SERVER_TEXT_MAX_CHARS = 200;
565
+ /**
566
+ * Server text as one line: control characters that are not whitespace are
567
+ * removed, each run of whitespace (line breaks included) becomes one space,
568
+ * and the ends are trimmed.
569
+ */
570
+ function oneLine(text) {
571
+ return text
572
+ .replace(/[\u0000-\u0008\u000E-\u001F\u007F-\u0084\u0086-\u009F]/g, "")
573
+ .replace(/[\s\u0085]+/g, " ")
574
+ .trim();
575
+ }
576
+ /** `line` cut after SERVER_TEXT_MAX_CHARS characters, ending in "...", when it is longer. */
577
+ function cutToBound(line) {
578
+ let count = 0;
579
+ let index = 0;
580
+ for (const ch of line) {
581
+ if (count === SERVER_TEXT_MAX_CHARS)
582
+ return `${line.slice(0, index).trimEnd()}...`;
583
+ count++;
584
+ index += ch.length;
585
+ }
586
+ return line;
587
+ }
588
+ /**
589
+ * Server text as one line: control characters that are not whitespace are
590
+ * removed, each run of whitespace (line breaks included) becomes one space and
591
+ * the ends are trimmed, and text longer than SERVER_TEXT_MAX_CHARS characters
592
+ * is cut there and ends in "...".
593
+ */
594
+ export function boundServerText(text) {
595
+ return cutToBound(oneLine(text));
596
+ }
597
+ /**
598
+ * A private-use character no value in `sentValues` contains, standing in for
599
+ * REDACTED_CREDENTIAL while boundAndRedact works: line-making leaves it alone
600
+ * and no sent value can match it, so the second pass does not alter the marker.
601
+ * The private-use ranges hold over 137,000 characters, more than an
602
+ * Authorization header the transport sends can contain; were none free, the
603
+ * marker itself would stand in.
604
+ */
605
+ function standInFor(sentValues) {
606
+ for (const [first, last] of [[0xe000, 0xf8ff], [0xf0000, 0xffffd], [0x100000, 0x10fffd]]) {
607
+ for (let cp = first; cp <= last; cp++) {
608
+ const ch = String.fromCodePoint(cp);
609
+ if (!sentValues.some((value) => value.includes(ch)))
610
+ return ch;
611
+ }
612
+ }
613
+ return REDACTED_CREDENTIAL;
614
+ }
615
+ /**
616
+ * The text of `line` (holding stand-ins `standIn`, each displayed as
617
+ * REDACTED_CREDENTIAL) that fits SERVER_TEXT_MAX_CHARS displayed characters,
618
+ * ending before a stand-in that does not fit and never inside a %XX or JSON
619
+ * string escape credentialIntervals decodes (viewUnit), with trailing
620
+ * whitespace trimmed; null when all of `line` fits (flair#2764).
621
+ */
622
+ function keptBeforeCut(line, standIn) {
623
+ let count = 0;
624
+ let index = 0;
625
+ let cut = -1;
626
+ for (const ch of line) {
627
+ const width = ch === standIn ? REDACTED_CREDENTIAL.length : 1;
628
+ if (count + width > SERVER_TEXT_MAX_CHARS) {
629
+ cut = index;
630
+ break;
631
+ }
632
+ count += width;
633
+ index += ch.length;
634
+ }
635
+ if (cut === -1)
636
+ return null;
637
+ let boundary = cut;
638
+ if (line.includes("%") || line.includes("\\")) {
639
+ for (let i = 0; i < cut;) {
640
+ const width = viewUnit(line, i).width;
641
+ if (i + width > cut) {
642
+ boundary = i;
643
+ break;
644
+ }
645
+ i += width;
646
+ }
647
+ }
648
+ return line.slice(0, boundary).trimEnd();
649
+ }
650
+ /**
651
+ * boundServerText for output, with `sentValues` redacted from the server's
652
+ * text (flair#2764). Order: redact, make one line, redact again, cut. Each
653
+ * occurrence is replaced by a stand-in character (standInFor) while this
654
+ * works; the first pass catches a credential before line-making can change it
655
+ * (a whitespace run collapsed, a control character removed), and the second
656
+ * catches one that line-making forms. The cut (keptBeforeCut) counts each
657
+ * stand-in as the marker's length and falls between view units, so it splits
658
+ * neither the marker nor an occurrence; then the stand-ins become
659
+ * REDACTED_CREDENTIAL and "..." is appended to a cut text. Neither the marker
660
+ * nor "..." is passed through redaction.
661
+ */
662
+ function boundAndRedact(text, sentValues) {
663
+ if (sentValues.length === 0)
664
+ return boundServerText(text);
665
+ const standIn = standInFor(sentValues);
666
+ let line = oneLine(replaceIntervals(text, credentialIntervals(text, sentValues), standIn));
667
+ line = replaceIntervals(line, credentialIntervals(line, sentValues), standIn);
668
+ const shown = (t) => t.split(standIn).join(REDACTED_CREDENTIAL);
669
+ const kept = keptBeforeCut(line, standIn);
670
+ return kept === null ? shown(line) : `${shown(kept)}...`;
671
+ }
672
+ /**
673
+ * The message of an ApiHttpError built from a response body (flair#2764):
674
+ * `HTTP <status>`, then the body's named error when the body is a JSON object
675
+ * with an `error`, else `code`, else `message` string that is non-empty once
676
+ * bounded; otherwise an excerpt of the body, or BODY_WITHHELD when displayBody
677
+ * withholds the body. The named error and the excerpt are read from the
678
+ * unredacted body and go through boundAndRedact with `sentValues`. The
679
+ * `HTTP <status>` prefix and BODY_WITHHELD are written by this function and
680
+ * are not passed through redaction. With `withhold` set (credentialsInHeader),
681
+ * the reason for a non-empty body is BODY_WITHHELD.
682
+ */
683
+ export function describeHttpFailure(status, body, sentValues = [], withhold = false) {
684
+ if (withhold && body.length > 0)
685
+ return `HTTP ${status}: ${BODY_WITHHELD}`;
686
+ let reason = "";
687
+ let parsed;
688
+ try {
689
+ parsed = JSON.parse(body);
690
+ }
691
+ catch {
692
+ parsed = undefined;
693
+ }
694
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
695
+ for (const key of ["error", "code", "message"]) {
696
+ const value = parsed[key];
697
+ if (typeof value === "string")
698
+ reason = boundAndRedact(value, sentValues);
699
+ if (reason)
700
+ break;
701
+ }
702
+ }
703
+ if (!reason) {
704
+ reason = displayBody(body, sentValues) === BODY_WITHHELD ? BODY_WITHHELD : boundAndRedact(body, sentValues);
705
+ }
706
+ return reason ? `HTTP ${status}: ${reason}` : `HTTP ${status}`;
707
+ }
708
+ /**
709
+ * The display form of the response body an ApiHttpError carries (`body`):
710
+ * when fromResponse built the error, displayBody's form of the server's text,
711
+ * redacted with the values credentialsInHeader read from its request's
712
+ * Authorization header (within the scope on ApiHttpError), or withheld.
713
+ * Undefined for any other error (flair#2764).
714
+ */
715
+ export function apiErrorBody(err) {
716
+ return err instanceof ApiHttpError ? err.body : undefined;
717
+ }
718
+ /**
719
+ * The unredacted response text, for code that classifies a failure by the
720
+ * server's text (flair#2764). It may hold a credential the request sent:
721
+ * classifiers read it, and text displayed from it goes through boundErrorText,
722
+ * which redacts it within the scope on ApiHttpError or withholds it. For an
723
+ * ApiHttpError not built by fromResponse it is `body`; undefined for any other
724
+ * error.
725
+ */
726
+ export function apiErrorRawBody(err) {
727
+ if (!(err instanceof ApiHttpError))
728
+ return undefined;
729
+ return privateText.get(err)?.raw ?? err.body;
730
+ }
731
+ /**
732
+ * `text` (taken from apiErrorRawBody) as one bounded line for output, with
733
+ * the credential values credentialsInHeader read from `err`'s request header
734
+ * redacted from it (boundAndRedact, within the scope on ApiHttpError), or
735
+ * BODY_WITHHELD when credentialsInHeader set `withhold` for that header and
736
+ * the response text `err` was built from is non-empty, whatever `text` is
737
+ * (an empty `text` derived from it, such as an empty `error` string, included).
738
+ * When that response text is empty nothing is withheld. For an error that has
739
+ * no sent values, boundServerText(text) (flair#2764).
740
+ */
741
+ export function boundErrorText(err, text) {
742
+ const kept = err instanceof ApiHttpError ? privateText.get(err) : undefined;
743
+ if (kept?.withhold && kept.raw.length > 0)
744
+ return BODY_WITHHELD;
745
+ return boundAndRedact(text, kept?.sentValues ?? []);
746
+ }
747
+ /**
748
+ * With FLAIR_DEBUG set (any non-empty value), write the display form of a
749
+ * failed response's body to stderr as one JSON string (flair#2764). The path
750
+ * is shown by displayPath (percent-decoded, then redacted, or withheld) and
751
+ * the body by displayBody (a JSON body re-serialized, or withheld; any
752
+ * non-empty body withheld when `withhold` is set, an empty one shown as ""),
753
+ * each redacted within the scope on
754
+ * ApiHttpError; the labels, method, status and the JSON encoding of the body
755
+ * are written by this function and are not passed through redaction. In the
756
+ * JSON-encoded body, DEL, C1 control characters and the Unicode line and
757
+ * paragraph separators are escaped as well, so the line holds no
758
+ * CONTROL_CHARACTER but its final newline. `sendJsonRequest` calls it where it
759
+ * builds the error from the body. `env` and `write` are injectable for tests.
760
+ */
761
+ export function emitHttpErrorBodyDebug(method, path, status, body, sentValues = [], withhold = false, env = process.env, write = (s) => { process.stderr.write(s); }) {
762
+ if (!env.FLAIR_DEBUG)
763
+ return;
764
+ const shownBody = JSON.stringify(displayBody(body, sentValues, withhold)).replace(/[\u007F-\u009F\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
765
+ write(`[flair] ${method} ${displayPath(path, sentValues)} answered HTTP ${status}; response body: ${shownBody}\n`);
92
766
  }
93
767
  // ─── Admin-pass file handling ───────────────────────────────────────────────
94
768
  /**
@@ -131,6 +805,9 @@ export function readAdminPassFileSecure(path) {
131
805
  /** Thrown by `resolveAdminPassFromSources` when two credential sources are given at once. */
132
806
  export class AdminPassSourceError extends Error {
133
807
  }
808
+ export class AdminPassEmptyError extends Error {
809
+ name = "AdminPassEmptyError";
810
+ }
134
811
  /**
135
812
  * Resolve an admin password from the credential sources a command exposes, in
136
813
  * the precedence its usage text states: an explicit option — `--admin-pass-file`
@@ -144,20 +821,24 @@ export class AdminPassSourceError extends Error {
144
821
  * with a message naming the path and its mode.
145
822
  *
146
823
  * 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.
824
+ * required" message.
150
825
  */
151
826
  export function resolveAdminPassFromSources(input) {
152
827
  const { adminPassFile, adminPass, envPass } = input;
153
- if (adminPassFile && adminPass) {
828
+ if (adminPassFile !== undefined && adminPass !== undefined) {
154
829
  throw new AdminPassSourceError("--admin-pass and --admin-pass-file cannot be combined; pass exactly one. " +
155
830
  "Prefer --admin-pass-file: it keeps the password out of shell history and the process list.");
156
831
  }
157
- if (adminPassFile)
832
+ if (adminPassFile !== undefined) {
833
+ if (adminPassFile === "")
834
+ throw new AdminPassEmptyError("--admin-pass-file must not be empty");
158
835
  return readAdminPassFileSecure(adminPassFile);
159
- if (adminPass)
836
+ }
837
+ if (adminPass !== undefined) {
838
+ if (adminPass === "")
839
+ throw new AdminPassEmptyError("--admin-pass must not be empty");
160
840
  return adminPass;
841
+ }
161
842
  return envPass ?? "";
162
843
  }
163
844
  export function defaultAdminPassPath() {
@@ -173,10 +854,71 @@ export function defaultAdminPassPath() {
173
854
  // these strings locally, flair#1873) and the shared credential-option helper
174
855
  // every sibling command uses.
175
856
  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. " +
857
+ 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
858
  "An explicit option (this or --admin-pass) overrides FLAIR_ADMIN_PASS; combining it with --admin-pass is a usage error.";
178
859
  export const ADMIN_PASS_FLAG = "--admin-pass <pass>";
179
860
  export const ADMIN_PASS_HELP = "Admin password (legacy: lands in shell history and the process list — prefer --admin-pass-file or FLAIR_ADMIN_PASS)";
861
+ /** Commands whose admin-password pair `addAdminPassOptions` wired. A test walks
862
+ * the registered tree and asserts every command that declares `--admin-pass`
863
+ * is in it, and every command that declares `--admin-pass-file` except
864
+ * `rem nightly enable`, which declares that flag itself as path-only. Inherited
865
+ * leaves are not in this set: `federation sync enable` stores the path in the
866
+ * unit it installs, and `sync status`/`disable` apply the pair in their own
867
+ * hooks. */
868
+ export const adminPassFileWired = new WeakSet();
869
+ /**
870
+ * Declare the admin-password pair on `cmd`: the argv form and the file form
871
+ * together, in that order, and apply it in a preAction hook. For a command that
872
+ * declares the pair, the hook runs after option parsing and before the action
873
+ * body, so a refused file exits before any request the action makes. A
874
+ * subcommand that inherits the pair from `cmd` stores the values on `cmd`; the
875
+ * leaves that apply them (`federation sync status`/`disable`) do so in their
876
+ * own hooks.
877
+ */
878
+ export function addAdminPassOptions(cmd, adminPassHelp = ADMIN_PASS_HELP, opts = {}) {
879
+ const adminPassFile = new Option(ADMIN_PASS_FILE_FLAG, opts.adminPassFileHelp ?? ADMIN_PASS_FILE_HELP);
880
+ cmd.option(ADMIN_PASS_FLAG, adminPassHelp).addOption(adminPassFile);
881
+ adminPassFileWired.add(cmd);
882
+ cmd.hook("preAction", (_thisCommand, actionCommand) => {
883
+ // A subcommand that inherits the pair (`federation sync status`) stores the
884
+ // values on this command, not on itself; the leaves that read an inherited
885
+ // pair apply it in their own hook. Reading only the leaf's opts() would ignore
886
+ // the inherited pair, leaving `status` able to send its request with the
887
+ // ambient admin password.
888
+ if (!actionCommand.options.some((o) => o.long === "--admin-pass-file"))
889
+ return;
890
+ const actionOpts = actionCommand.opts();
891
+ // Recorded before the file is applied: the warning keys on whether
892
+ // --admin-pass itself was given, not on the value that ends up in the slot.
893
+ actionOpts.inlineAdminPass =
894
+ actionCommand.getOptionValueSource("adminPass") === "cli" ? actionOpts.adminPass : undefined;
895
+ applyAdminPassFile(actionOpts, opts.onAdminPassRefusal
896
+ ? (err) => opts.onAdminPassRefusal(err, actionCommand)
897
+ : undefined);
898
+ });
899
+ return cmd;
900
+ }
901
+ /**
902
+ * Copy a nonempty explicit password into `opts.adminPass`; callers own environment fallback.
903
+ * Refuse combined options and missing, empty or group-/world-accessible files.
904
+ * Group/world permission refusals name the path and mode; missing and empty file errors name only the path.
905
+ */
906
+ export function applyAdminPassFile(opts, onRefusal) {
907
+ try {
908
+ const pass = resolveAdminPassFromSources({
909
+ adminPassFile: opts.adminPassFile,
910
+ adminPass: opts.adminPass,
911
+ });
912
+ if (pass)
913
+ opts.adminPass = pass;
914
+ }
915
+ catch (err) {
916
+ if (onRefusal)
917
+ onRefusal(err);
918
+ console.error(`Error: ${err.message}`);
919
+ process.exit(1);
920
+ }
921
+ }
180
922
  /** The admin username Harper's bootstrap creates and every Basic-auth path
181
923
  * historically hardcoded. Kept as the default; overridable per call via
182
924
  * `resolveAdminUser` (flair#1345). */
@@ -205,9 +947,6 @@ export const DEFAULT_ADMIN_USER = "admin";
205
947
  export function resolveAdminUser(explicit) {
206
948
  return explicit || process.env.FLAIR_ADMIN_USER || DEFAULT_ADMIN_USER;
207
949
  }
208
- export function defaultKeysDir() {
209
- return join(resolveHome(), ".flair", "keys");
210
- }
211
950
  /**
212
951
  * Resolve an admin password for LOCAL-only CLI convenience (`agent add`,
213
952
  * `principal add`) without requiring `--admin-pass` on every call (#590).
@@ -263,15 +1002,19 @@ export function resolveLocalAdminPass(explicit, isRemoteTarget = false, adminPas
263
1002
  // ─── Ed25519 agent-key signing ──────────────────────────────────────────────
264
1003
  /** Find the agent's private key file from standard locations. */
265
1004
  export function resolveKeyPath(agentId) {
266
- const candidates = [
267
- process.env.FLAIR_KEY_DIR ? join(process.env.FLAIR_KEY_DIR, `${agentId}.key`) : null,
268
- join(resolveHome(), ".flair", "keys", `${agentId}.key`),
269
- join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
270
- ].filter(Boolean);
271
- return candidates.find((p) => existsSync(p)) ?? null;
272
- }
273
- /** Build a TPS-Ed25519 auth header from a raw 32-byte seed on disk. */
274
- export function buildEd25519Auth(agentId, method, path, keyPath) {
1005
+ for (const location of agentKeyLocations()) {
1006
+ const path = keyPathIn(location, agentId);
1007
+ if (existsSync(path))
1008
+ return path;
1009
+ }
1010
+ return null;
1011
+ }
1012
+ /**
1013
+ * Load a signing key from disk: read the file, decode it (raw 32-byte seed,
1014
+ * base64 seed, full PKCS8 DER or PEM), and require an Ed25519 key. A throw here
1015
+ * is a failure of THIS key file; nothing has been sent for it.
1016
+ */
1017
+ function loadEd25519SigningKey(keyPath) {
275
1018
  const raw = readFileSync(keyPath);
276
1019
  const pkcs8Header = Buffer.from("302e020100300506032b657004220420", "hex");
277
1020
  let privKey;
@@ -296,12 +1039,23 @@ export function buildEd25519Auth(agentId, method, path, keyPath) {
296
1039
  }
297
1040
  }
298
1041
  }
1042
+ if (privKey.asymmetricKeyType !== "ed25519") {
1043
+ throw new Error(`signing key ${keyPath} is not an Ed25519 private key`);
1044
+ }
1045
+ return privKey;
1046
+ }
1047
+ /** Build a TPS-Ed25519 auth header from an already-loaded Ed25519 key. */
1048
+ function buildEd25519AuthFromKey(agentId, method, path, privKey) {
299
1049
  const ts = Date.now().toString();
300
1050
  const nonce = randomUUID();
301
1051
  const payload = `${agentId}:${ts}:${nonce}:${method}:${path}`;
302
1052
  const sig = nodeCryptoSign(null, Buffer.from(payload), privKey).toString("base64");
303
1053
  return `TPS-Ed25519 ${agentId}:${ts}:${nonce}:${sig}`;
304
1054
  }
1055
+ /** Build a TPS-Ed25519 auth header from the key file at `keyPath`. */
1056
+ export function buildEd25519Auth(agentId, method, path, keyPath) {
1057
+ return buildEd25519AuthFromKey(agentId, method, path, loadEd25519SigningKey(keyPath));
1058
+ }
305
1059
  /** Join a Flair route to an optional base path before signing or sending it. */
306
1060
  export function requestUrl(baseUrl, path) {
307
1061
  const base = new URL(baseUrl);
@@ -398,6 +1152,15 @@ export function describeKeyLoadFailure(keyPath, kind, underlying) {
398
1152
  * failures are not classified here.
399
1153
  */
400
1154
  export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
1155
+ return (await authFetchWithSentCredentials(baseUrl, agentId, keyPath, method, path, body)).res;
1156
+ }
1157
+ /**
1158
+ * `authFetch`'s request, with the credentials it sent: a caller that renders a
1159
+ * non-ok response needs them to redact a body that echoes the Authorization
1160
+ * header (flair#2889). `sent` is `credentialsInHeader`'s reading of the header
1161
+ * this request sent.
1162
+ */
1163
+ export async function authFetchWithSentCredentials(baseUrl, agentId, keyPath, method, path, body) {
401
1164
  const url = requestUrl(baseUrl, path);
402
1165
  let auth;
403
1166
  try {
@@ -409,11 +1172,12 @@ export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
409
1172
  const headers = { Authorization: auth };
410
1173
  if (body !== undefined)
411
1174
  headers["Content-Type"] = "application/json";
412
- return fetch(url.href, {
1175
+ const res = await fetch(url.href, {
413
1176
  method,
414
1177
  headers,
415
1178
  body: body !== undefined ? JSON.stringify(body) : undefined,
416
1179
  });
1180
+ return { res, sent: credentialsInHeader(auth) };
417
1181
  }
418
1182
  export function isLocalBase(base) {
419
1183
  try {
@@ -424,7 +1188,20 @@ export function isLocalBase(base) {
424
1188
  return !base;
425
1189
  }
426
1190
  }
427
- // ─── HTTP + response handling ───────────────────────────────────────────────
1191
+ function noCredentialsHint(isLocal, signedOnly) {
1192
+ if (signedOnly) {
1193
+ // No admin password leaves a signedOnly request, so only an agent key helps.
1194
+ const keyPath = signedOnly.agentId ? agentKeyPath(defaultKeysDir(), signedOnly.agentId) : null;
1195
+ const remedy = keyPath
1196
+ ? `Provide the key of agent '${signedOnly.agentId}' at ${keyPath} ` +
1197
+ `(or set FLAIR_KEY_DIR to a directory containing ${basename(keyPath)}).`
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
+ }
428
1205
  /**
429
1206
  * Perform the actual Flair REST call with an already-resolved Authorization
430
1207
  * header (or none) and classify the response. Shared by the primary
@@ -432,47 +1209,203 @@ export function isLocalBase(base) {
432
1209
  * agree on 204/empty-body handling, JSON parsing, and the no-credentials
433
1210
  * 403 hint text.
434
1211
  */
435
- export async function sendJsonRequest(url, method, body, authHeader, isLocal) {
436
- const res = await fetch(url.href, {
437
- method,
438
- headers: {
439
- "content-type": "application/json",
440
- ...(authHeader ? { authorization: authHeader } : {}),
441
- },
442
- body: body ? JSON.stringify(body) : undefined,
443
- });
444
- // Handle 204 No Content (e.g., PUT upsert returns empty body)
445
- if (res.status === 204 || res.headers.get("content-length") === "0") {
446
- if (!res.ok)
447
- throw new ApiHttpError(res.status, `HTTP ${res.status}`);
448
- return { ok: true };
449
- }
450
- const text = await res.text();
451
- 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
+ }
452
1278
  // 403 with no credentials sent at all is the flair#634 case: a gated
453
1279
  // resource rejected a credential-less call. Name the fix instead of
454
- // 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).
455
1283
  if (res.status === 403 && !authHeader) {
456
- const hint = isLocal
457
- ? "Set FLAIR_ADMIN_PASS, or run `flair init` to provision ~/.flair/admin-pass or an agent key."
458
- : "Set FLAIR_ADMIN_PASS (remote targets have no local admin-pass fallback).";
1284
+ await readBody();
1285
+ const hint = noCredentialsHint(isLocal, transport.signedOnly);
459
1286
  throw new ApiHttpError(403, `HTTP 403: no credentials sent. ${hint}`, /* noCredentials */ true);
460
1287
  }
461
- 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;
462
1379
  }
463
- if (!text)
464
- return { ok: true };
465
- return JSON.parse(text);
466
1380
  }
467
1381
  /**
468
1382
  * Tier 5, the floor (flair#747, generalizing flair#742's `verifyAuthedGet`
469
- * GET-only fallback to any method/body): try every registered key in
470
- * `keysDir` in sorted (deterministic) filename order, first one that
471
- * authenticates wins. Returns `undefined` — never throws — when every key
472
- * fails or none exist, so the caller can rethrow its ORIGINAL
473
- * 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.
474
1407
  */
475
- export async function tryAgentKeyFloor(url, method, body, keysDir) {
1408
+ export async function tryAgentKeyFloor(url, method, body, keysDir, transport = {}) {
476
1409
  let keyFiles = [];
477
1410
  try {
478
1411
  keyFiles = readdirSync(keysDir).filter((f) => f.endsWith(".key")).sort();
@@ -481,18 +1414,51 @@ export async function tryAgentKeyFloor(url, method, body, keysDir) {
481
1414
  // No keys dir at all — nothing to fall back to.
482
1415
  }
483
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);
484
1421
  for (const kf of keyFiles) {
485
1422
  const agentId = kf.replace(/\.key$/, "");
486
1423
  const keyPath = join(keysDir, kf);
1424
+ let privKey;
487
1425
  try {
488
- const authHeader = buildEd25519Auth(agentId, method, requestTarget(url), keyPath);
489
- return await sendJsonRequest(url, method, body, authHeader, isLocal);
1426
+ privKey = loadEd25519SigningKey(keyPath);
490
1427
  }
491
1428
  catch {
492
- // This key didn't work (unregistered, bad signature, network blip on
493
- // 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;
494
1458
  }
495
1459
  }
1460
+ // No key authenticated. Returning `undefined` lets the caller rethrow its
1461
+ // original no-credentials hint, which carries the operator's remedy.
496
1462
  return undefined;
497
1463
  }
498
1464
  /**
@@ -581,7 +1547,7 @@ export async function authedRequest(method, path, body, opts) {
581
1547
  const keyPath = resolveKeyPath(opts.agentId);
582
1548
  if (!keyPath) {
583
1549
  throw new Error(`--agent '${opts.agentId}' has no signing key. Expected a key at ` +
584
- `${join(defaultKeysDir(), `${opts.agentId}.key`)} (or set FLAIR_KEY_DIR ` +
1550
+ `${agentKeyPath(defaultKeysDir(), opts.agentId)} (or set FLAIR_KEY_DIR ` +
585
1551
  `to a directory containing it). Refusing to fall back to FLAIR_ADMIN_PASS ` +
586
1552
  `or the local admin-pass file.`);
587
1553
  }
@@ -655,14 +1621,24 @@ export async function authedRequest(method, path, body, opts) {
655
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");
656
1622
  }
657
1623
  try {
658
- return await sendJsonRequest(url, method, 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
+ });
659
1631
  }
660
1632
  catch (err) {
661
1633
  // Tier 5 — the floor. Only engages when NOTHING above resolved to
662
1634
  // anything sendable (see module header for why a rejected credential
663
1635
  // does not retry here).
664
1636
  if (err instanceof ApiHttpError && err.noCredentials) {
665
- const floorResult = await tryAgentKeyFloor(url, method, body, keysDir);
1637
+ const floorResult = await tryAgentKeyFloor(url, method, body, keysDir, {
1638
+ deadlineMs: opts.deadlineMs,
1639
+ deadlineSource: opts.deadlineSource,
1640
+ tolerateUnparsedSuccessBody: opts.tolerateUnparsedSuccessBody,
1641
+ });
666
1642
  if (floorResult !== undefined)
667
1643
  return floorResult;
668
1644
  }