@tpsdev-ai/flair 0.55.2 → 0.57.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 (106) hide show
  1. package/README.md +18 -19
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +125 -26
  7. package/dist/commands/agent.js +22 -15
  8. package/dist/commands/attention.js +2 -2
  9. package/dist/commands/backup.js +2 -2
  10. package/dist/commands/bridge.js +40 -3
  11. package/dist/commands/doctor.js +91 -28
  12. package/dist/commands/export.js +2 -2
  13. package/dist/commands/federation.js +441 -68
  14. package/dist/commands/hook.js +4 -4
  15. package/dist/commands/init.js +59 -12
  16. package/dist/commands/mcp.js +2 -2
  17. package/dist/commands/migrate-harness-memory.js +8 -8
  18. package/dist/commands/rem.js +2 -2
  19. package/dist/commands/service.js +25 -1
  20. package/dist/commands/session.js +2 -2
  21. package/dist/commands/uninstall.js +2 -2
  22. package/dist/commands/upgrade.js +3 -3
  23. package/dist/doctor-client.js +5 -23
  24. package/dist/engine-version.js +2 -2
  25. package/dist/federation/scheduler.js +5 -5
  26. package/dist/install/clients.js +5 -10
  27. package/dist/keystore.js +10 -2
  28. package/dist/lib/auth-resolve.js +51 -5
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/flair-paths.js +29 -0
  31. package/dist/lib/home.js +60 -0
  32. package/dist/lib/instance-identity-row.js +580 -0
  33. package/dist/lib/launchd-repair.js +6 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +1 -13
  36. package/dist/lib/redact-token-id.js +197 -0
  37. package/dist/lib/socket-path-limit.js +120 -0
  38. package/dist/lib/uninstall-purge.js +2 -18
  39. package/dist/lib/upgrade-plain-tree.js +2 -2
  40. package/dist/mcp-client-assertion.js +3 -3
  41. package/dist/rem/runner.js +3 -3
  42. package/dist/rem/scheduler.js +5 -5
  43. package/dist/rem/snapshot.js +2 -2
  44. package/dist/resources/AgentSeed.js +4 -1
  45. package/dist/resources/Asset.js +3 -11
  46. package/dist/resources/Credential.js +4 -10
  47. package/dist/resources/Federation.js +232 -78
  48. package/dist/resources/Integration.js +8 -32
  49. package/dist/resources/Memory.js +58 -16
  50. package/dist/resources/MemoryBootstrap.js +19 -12
  51. package/dist/resources/MemoryCandidate.js +3 -11
  52. package/dist/resources/MemoryDedupStats.js +1 -1
  53. package/dist/resources/MemoryFeed.js +10 -2
  54. package/dist/resources/MemoryGrant.js +19 -40
  55. package/dist/resources/MemoryUsage.js +7 -20
  56. package/dist/resources/OAuth.js +62 -11
  57. package/dist/resources/Presence.js +135 -47
  58. package/dist/resources/Relationship.js +3 -11
  59. package/dist/resources/SemanticSearch.js +25 -13
  60. package/dist/resources/admin-layout.js +7 -2
  61. package/dist/resources/auth-middleware.js +32 -5
  62. package/dist/resources/bm25.js +13 -14
  63. package/dist/resources/federation-cleanup.js +289 -51
  64. package/dist/resources/health.js +48 -8
  65. package/dist/resources/in-process-api.js +2 -1
  66. package/dist/resources/instance-create-lock.js +363 -0
  67. package/dist/resources/instance-identity-rows.js +43 -0
  68. package/dist/resources/instance-identity.js +94 -10
  69. package/dist/resources/mcp-handler.js +9 -1
  70. package/dist/resources/mcp-tool-arguments.js +83 -0
  71. package/dist/resources/mcp-tools.js +4 -5
  72. package/dist/resources/memory-reflect-lib.js +17 -1
  73. package/dist/resources/memory-visibility.js +10 -7
  74. package/dist/resources/rate-limit.js +6 -4
  75. package/dist/resources/record-type-kit.js +47 -23
  76. package/dist/resources/search-readiness.js +7 -1
  77. package/dist/resources/semantic-retrieval-core.js +98 -3
  78. package/dist/resources/table-helpers.js +33 -0
  79. package/dist/resources/tool-descriptors/index.js +2 -2
  80. package/dist/src/keystore.js +10 -2
  81. package/dist/src/lib/home.js +60 -0
  82. package/dist/src/lib/instance-identity-row.js +580 -0
  83. package/dist/src/lib/redact-token-id.js +197 -0
  84. package/dist/src/rem/scheduler.js +5 -5
  85. package/dist/version-check.js +2 -2
  86. package/dist/version-handshake.js +2 -2
  87. package/docs/api-reference.md +32 -7
  88. package/docs/auth.md +19 -7
  89. package/docs/claude-code.md +5 -6
  90. package/docs/deploying-on-fabric.md +8 -4
  91. package/docs/deployment.md +26 -37
  92. package/docs/embedding-in-a-harper-app.md +4 -2
  93. package/docs/entity-vocabulary.md +5 -5
  94. package/docs/federation.md +48 -21
  95. package/docs/hosted-on-fabric.md +7 -4
  96. package/docs/integrations.md +24 -15
  97. package/docs/mcp-clients.md +44 -23
  98. package/docs/n8n.md +8 -8
  99. package/docs/notes/mcp-oauth-model2.md +12 -17
  100. package/docs/openclaw.md +29 -28
  101. package/docs/spoke-bringup.md +44 -22
  102. package/docs/standalone-local.md +12 -16
  103. package/docs/supply-chain-policy.md +21 -8
  104. package/docs/system-requirements.md +1 -1
  105. package/docs/upgrade.md +2 -2
  106. package/package.json +1 -1
@@ -5,9 +5,11 @@ import { keystore, keyPath as keystoreKeyPath } from "../keystore.js";
5
5
  import * as render from "../render.js";
6
6
  import { runFederationVerify } from "../federation-verify.js";
7
7
  import { resolveHubPeerIdentity } from "../lib/federation-pair-identity.js";
8
+ import { redactTokenMessage } from "../lib/redact-token-id.js";
8
9
  import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
9
- import { defaultAdminPassPath, isLocalBase, resolveAdminUser, } from "../lib/auth-resolve.js";
10
+ import { defaultAdminPassPath, isLocalBase, resolveAdminPassFromSources, resolveAdminUser, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, ADMIN_PASS_HELP, } from "../lib/auth-resolve.js";
10
11
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
12
+ import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
11
13
  let cli;
12
14
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
13
15
  export function bindCli(fns) {
@@ -31,6 +33,34 @@ function resolveOpsPort(opts) {
31
33
  function applyAdminPassFile(opts) {
32
34
  cli.applyAdminPassFile(opts);
33
35
  }
36
+ /** `federation token` / `federation pair` credential flags (flair#1873).
37
+ * The flag/help strings live in auth-resolve.ts next to the resolver, shared
38
+ * with every sibling command's credential options (flair#1910). */
39
+ /**
40
+ * Resolve `federation token`/`pair`'s admin password through the SAME reader
41
+ * `flair backup` uses (`readAdminPassFileSecure`), with the precedence the
42
+ * usage text states: an explicit `--admin-pass-file` or `--admin-pass` over
43
+ * `FLAIR_ADMIN_PASS`; combining the file and the flag is a usage error. The resolved value is written back to
44
+ * `opts.adminPass`, the slot the ops preflight and `loadInstanceSecretKey`
45
+ * read — mirroring `applyAdminPassFile` for the sibling commands. Never prints
46
+ * the value.
47
+ */
48
+ function resolveFederationAdminPass(opts, envPass) {
49
+ try {
50
+ const pass = resolveAdminPassFromSources({
51
+ adminPassFile: opts.adminPassFile,
52
+ adminPass: opts.adminPass,
53
+ envPass,
54
+ });
55
+ if (pass)
56
+ opts.adminPass = pass;
57
+ return pass;
58
+ }
59
+ catch (err) {
60
+ console.error(`Error: ${err.message}`);
61
+ process.exit(1);
62
+ }
63
+ }
34
64
  function addSharedCredentialOptions(cmd) {
35
65
  return cli.addSharedCredentialOptions(cmd);
36
66
  }
@@ -109,17 +139,139 @@ const FEDERATION_PRIVATE_VISIBILITY = "private";
109
139
  function isFederationPrivateVisibility(visibility) {
110
140
  return visibility === FEDERATION_PRIVATE_VISIBILITY;
111
141
  }
142
+ /** The exact refusal sentence when nothing has reached the hub yet. */
143
+ const NOTHING_SENT_TO_HUB = "Nothing was sent to the hub; the pairing token is still valid.";
144
+ /** The post-hub failure sentence: the token is already spent. */
145
+ const PAIR_TOKEN_CONSUMED = "The pairing token has been consumed; mint a new one with 'flair federation token' on the hub and re-run pair.";
146
+ /** A rejected hub fetch may or may not have reached the hub, so be uncertain. */
147
+ const PAIR_TOKEN_MAYBE_CONSUMED = "The request may not have reached the hub; verify the pairing token there before re-minting one with 'flair federation token'.";
148
+ /**
149
+ * Strip any userinfo (user:password) and query string from a URL before printing
150
+ * it. An --ops-target like https://user:pass@host/?token=... must never put the
151
+ * credential or the query token on stderr.
152
+ */
153
+ export function redactUrl(u) {
154
+ try {
155
+ const url = new URL(u);
156
+ url.username = "";
157
+ url.password = "";
158
+ url.search = "";
159
+ return url.toString();
160
+ }
161
+ catch {
162
+ // Not a parseable absolute URL: strip a userinfo-looking prefix and any query.
163
+ return u.replace(/\/\/[^/@]*@/, "//").replace(/\?.*$/, "");
164
+ }
165
+ }
166
+ /**
167
+ * A fetch error's code or name — NEVER its message. Under Node a rejected
168
+ * fetch to a user-supplied URL can carry the full URL (credentials included)
169
+ * in err.message, so the message must never reach an error line.
170
+ */
171
+ function fetchErrorLabel(err) {
172
+ // Node's fetch wraps the OS error: the useful code (ECONNREFUSED, ENOTFOUND,
173
+ // …) is on err.cause.code, so prefer it over the wrapper's code/name.
174
+ const e = err;
175
+ const causeCode = typeof e?.cause?.code === "string" && e.cause.code ? e.cause.code : undefined;
176
+ const code = typeof e?.code === "string" && e.code ? e.code : undefined;
177
+ const name = typeof e?.name === "string" && e.name ? e.name : undefined;
178
+ return causeCode ?? code ?? name ?? "request failed";
179
+ }
180
+ /** Strip any userinfo from URLs embedded in a message before printing it. */
181
+ function redactMessage(text) {
182
+ return text.replace(/\/\/[^/@\s]+@/g, "//");
183
+ }
184
+ /**
185
+ * The one line `flair federation token` prints about its PairingToken rollback.
186
+ *
187
+ * A rollback is only real if Harper CONFIRMS the delete. A `delete` answers 200
188
+ * even when it removes nothing, naming what it removed in `deleted_hashes` and a
189
+ * record it did NOT remove in `skipped_hashes`; a body that names no ids at all
190
+ * is also not a confirmation. One rule, shared with the identity-row writes and
191
+ * the cleanup sweep — `writeConfirmed` (flair#1899). A confirmed rollback is
192
+ * reported as such; anything else is reported as a FAILED rollback that names
193
+ * the token by its 8-character prefix only.
194
+ */
195
+ export function pairingTokenRollbackLine(result, tokenId) {
196
+ const prefix = tokenId.slice(0, 8);
197
+ if (writeConfirmed(result, "deleted_hashes", tokenId)) {
198
+ // Only the delete is claimed. A LOST add_user response does not establish
199
+ // that the user was not created, so the line says nothing about it.
200
+ return `Rolled back pairing token ${prefix}…: Harper confirmed it was deleted.`;
201
+ }
202
+ const body = (result ?? {});
203
+ const why = body.error !== undefined && body.error !== null
204
+ ? `Harper reported: ${redactTokenMessage(String(body.error), [tokenId])}`
205
+ : Array.isArray(body.skipped_hashes) && body.skipped_hashes.map(String).includes(tokenId)
206
+ ? "Harper named it in skipped_hashes"
207
+ : "Harper's result did not name it as deleted";
208
+ // An unconfirmed delete is NOT proof the row survived: the response may have
209
+ // been lost. Report what is known (the delete is unconfirmed), not the state
210
+ // we cannot see.
211
+ return (`Pairing token rollback FAILED: Harper did not confirm that token ${prefix}… was deleted — ${why}. ` +
212
+ `A lost response does not mean the row survived; check the PairingToken table.`);
213
+ }
214
+ /**
215
+ * Delete the PairingToken a failed `flair federation token` persisted, and
216
+ * return the one-line outcome for the caller to print.
217
+ *
218
+ * Never throws: the caller is already failing, and its ORIGINAL error is what
219
+ * must reach the exit code, so a rollback that itself fails is reported, not
220
+ * raised. Sends `hash_values` (a list) — the field Harper's delete schema
221
+ * REQUIRES; the singular `hash_value` is refused with a 400, which left the
222
+ * token in the table so it outlived the user it was minted for (flair#1895).
223
+ */
224
+ export async function rollbackPairingToken(opsEndpoint, auth, tokenId) {
225
+ try {
226
+ const res = await fetch(`${opsEndpoint}/`, {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/json", Authorization: auth },
229
+ body: JSON.stringify({
230
+ operation: "delete",
231
+ database: "flair",
232
+ table: "PairingToken",
233
+ hash_values: [tokenId],
234
+ }),
235
+ signal: AbortSignal.timeout(10_000),
236
+ });
237
+ const result = await res.json().catch(() => null);
238
+ return pairingTokenRollbackLine(result, tokenId);
239
+ }
240
+ catch (err) {
241
+ return pairingTokenRollbackLine({ error: String(err?.message ?? err) }, tokenId);
242
+ }
243
+ }
244
+ /**
245
+ * Whether a Harper permission object can WRITE the Peer table: a super_user, or
246
+ * an explicit flair.Peer insert+update grant. A restrictive `operations`
247
+ * allowlist additionally gates the operation itself, so `upsert` must be
248
+ * permitted for any Peer write to reach the table. A read-only credential can
249
+ * search but not upsert, so the preflight must check this, not readability.
250
+ */
251
+ export function canWritePeerPermission(permission) {
252
+ if (permission?.super_user === true)
253
+ return true;
254
+ const operations = permission?.operations;
255
+ if (Array.isArray(operations) && !operations.includes("upsert") && !operations.includes("standard_user")) {
256
+ return false;
257
+ }
258
+ const peer = permission?.flair?.tables?.Peer;
259
+ return peer?.insert === true && peer?.update === true;
260
+ }
112
261
  async function loadInstanceSecretKey(instanceId, opts) {
113
262
  // Try keystore first
114
263
  const seed = keystore.getPrivateKeySeed(instanceId);
115
264
  if (seed) {
116
265
  return nacl.sign.keyPair.fromSeed(seed).secretKey;
117
266
  }
118
- // Fallback: check DB for legacy _keySeed
119
- const opsPort = resolveOpsPort(opts);
120
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
267
+ // Fallback: check DB for legacy _keySeed. Use the SAME three-source
268
+ // credential and the SAME resolved ops endpoint as the pair preflight, so a
269
+ // legacy-key spoke cannot pass preflight and then fail here for a different
270
+ // endpoint or a credential the fallback would not send.
271
+ const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
272
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
121
273
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
122
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
274
+ const res = await fetch(`${opsEndpoint}/`, {
123
275
  method: "POST",
124
276
  headers: { "Content-Type": "application/json", Authorization: auth },
125
277
  body: JSON.stringify({ operation: "search_by_value", schema: "flair", table: "Instance", search_attribute: "id", search_type: "equals", search_value: instanceId, get_attributes: ["*"] }),
@@ -1104,7 +1256,8 @@ export function register(program) {
1104
1256
  .command("pair <hub-url>")
1105
1257
  .description("Pair this spoke with a hub instance")
1106
1258
  .option("--port <port>", "Harper HTTP port")
1107
- .option("--admin-pass <pass>", "Admin password")
1259
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1260
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1108
1261
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1109
1262
  .option("--ops-port <port>", "Harper operations API port")
1110
1263
  .option("--token <token>", "One-time pairing token from hub admin (env: FLAIR_PAIRING_TOKEN) [deprecated: use --token-from]")
@@ -1113,22 +1266,39 @@ export function register(program) {
1113
1266
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")
1114
1267
  .action(async (hubUrl, opts) => {
1115
1268
  const target = resolveTarget(opts);
1269
+ // flair#1873: resolve the SPOKE admin credential FIRST, before any
1270
+ // request. `--admin-pass-file` is read in-process (mode 0600 enforced),
1271
+ // so a refusal sends nothing anywhere; combining it with --admin-pass is
1272
+ // a usage error. The value is written back into opts.adminPass, which the
1273
+ // ops preflight and the signing-key fallback below both read.
1274
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD);
1116
1275
  // One URL for the identity GET and the named error. resolveBaseUrl
1117
1276
  // honors --target / FLAIR_TARGET / FLAIR_URL / --port — the same host
1118
1277
  // the GET actually probes (do not cite resolveBaseUrl only in the
1119
1278
  // rewriter while api() falls through to resolveHttpPort({})).
1120
1279
  const identityUrl = resolveBaseUrl(opts).replace(/\/$/, "");
1280
+ // Set immediately before the hub's FederationPair request, so the outer
1281
+ // catch can say whether the one-time token may already be consumed.
1282
+ let hubContacted = false;
1121
1283
  try {
1122
1284
  // flair#820: the identity GET is pair's first step and is allowAdmin.
1123
1285
  // A 403 here is LOCAL (or --target REMOTE), never the hub handshake.
1124
1286
  // Rewrite Harper's raw AccessViolation into a named role/grant error.
1125
1287
  let instance;
1126
1288
  try {
1127
- instance = await api("GET", "/FederationInstance", undefined, { baseUrl: identityUrl });
1289
+ // flair#1873: hand the identity GET the credential the operator
1290
+ // provided (--admin-pass-file / --admin-pass), not only baseUrl — a
1291
+ // protected instance refuses this allowAdmin GET before pair ever
1292
+ // reaches the authenticated ops preflight.
1293
+ instance = await api("GET", "/FederationInstance", undefined, {
1294
+ baseUrl: identityUrl,
1295
+ explicitAdminPass: opts.adminPass,
1296
+ adminUser: opts.adminUser,
1297
+ });
1128
1298
  }
1129
1299
  catch (err) {
1130
1300
  throw rewriteFederationPairLocalAccessError(err, {
1131
- url: identityUrl,
1301
+ url: redactUrl(identityUrl),
1132
1302
  side: target ? "REMOTE" : "LOCAL",
1133
1303
  agentId: process.env.FLAIR_AGENT_ID,
1134
1304
  });
@@ -1162,6 +1332,65 @@ export function register(program) {
1162
1332
  console.error("Error: --token or --token-from is required. Ask the hub admin to run 'flair federation token' and provide the token.");
1163
1333
  process.exit(1);
1164
1334
  }
1335
+ // flair#1875: the SPOKE admin credential was resolved at the top of this
1336
+ // action (flair#1873) and preflighted BEFORE any request that consumes the
1337
+ // one-time token. The hub's FederationPair burns the token, so a missing or
1338
+ // refused admin credential must be caught here — while the token is still
1339
+ // valid — not after the hub has already paired us. Zero hub requests happen
1340
+ // on this path.
1341
+ if (!adminPass) {
1342
+ console.error("Error: refusing to contact the hub: the local hub-peer record needs admin auth to write — " +
1343
+ "pass --admin-pass-file (preferred), --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD (the SPOKE admin password), then re-run pair. " +
1344
+ NOTHING_SENT_TO_HUB);
1345
+ process.exit(1);
1346
+ }
1347
+ const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1348
+ const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1349
+ const safeOps = redactUrl(opsEndpoint);
1350
+ // Preflight the credential against the LOCAL ops API before the hub
1351
+ // request. user_info reports the credential's own role/permissions, so
1352
+ // this proves it can WRITE flair.Peer — a read-only credential can search
1353
+ // but is refused by the upsert, and by then the hub has burned the token.
1354
+ let preflightRes;
1355
+ try {
1356
+ preflightRes = await fetch(`${opsEndpoint}/`, {
1357
+ method: "POST",
1358
+ headers: { "Content-Type": "application/json", Authorization: auth },
1359
+ body: JSON.stringify({ operation: "user_info" }),
1360
+ signal: AbortSignal.timeout(10_000),
1361
+ });
1362
+ }
1363
+ catch (err) {
1364
+ // Never print err.message: a rejected fetch to the user-supplied ops
1365
+ // URL can carry the full URL (credentials included) in its message.
1366
+ console.error(`Error: could not reach the local ops API at ${safeOps} to preflight the spoke admin credential ` +
1367
+ `(${fetchErrorLabel(err)}). ${NOTHING_SENT_TO_HUB}`);
1368
+ process.exit(1);
1369
+ }
1370
+ if (preflightRes.status === 401 || preflightRes.status === 403) {
1371
+ console.error(`Error: the spoke admin credential was refused by the local ops API (${preflightRes.status}). ${NOTHING_SENT_TO_HUB}`);
1372
+ process.exit(1);
1373
+ }
1374
+ if (!preflightRes.ok) {
1375
+ console.error(`Error: the local ops API at ${safeOps} answered ${preflightRes.status} to user_info. ${NOTHING_SENT_TO_HUB}`);
1376
+ process.exit(1);
1377
+ }
1378
+ const userInfo = (await preflightRes.json().catch(() => null));
1379
+ const rolePermission = userInfo?.role?.permission;
1380
+ if (rolePermission === undefined || rolePermission === null) {
1381
+ console.error(`Error: user_info returned no role information. ${NOTHING_SENT_TO_HUB}`);
1382
+ process.exit(1);
1383
+ }
1384
+ // super_user is the supported credential. For a non-super_user role this
1385
+ // checks TABLE-level grants only (flair.Peer insert+update) plus the
1386
+ // operations allowlist; it cannot see attribute-level grants, so a role
1387
+ // with table access but restricted attributes still passes here and the
1388
+ // upsert may fail later (reported on the consumed-token path).
1389
+ if (!canWritePeerPermission(rolePermission)) {
1390
+ const roleName = userInfo?.role?.role ?? userInfo?.role?.name ?? "(unknown)";
1391
+ console.error(`Error: the spoke admin credential cannot write the Peer table (role ${roleName}). ${NOTHING_SENT_TO_HUB}`);
1392
+ process.exit(1);
1393
+ }
1165
1394
  // Load secret key and sign the pairing request.
1166
1395
  const secretKey = await loadInstanceSecretKey(instance.id, opts);
1167
1396
  const pairBody = {
@@ -1175,14 +1404,25 @@ export function register(program) {
1175
1404
  if (authHeader) {
1176
1405
  fetchHeaders.Authorization = authHeader;
1177
1406
  }
1178
- const res = await fetch(`${hubUrl}/FederationPair`, {
1179
- method: "POST",
1180
- headers: fetchHeaders,
1181
- body: JSON.stringify(signedBody),
1182
- });
1407
+ let res;
1408
+ try {
1409
+ hubContacted = true;
1410
+ res = await fetch(`${hubUrl}/FederationPair`, {
1411
+ method: "POST",
1412
+ headers: fetchHeaders,
1413
+ body: JSON.stringify(signedBody),
1414
+ });
1415
+ }
1416
+ catch (err) {
1417
+ // A rejected fetch to the user-supplied hub URL: name the error, never
1418
+ // print its message (it can carry the URL). The request was sent, so
1419
+ // the token may already be consumed.
1420
+ console.error(`Error: could not reach the hub at ${redactUrl(hubUrl)} (${fetchErrorLabel(err)}). ${PAIR_TOKEN_MAYBE_CONSUMED}`);
1421
+ process.exit(1);
1422
+ }
1183
1423
  if (!res.ok) {
1184
1424
  const text = await res.text().catch(() => "");
1185
- const hubDenial = rewriteFederationPairHubAccessError(res.status, hubUrl, text);
1425
+ const hubDenial = rewriteFederationPairHubAccessError(res.status, redactUrl(hubUrl), text);
1186
1426
  if (hubDenial) {
1187
1427
  console.error(`Error: ${hubDenial.message}`);
1188
1428
  process.exit(1);
@@ -1209,42 +1449,54 @@ export function register(program) {
1209
1449
  // never runs. Previously this was gated on `if (adminPass)` and the write
1210
1450
  // result was never checked — pairing with only an agent key (or a failed
1211
1451
  // upsert) left no peer behind a misleadingly green "✅ Paired".
1212
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
1213
- if (!adminPass) {
1214
- console.error("Error: paired on the hub, but the local hub-peer record needs admin auth to write — " +
1215
- "pass --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD, then re-run pair. " +
1216
- "Without it, 'flair federation sync' will report 'No hub peer configured'.");
1452
+ // flair#1875: the admin credential was resolved and preflighted BEFORE the
1453
+ // hub request, so reaching here means it was accepted. A rejected write
1454
+ // (or a failed upsert) is a genuine post-pair failure: the token is gone.
1455
+ let peerRes;
1456
+ try {
1457
+ peerRes = await fetch(`${opsEndpoint}/`, {
1458
+ method: "POST",
1459
+ headers: { "Content-Type": "application/json", Authorization: auth },
1460
+ body: JSON.stringify({
1461
+ operation: "upsert", database: "flair", table: "Peer",
1462
+ records: [{
1463
+ id: resolvedHub.peer.id,
1464
+ publicKey: resolvedHub.peer.publicKey,
1465
+ role: "hub", endpoint: hubUrl, status: "paired",
1466
+ pairedAt: new Date().toISOString(),
1467
+ createdAt: new Date().toISOString(),
1468
+ updatedAt: new Date().toISOString(),
1469
+ }],
1470
+ }),
1471
+ signal: AbortSignal.timeout(10_000),
1472
+ });
1473
+ }
1474
+ catch (err) {
1475
+ // A THROWN upsert (network error) after the hub returned 200 is the same
1476
+ // post-pair failure as an HTTP error: the token is already consumed.
1477
+ // Name the error, never print its message (the ops URL is user-supplied).
1478
+ console.error(`Error: paired on the hub, but writing the local hub-peer record failed ` +
1479
+ `(${fetchErrorLabel(err)}). ${PAIR_TOKEN_CONSUMED}`);
1217
1480
  process.exit(1);
1218
1481
  }
1219
- const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1220
- const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1221
- const peerRes = await fetch(`${opsEndpoint}/`, {
1222
- method: "POST",
1223
- headers: { "Content-Type": "application/json", Authorization: auth },
1224
- body: JSON.stringify({
1225
- operation: "upsert", database: "flair", table: "Peer",
1226
- records: [{
1227
- id: resolvedHub.peer.id,
1228
- publicKey: resolvedHub.peer.publicKey,
1229
- role: "hub", endpoint: hubUrl, status: "paired",
1230
- pairedAt: new Date().toISOString(),
1231
- createdAt: new Date().toISOString(),
1232
- updatedAt: new Date().toISOString(),
1233
- }],
1234
- }),
1235
- signal: AbortSignal.timeout(10_000),
1236
- });
1237
1482
  if (!peerRes.ok) {
1238
1483
  const text = await peerRes.text().catch(() => "");
1239
- console.error(`Error: paired with the hub but failed to write the local hub-peer record ` +
1240
- `(${peerRes.status} ${text.slice(0, 200)}). Ops endpoint: ${opsEndpoint}. ` +
1241
- `'flair federation sync' will not find the hub until this succeeds — check --admin-pass and the ops port.`);
1484
+ console.error(`Error: paired on the hub, but writing the local hub-peer record failed ` +
1485
+ `(${peerRes.status} ${text.slice(0, 200)}). ${PAIR_TOKEN_CONSUMED}`);
1242
1486
  process.exit(1);
1243
1487
  }
1244
1488
  console.log(`✅ Recorded hub as local peer: ${resolvedHub.peer.id} → ${hubUrl}`);
1245
1489
  }
1246
1490
  catch (err) {
1247
- console.error(`Error: ${err.message}`);
1491
+ // A rejected fetch to a user-supplied URL can carry the full URL —
1492
+ // credentials included — in err.message, so for fetch-shaped errors
1493
+ // print the code/name instead. Append whether the hub was contacted: if
1494
+ // the identity GET (or anything before the hub fetch) failed, nothing
1495
+ // reached the hub and the token is untouched.
1496
+ const tail = hubContacted ? PAIR_TOKEN_CONSUMED : NOTHING_SENT_TO_HUB;
1497
+ const name = typeof err?.name === "string" ? err.name : "";
1498
+ const fetchShaped = name === "TypeError" || name === "AbortError" || name === "TimeoutError";
1499
+ console.error(`Error: ${fetchShaped ? fetchErrorLabel(err) : redactMessage(String(err?.message ?? err))}. ${tail}`);
1248
1500
  process.exit(1);
1249
1501
  }
1250
1502
  });
@@ -1252,7 +1504,8 @@ export function register(program) {
1252
1504
  .command("token")
1253
1505
  .description("Generate a one-time pairing token (run on the hub)")
1254
1506
  .option("--port <port>", "Harper HTTP port")
1255
- .option("--admin-pass <pass>", "Admin password")
1507
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1508
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1256
1509
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1257
1510
  .option("--ops-port <port>", "Harper operations API port")
1258
1511
  .option("--ttl <minutes>", "Token TTL in minutes (default: 60)", "60")
@@ -1267,7 +1520,10 @@ export function register(program) {
1267
1520
  const ttlMinutes = parseInt(opts.ttl, 10) || 60;
1268
1521
  const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000).toISOString();
1269
1522
  const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1270
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1523
+ // flair#1873: read --admin-pass-file in-process (mode 0600 enforced);
1524
+ // an explicit --admin-pass-file or --admin-pass overrides FLAIR_ADMIN_PASS,
1525
+ // and file+flag is a usage error.
1526
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS);
1271
1527
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1272
1528
  // 1. Persist the PairingToken record
1273
1529
  const opsRes = await fetch(`${opsEndpoint}/`, {
@@ -1285,7 +1541,10 @@ export function register(program) {
1285
1541
  });
1286
1542
  if (!opsRes.ok) {
1287
1543
  const detail = await opsRes.text().catch(() => "");
1288
- throw new Error(`Failed to persist pairing token (${opsRes.status}): ${detail || "no body"}`);
1544
+ // Harper's error body can echo the upsert's record, whose `id` IS the
1545
+ // pairing token. Cut the token id to its prefix before it reaches the
1546
+ // thrown message, which this command's catch prints (flair#1902).
1547
+ throw new Error(`Failed to persist pairing token (${opsRes.status}): ${redactTokenMessage(detail || "no body", [token])}`);
1289
1548
  }
1290
1549
  // 2. Create bootstrap user for this token
1291
1550
  const bootstrapPassword = randomBytes(32).toString("base64url");
@@ -1306,33 +1565,17 @@ export function register(program) {
1306
1565
  });
1307
1566
  }
1308
1567
  catch (err) {
1309
- // Network failure creating bootstrap user — roll back PairingToken
1310
- await fetch(`${opsEndpoint}/`, {
1311
- method: "POST",
1312
- headers: { "Content-Type": "application/json", Authorization: auth },
1313
- body: JSON.stringify({
1314
- operation: "delete",
1315
- database: "flair",
1316
- table: "PairingToken",
1317
- hash_value: token,
1318
- }),
1319
- signal: AbortSignal.timeout(10_000),
1320
- }).catch(() => { });
1568
+ // Network failure creating bootstrap user — roll back PairingToken. The
1569
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1570
+ // original (network) failure below.
1571
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1321
1572
  throw new Error(`Failed to create bootstrap user (network): ${err.message}`);
1322
1573
  }
1323
1574
  if (!addUserRes.ok) {
1324
- // add_user failed — roll back PairingToken so the two stay in sync
1325
- await fetch(`${opsEndpoint}/`, {
1326
- method: "POST",
1327
- headers: { "Content-Type": "application/json", Authorization: auth },
1328
- body: JSON.stringify({
1329
- operation: "delete",
1330
- database: "flair",
1331
- table: "PairingToken",
1332
- hash_value: token,
1333
- }),
1334
- signal: AbortSignal.timeout(10_000),
1335
- }).catch(() => { });
1575
+ // add_user failed — roll back PairingToken so the two stay in sync. The
1576
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1577
+ // original add_user failure below.
1578
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1336
1579
  const detail = await addUserRes.text().catch(() => "");
1337
1580
  throw new Error(`Failed to create bootstrap user (${addUserRes.status}): ${detail || "no body"}`);
1338
1581
  }
@@ -1606,6 +1849,136 @@ export function register(program) {
1606
1849
  if (errors > 0)
1607
1850
  process.exit(1);
1608
1851
  });
1852
+ // ── flair federation instance — the identity row (flair#1883) ────────────
1853
+ //
1854
+ // A hub's identity is ONE `flair.Instance` row and the pairing-cleanup sweep
1855
+ // reads its role. `GET /FederationInstance` find-or-creates one, `flair init
1856
+ // --remote` used to insert a SECOND, and everything downstream that took "the
1857
+ // first row" then read whichever row the table yielded first. `list` shows the
1858
+ // rows; `prune` gets back to one.
1859
+ const instanceCmd = federation
1860
+ .command("instance")
1861
+ .description("Inspect and repair this instance's federation identity row");
1862
+ /** The ops endpoint these two subcommands read and write. */
1863
+ const instanceOpsEndpoint = (opts) => {
1864
+ // --admin-pass-file resolves into the same `adminPass` slot the inline flag
1865
+ // uses (the shared idiom: the secret stays out of ps and shell history).
1866
+ applyAdminPassFile(opts);
1867
+ const opsUrl = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1868
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1869
+ return { opsUrl, credentials: { user: resolveAdminUser(opts.adminUser), pass: adminPass } };
1870
+ };
1871
+ addSharedCredentialOptions(instanceCmd.command("list"))
1872
+ .description("List every Instance row on this instance (a hub should have exactly one)")
1873
+ .option("--port <port>", "Harper HTTP port")
1874
+ .option("--ops-port <port>", "Harper operations API port")
1875
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1876
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1877
+ .option("--json", "Emit JSON")
1878
+ .action(async (opts) => {
1879
+ let rows;
1880
+ try {
1881
+ rows = await readInstanceRows(instanceOpsEndpoint(opts));
1882
+ }
1883
+ catch (err) {
1884
+ console.error(`Error: ${err?.message ?? err}`);
1885
+ process.exit(1);
1886
+ }
1887
+ if (opts.json) {
1888
+ console.log(JSON.stringify({ rows }, null, 2));
1889
+ return;
1890
+ }
1891
+ if (rows.length === 0) {
1892
+ console.log("No Instance rows. This instance has no federation identity yet (it is created on the first `GET /FederationInstance`, or by `flair init --remote`).");
1893
+ return;
1894
+ }
1895
+ console.log(`${rows.length} Instance row(s):`);
1896
+ for (const row of rows)
1897
+ console.log(` ${formatInstanceRow(row)}`);
1898
+ if (rows.length > 1) {
1899
+ console.log(`\nMore than one row means there is no canonical identity. Keep one and delete the rest:`);
1900
+ console.log(` ${INSTANCE_ROW_PRUNE_REMEDY}`);
1901
+ }
1902
+ });
1903
+ addSharedCredentialOptions(instanceCmd.command("prune"))
1904
+ .description("Delete every Instance row except --keep <id> (dry-run by default)")
1905
+ .option("--keep <id>", "The Instance row to keep; the rest are deleted")
1906
+ .option("--apply", "Actually delete (default is dry-run)")
1907
+ .option("--port <port>", "Harper HTTP port")
1908
+ .option("--ops-port <port>", "Harper operations API port")
1909
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1910
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1911
+ .action(async (opts) => {
1912
+ const endpoint = instanceOpsEndpoint(opts);
1913
+ if (!opts.keep) {
1914
+ // No --keep: show what is there. Never guess which row is the identity —
1915
+ // the id and key peers know is the operator's fact, not this command's.
1916
+ try {
1917
+ const rows = await readInstanceRows(endpoint);
1918
+ if (rows.length === 0) {
1919
+ console.log("No Instance rows — nothing to prune.");
1920
+ return;
1921
+ }
1922
+ console.log(`${rows.length} Instance row(s):`);
1923
+ for (const row of rows)
1924
+ console.log(` ${formatInstanceRow(row)}`);
1925
+ console.error(`\nError: --keep <id> is required: name the row to keep.`);
1926
+ }
1927
+ catch (err) {
1928
+ console.error(`Error: ${err?.message ?? err}`);
1929
+ }
1930
+ process.exit(1);
1931
+ }
1932
+ let decision;
1933
+ try {
1934
+ decision = decideInstancePrune(await readInstanceRows(endpoint), opts.keep);
1935
+ }
1936
+ catch (err) {
1937
+ console.error(`Error: ${err?.message ?? err}`);
1938
+ process.exit(1);
1939
+ }
1940
+ if (decision.kind === "unknown-id") {
1941
+ console.error(`Error: --keep ${opts.keep} names no Instance row on this instance. Rows present:`);
1942
+ for (const row of decision.rows)
1943
+ console.error(` ${formatInstanceRow(row)}`);
1944
+ process.exit(1);
1945
+ }
1946
+ if (decision.kind === "nothing") {
1947
+ console.log(`Nothing to prune — --keep names the only Instance row this instance has.`);
1948
+ return;
1949
+ }
1950
+ // What a prune must tell the operator (flair#1883 round 3; tense
1951
+ // corrected in round 4): a paired peer pinned this instance's identity from
1952
+ // the `POST /FederationPair` response, which — while the table held several
1953
+ // rows — was whichever row the search yielded first. A peer that paired in
1954
+ // that state may have pinned ANY of the rows being deleted, and which one
1955
+ // it pinned is NOT determinable here, so the warning does not name one. (The
1956
+ // response is a 409 now, so this is history, not the current behaviour — but
1957
+ // those peers are still out there.) A peer paired with a deleted identity
1958
+ // must re-pair.
1959
+ const peerWarnings = prunePeerWarningLines({ drop: decision.drop });
1960
+ if (!opts.apply) {
1961
+ console.log(`── flair federation instance prune — dry-run (use --apply to delete) ──`);
1962
+ console.log(`Keeping ${formatInstanceRow(decision.keep)}`);
1963
+ console.log(`Would delete ${decision.drop.length} row(s):`);
1964
+ for (const row of decision.drop)
1965
+ console.log(` ${formatInstanceRow(row)}`);
1966
+ for (const line of peerWarnings)
1967
+ console.log(line);
1968
+ return;
1969
+ }
1970
+ try {
1971
+ const { dropped } = await pruneInstanceRows(endpoint, opts.keep);
1972
+ console.log(`Kept ${decision.keep.id}; deleted ${dropped.length} row(s): ${dropped.join(", ")}`);
1973
+ for (const line of peerWarnings)
1974
+ console.log(line);
1975
+ console.log("Re-run `flair init --remote` to set the kept row's role to hub.");
1976
+ }
1977
+ catch (err) {
1978
+ console.error(`Error: ${err?.message ?? err}`);
1979
+ process.exit(1);
1980
+ }
1981
+ });
1609
1982
  // `flair federation verify` — end-to-end roundtrip: write a tagged memory
1610
1983
  // locally, push it (bring-up has no daemon yet), probe peers for the tag.
1611
1984
  // Same class as fleet-verify / flair#988: 401/403 and unreachable are