@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,25 +1,37 @@
1
1
  import { Resource, databases, server } from "harper";
2
- import { randomBytes } from "node:crypto";
2
+ import { randomBytes, randomUUID } from "node:crypto";
3
3
  import nacl from "tweetnacl";
4
4
  import { allowAdmin } from "./agent-auth.js";
5
5
  import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce, } from "./federation-crypto.js";
6
6
  import { reconcileState } from "./relay-lib.js";
7
+ import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY, multipleInstanceRowsMessage, } from "../src/lib/instance-identity-row.js";
8
+ import { readAllInstanceRows } from "./instance-identity-rows.js";
9
+ import { findOrCreateInstance } from "./instance-create-lock.js";
10
+ import { withDetachedTxnAsync } from "./table-helpers.js";
7
11
  import { isSkillWrite } from "./skill-write.js";
12
+ import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declared-attributes.js";
8
13
  import { noteWriteStamp } from "./embedding-space-guard.js";
9
14
  import { initFederationCleanup } from "./federation-cleanup.js";
10
- import { createPersistentNonceStore, initNonceStoreCleanup } from "./federation-nonce-store.js";
15
+ import { verifyFederationRequestBody } from "./replay-store.js";
11
16
  import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, } from "./federation-classify.js";
12
17
  export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
13
- // Module-level nonce store for federation anti-replay.
14
- // Shared across FederationPair + FederationSync — nonces are globally unique
15
- // (generated by signBodyFresh per request with 128-bit random nonces).
16
- //
17
- // Backed by the `Nonce` table (federation-edge-hardening slice 4) so a
18
- // process restart doesn't wipe recently-seen nonces within the ±30s
19
- // freshness window — see federation-nonce-store.ts for the full design.
20
- // The NonceStore interface (has/set/evict) stays synchronous, so this swap
21
- // requires NO change to verifyBodySignatureFresh or its 2 call sites below.
22
- const federationNonceStore = createPersistentNonceStore();
18
+ // Federation anti-replay: FederationPair and FederationSync both verify through
19
+ // verifyFederationRequestBody (resources/replay-store.ts), which claims each
20
+ // body nonce ONCE in the instance-wide `ReplayNonce` table after the signature
21
+ // has verified (flair#2061). Nonces are globally unique (signBodyFresh generates
22
+ // a 128-bit random nonce per request), so the nonce alone is the key.
23
+ /** The response for a body whose signature, freshness or nonce check refused. */
24
+ function federationVerifyRefusal(reason) {
25
+ if (reason === "replay_store_unavailable") {
26
+ return new Response(JSON.stringify({
27
+ error: "replay_store_unavailable",
28
+ detail: "This instance cannot record request nonces right now, so it refuses signed federation requests. The server log names the cause.",
29
+ }), { status: 503, headers: { "content-type": "application/json" } });
30
+ }
31
+ return new Response(JSON.stringify({ error: `invalid signature — ${reason}` }), {
32
+ status: 401, headers: { "content-type": "application/json" },
33
+ });
34
+ }
23
35
  // Re-export for consumers that import from Federation.ts
24
36
  export { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce };
25
37
  // ─── Per-record signature enforcement mode (federation-edge-hardening slice 3b) ──
@@ -53,11 +65,18 @@ function requireRecordPrincipal() {
53
65
  }
54
66
  // ─── Conflict resolution ─────────────────────────────────────────────────────
55
67
  /**
56
- * Field-level Last-Write-Wins merge.
57
- * For each field, the value with the later `updatedAt` wins.
68
+ * The row written is `record.data`, but the row checked (and merged against) is
69
+ * `record.id`. The payload must carry that same id, or the record is not applied.
70
+ */
71
+ export function payloadIdMismatch(record) {
72
+ return !record.data || record.data.id !== record.id;
73
+ }
74
+ /**
75
+ * Record-level Last-Write-Wins merge.
76
+ * Incoming fields are applied when the remote record's updatedAt is later.
58
77
  * Records with no local counterpart are accepted directly.
59
78
  */
60
- function mergeRecord(local, remote) {
79
+ export function mergeRecord(local, remote) {
61
80
  if (!local)
62
81
  return remote.data;
63
82
  const merged = { ...local };
@@ -67,7 +86,11 @@ function mergeRecord(local, remote) {
67
86
  // Field-level LWW is the spec target but record-level is sufficient
68
87
  // for the initial implementation and avoids per-field clock tracking.
69
88
  if (remoteUpdated > localUpdated) {
70
- Object.assign(merged, remote.data);
89
+ // Preserve stored visibility on updates before applying write policy.
90
+ const incoming = { ...remote.data };
91
+ if (incoming.visibility === null || incoming.visibility === undefined)
92
+ delete incoming.visibility;
93
+ Object.assign(merged, incoming);
71
94
  merged.updatedAt = remoteUpdated;
72
95
  }
73
96
  return merged;
@@ -97,91 +120,184 @@ export function noteFederationMergedMemory(recordTable, mergedData) {
97
120
  }
98
121
  }
99
122
  // ─── Instance identity ───────────────────────────────────────────────────────
123
+ /**
124
+ * Every `flair.Instance` row on this instance, or a THROWN error — the ONE
125
+ * strict reader (resources/instance-identity-rows.ts), re-exported here so
126
+ * existing consumers keep importing it from the Federation resource.
127
+ *
128
+ * The readers used to take the first row `search()` yielded. `search()` order is
129
+ * not a fact about an identity: on a table with two rows one reader reported one
130
+ * identity and a pairing peer was handed the other, and which was which depended
131
+ * on the table's internal ordering (flair#1883 round 3).
132
+ *
133
+ * A read that FAILS must not look like a table with no rows: the callers answer
134
+ * 5xx and write nothing, because only a SUCCESSFUL read of zero rows may mint an
135
+ * identity.
136
+ *
137
+ * And neither must a row the reader cannot NAME (flair#1883 round 4): an entry
138
+ * without a usable id used to be skipped here, so a table serving one bad entry
139
+ * (or a good one beside it) read as "the rows I could name" — possibly zero — and
140
+ * the GET's create branch could mint a second identity from a read that never
141
+ * saw the table. `readableInstanceRows` throws instead, which the callers map to
142
+ * 5xx and no write.
143
+ */
144
+ export { readAllInstanceRows };
100
145
  /**
101
146
  * GET /FederationInstance — return this instance's identity.
102
- * Used by peers during pairing and by the admin UI.
147
+ *
148
+ * The admin UI and CLI tooling read it. Peers do NOT read it while pairing: a
149
+ * spoke is handed this instance's identity in the `POST /FederationPair`
150
+ * response, which FederationPair.post() builds server-side by reading the
151
+ * Instance table directly. (The pair CLI must not GET this path to fill a missing
152
+ * pair publicKey either — flair#822: allowRead is allowAdmin, and get() creates an
153
+ * identity when it finds none, which would invent a hub row; #839.)
103
154
  *
104
155
  * allowRead()=allowAdmin (defense-in-depth, authorizeLocal-escalation-class
105
156
  * follow-up to #601/#604/#609/#612 — flair#614's backstop found this one had
106
157
  * NO allow* at all, so Harper's own default — `user?.role.permission.
107
158
  * super_user`, satisfiable only by a genuine admin OR authorizeLocal's forged
108
- * loopback super_user — was silently standing in). Same idiom as
109
- * AdminInstance.ts/AdminDashboard.ts: this is an admin-view endpoint (peers
110
- * never call it during pairing — FederationPair.post() reads the Instance
111
- * table directly server-side to hand a peer our identity; this HTTP GET is
112
- * CLI tooling only). The spoke pair CLI must not GET this path to fill a
113
- * missing pair publicKey (flair#822): allowRead is allowAdmin, and get()
114
- * find-or-creates an Instance (that would invent a hub row; #839).
159
+ * loopback super_user — was silently standing in).
160
+ *
161
+ * With SEVERAL rows there is no single identity to report, so this answers 409
162
+ * naming every row and the prune. It never reports the row the search happened
163
+ * to yield first (flair#1883 round 3).
115
164
  */
116
165
  export class FederationInstance extends Resource {
117
166
  async allowRead() {
118
167
  return allowAdmin(this.getContext?.());
119
168
  }
120
169
  async get() {
121
- // Find or create instance identity
122
- let instance = null;
170
+ // Find or create instance identity.
171
+ //
172
+ // A read that did not happen is an ERROR, never "no row" (flair#1883 round 2).
173
+ // This used to log and fall through to the create branch: on a persistent
174
+ // storage or permission failure the GET then MINTED A SECOND identity row on
175
+ // every call, and which identity this instance reported depended on which row
176
+ // `search()` yielded first. Only a SUCCESSFUL read that returns zero rows may
177
+ // create.
178
+ // Every row, not the first one (flair#1883 round 3): with several rows the
179
+ // first is a coin toss, and reporting one identity here while a peer is
180
+ // handed another is how the two writers disagreed in the first place.
181
+ let rows = null;
182
+ let readError = null;
123
183
  try {
124
- for await (const i of databases.flair.Instance.search()) {
125
- instance = i;
126
- break;
127
- }
184
+ rows = await readAllInstanceRows();
128
185
  }
129
186
  catch (err) {
130
- // Expected on genuine first boot: the Instance table doesn't exist yet,
131
- // and the create branch below handles that. But a bare swallow here also
132
- // hid every OTHER read failure (storage, permissions), making a
133
- // persistently failing read indistinguishable from first boot
134
- // (flair#1233). Log the error class so the two are tellable apart in
135
- // server logs; behavior is unchanged — fall through to create.
136
- console.warn("[federation] Instance read failed — proceeding as first boot (create branch will run). " +
137
- "If this instance already has an identity, this is a real read error, not an absent table. " +
138
- `${err?.constructor?.name ?? "Error"}: ${err?.message ?? err}`);
187
+ readError = err;
188
+ }
189
+ if (readError) {
190
+ // 5xx: the caller retries, and a retry that finally reads is the only thing
191
+ // that creates. flair#1233's warn stays — the error class belongs in the
192
+ // server log — but it is no longer a licence to write.
193
+ console.error("[federation] GET /FederationInstance could not read the Instance table — answering 503 and creating NOTHING. " +
194
+ "A read error is not first boot; minting an identity here would add a second row to an instance that already has one. " +
195
+ `${readError?.constructor?.name ?? "Error"}: ${readError?.message ?? readError}`);
196
+ return new Response(JSON.stringify({
197
+ error: "instance_identity_unreadable",
198
+ detail: "The Instance table could not be read, so this instance's identity is unknown. Nothing was created.",
199
+ }), { status: 503, headers: { "content-type": "application/json" } });
139
200
  }
201
+ const decision = decideInstanceAnswer(rows);
202
+ if (decision.kind === "refuse-multiple") {
203
+ // 409: several rows means there is no canonical identity, and reporting
204
+ // one of them would be exactly the coin toss #1883 exists to end — a peer
205
+ // could go on to pin it. Nothing is created and nothing is deleted; the
206
+ // operator resolves the table with the prune this names.
207
+ console.error(`[federation] GET /FederationInstance found ${decision.rows.length} Instance rows — answering 409 and creating NOTHING. ` +
208
+ "Which row this instance reports must not depend on which row the search yields first.");
209
+ return new Response(JSON.stringify({
210
+ error: "multiple_instance_rows",
211
+ detail: multipleInstanceRowsMessage(decision.rows, "GET /FederationInstance"),
212
+ rows: decision.rows,
213
+ }), { status: 409, headers: { "content-type": "application/json" } });
214
+ }
215
+ let instance = decision.kind === "answer" ? decision.row : null;
140
216
  // Runtime-only signal (flair#1233): whether this instance's private key
141
217
  // seed is present in the keystore, i.e. whether it can SIGN (pair/sync).
142
218
  // Deliberately NOT persisted — the Instance.status enum is
143
219
  // schema-constrained and this is transient machine state; recomputed on
144
220
  // every GET.
145
221
  let signingKeyAvailable = false;
146
- if (!instance) {
147
- // First boot — generate instance identity
148
- const kp = nacl.sign.keyPair();
149
- const id = `flair_${randomBytes(4).toString("hex")}`;
150
- const publicKey = Buffer.from(kp.publicKey).toString("base64url");
151
- instance = {
152
- id,
153
- publicKey,
154
- role: "spoke", // default; hub is set during `flair init --remote`
155
- status: "active",
156
- createdAt: new Date().toISOString(),
157
- updatedAt: new Date().toISOString(),
158
- };
159
- await databases.flair.Instance.put(instance);
160
- // Store private key seed in encrypted keystore (not in DB).
161
- //
162
- // flair#1233: a keystore failure no longer aborts the GET. This is a
163
- // READ path — the response never uses the private key, and the old
164
- // throw here left federation state entirely unobservable on hosts
165
- // whose HOME isn't writable (the #812 ENOTDIR class; keysDir() is
166
- // homedir()-relative). Fail-closed stays where the key is USED:
167
- // signing, in pair/sync, still throws when the key is absent. Here the
168
- // failure is logged server-side and surfaced to the caller as
169
- // signingKeyAvailable:false. Plaintext keys still never touch the DB.
170
- try {
171
- const { keystore } = await import("../src/keystore.js");
172
- const seed = kp.secretKey.slice(0, 32);
173
- keystore.setPrivateKeySeed(id, seed);
174
- signingKeyAvailable = true;
222
+ if (decision.kind === "none") {
223
+ // First boot: the read OUTSIDE the lock found no row. The create runs in the
224
+ // filesystem bakery critical section (flair#1897) — shared by EVERY HTTP
225
+ // worker of this process AND every process on this Flair home: a read taken
226
+ // UNDER the lock, the mint, the put, the keystore seed and a confirming
227
+ // re-read — so two concurrent first-boot GETs mint ONE row and both are
228
+ // answered with it. A GET that found a row above never reaches here, so
229
+ // reads stay concurrent.
230
+ const outcome = await findOrCreateInstance({
231
+ // Detach the request's transaction for EVERY read inside the lock: the
232
+ // outer read above opened the request's transaction BEFORE this create, so
233
+ // reusing it here would read the pre-create snapshot and mint a second row
234
+ // even serialised (the table-helpers.ts class). A fresh transaction sees
235
+ // the row the prior lock holder committed.
236
+ readAll: () => withDetachedTxnAsync(this.getContext?.(), () => readAllInstanceRows()),
237
+ // Commit the WRITE before the lock releases: both the row put and the
238
+ // keystore seed run in a DETACHED transaction, so Harper builds a fresh
239
+ // ImmediateTransaction that commits on its own rather than at the end of
240
+ // the request (the lock cannot serialise a write that commits after the
241
+ // method returns — the earlier BLOCKED finding, flair#1897 slice 1).
242
+ put: (row) => withDetachedTxnAsync(this.getContext?.(), () => databases.flair.Instance.put(row)),
243
+ setSeed: (createdId, seed) => withDetachedTxnAsync(this.getContext?.(), async () => {
244
+ const { keystore } = await import("../src/keystore.js");
245
+ keystore.setPrivateKeySeed(createdId, seed);
246
+ }),
247
+ seedPresent: async (rowId) => {
248
+ try {
249
+ const { keystore } = await import("../src/keystore.js");
250
+ return keystore.getPrivateKeySeed(rowId) !== null;
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ },
256
+ mint: () => {
257
+ const kp = nacl.sign.keyPair();
258
+ return {
259
+ id: `flair_${randomBytes(4).toString("hex")}`,
260
+ publicKey: Buffer.from(kp.publicKey).toString("base64url"),
261
+ secretKey: kp.secretKey,
262
+ };
263
+ },
264
+ });
265
+ if (outcome.kind === "refuse-multiple") {
266
+ if (outcome.putCommitted) {
267
+ // This request's OWN detached put committed a row AND the table holds >1.
268
+ console.error(`[federation] GET /FederationInstance: this request committed row ${outcome.mintedId}; the table now holds ` +
269
+ `${outcome.rows.length} rows — hand to ${INSTANCE_ROW_PRUNE_REMEDY}.`);
270
+ return new Response(JSON.stringify({
271
+ error: "multiple_instance_rows",
272
+ detail: multipleInstanceRowsMessage(outcome.rows, "GET /FederationInstance"),
273
+ rows: outcome.rows,
274
+ }), { status: 409, headers: { "content-type": "application/json" } });
275
+ }
276
+ // Pre-put (the read before or the first in-lock read) — nothing created.
277
+ console.error(`[federation] GET /FederationInstance found ${outcome.rows.length} Instance rows under the create lock — answering 409 and creating NOTHING.`);
278
+ return new Response(JSON.stringify({
279
+ error: "multiple_instance_rows",
280
+ detail: multipleInstanceRowsMessage(outcome.rows, "GET /FederationInstance"),
281
+ rows: outcome.rows,
282
+ }), { status: 409, headers: { "content-type": "application/json" } });
175
283
  }
176
- catch (err) {
177
- console.error("[federation] Could not store the federation signing key seed in the keystore " +
178
- "($HOME/.flair/keys, relative to the Harper process's HOME). The identity row was created and " +
179
- "reads work, but this instance cannot sign — pair/sync will fail until the keystore is fixed. " +
180
- "Remedy: make $HOME/.flair/keys a directory writable by the Harper process (mode 0700). " +
181
- "The seed for THIS identity was never stored, so after fixing the keystore, re-key: delete the " +
182
- "Instance row and re-pair to mint a fresh identity. " +
183
- `${err?.constructor?.name ?? "Error"}: ${err?.message ?? err}`);
284
+ if (outcome.kind === "refuse-unobservable") {
285
+ console.error(`[federation] GET /FederationInstance: minted ${outcome.mintedId} but the confirming re-read saw NO row — ` +
286
+ `the detached write was not observable. Refusing (no retry).`);
287
+ return new Response(JSON.stringify({
288
+ error: "instance_identity_unobservable",
289
+ detail: `This instance minted ${outcome.mintedId} but could not read it back — the write did not commit where expected. ` +
290
+ `Nothing is answered. Retry; if it persists, inspect the flair.Instance table.`,
291
+ }), { status: 503, headers: { "content-type": "application/json" } });
184
292
  }
293
+ if (outcome.kind === "refuse-lock") {
294
+ console.error(`[federation] GET /FederationInstance: ${outcome.detail}`);
295
+ return new Response(JSON.stringify({ error: "instance_create_lock_unavailable", detail: outcome.detail }), { status: 503, headers: { "content-type": "application/json" } });
296
+ }
297
+ if (outcome.warning)
298
+ console.error(`[federation] ${outcome.warning}`);
299
+ instance = outcome.row;
300
+ signingKeyAvailable = outcome.seeded;
185
301
  }
186
302
  else {
187
303
  // Existing identity: report whether its signing key is present and
@@ -236,14 +352,58 @@ export class FederationPair extends Resource {
236
352
  status: 401, headers: { "content-type": "application/json" },
237
353
  });
238
354
  }
239
- const verifyResult = verifyBodySignatureFresh(data, publicKey, {
240
- windowMs: 30_000,
241
- nonceStore: federationNonceStore,
242
- });
243
- if (!verifyResult.ok) {
244
- return new Response(JSON.stringify({ error: `invalid signature — ${verifyResult.reason}` }), {
245
- status: 401, headers: { "content-type": "application/json" },
246
- });
355
+ const verifyResult = await verifyFederationRequestBody(data, publicKey);
356
+ if (!verifyResult.ok)
357
+ return federationVerifyRefusal(verifyResult.reason);
358
+ // ── The identity this response hands the peer, decided BEFORE the pairing
359
+ // token is consumed, BEFORE the peer is read and before ANY peer is written
360
+ // (flair#1883 round 3). ──────────────────────────────────────────────────
361
+ //
362
+ // NOT "before anything": the signature check above has already run and
363
+ // RECORDED ITS NONCE (verifyFederationRequestBody → the ReplayNonce table,
364
+ // see replay-store.ts). That is deliberate anti-replay state, not a
365
+ // pairing effect — but it is written, and the refusal is precise about what
366
+ // it precedes.
367
+ //
368
+ // A spoke PINS what it is handed here as its hub peer, so this value is the
369
+ // identity a pairing outcome depends on. It used to be "the first row of an
370
+ // unordered search", read AFTER the pairing token was consumed and the peer
371
+ // written — so a hub holding two rows could burn a one-time token, record the
372
+ // new peer, and only then answer with whichever row the table yielded first.
373
+ // The read now comes first, and an unreadable table or several rows refuse
374
+ // with the token still unused and NO peer written.
375
+ let identityRows = null;
376
+ try {
377
+ identityRows = await readAllInstanceRows();
378
+ }
379
+ catch (err) {
380
+ console.error("[federation] POST /FederationPair could not read the Instance table — answering 503, consuming NO token and writing NO peer. " +
381
+ `${err?.constructor?.name ?? "Error"}: ${err?.message ?? err}`);
382
+ return new Response(JSON.stringify({
383
+ error: "instance_identity_unreadable",
384
+ detail: "The Instance table could not be read, so this hub's identity is unknown. Nothing was paired: the pairing token is unconsumed and no peer was written.",
385
+ }), { status: 503, headers: { "content-type": "application/json" } });
386
+ }
387
+ const identity = decideInstanceAnswer(identityRows);
388
+ if (identity.kind === "refuse-multiple") {
389
+ // 409: with several rows there is no identity this hub can hand a peer
390
+ // without picking one, and the peer would pin the pick. Refuse before the
391
+ // token is consumed and before any Peer row is written.
392
+ //
393
+ // This route is PUBLIC, and this refusal runs before the pairing token or
394
+ // a re-pairing peer's key is checked: any caller with a self-signed body
395
+ // reaches it. So the answer names no row. Each row's id, role and
396
+ // createdAt go to this hub's log; the caller learns only what it can act
397
+ // on: pairing is blocked on the hub side, and the hub's operator resolves
398
+ // it with the prune, which needs admin credentials.
399
+ console.error(`[federation] POST /FederationPair answering 409, consuming NO token and writing NO peer. ` +
400
+ multipleInstanceRowsMessage(identity.rows, "POST /FederationPair"));
401
+ return new Response(JSON.stringify({
402
+ error: "multiple_instance_rows",
403
+ detail: "This hub has more than one Instance row, so it has no single identity to hand a peer. Nothing was paired: " +
404
+ "the pairing token is unconsumed and no peer was written. The hub's operator must keep one row and delete the rest with: " +
405
+ INSTANCE_ROW_PRUNE_REMEDY,
406
+ }), { status: 409, headers: { "content-type": "application/json" } });
247
407
  }
248
408
  // Check if already paired (re-pairing doesn't need a token)
249
409
  const existing = await databases.flair.Peer.get(instanceId);
@@ -327,25 +487,17 @@ export class FederationPair extends Resource {
327
487
  console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
328
488
  }
329
489
  }
330
- // Return our own identity for the peer to record. Already
331
- // `{ id, publicKey, role }` when an Instance row exists (flair#213).
332
- // `instance: null` means the hub has no FederationInstance — that is
333
- // #839, not a pair-response-shape bug. The spoke must ERROR, never
490
+ // Return our own identity for the peer to record — `{ id, publicKey, role }`,
491
+ // decided BEFORE the token was consumed (above; flair#1883 round 3). An
492
+ // `instance` of `null` means a SUCCESSFUL read found no FederationInstance:
493
+ // that is #839, not a pair-response-shape bug. The spoke must ERROR, never
334
494
  // store publicKey:"" (flair#822).
335
- let ourInstance = null;
336
- try {
337
- for await (const i of databases.flair.Instance.search()) {
338
- ourInstance = i;
339
- break;
340
- }
341
- }
342
- catch { }
343
495
  return {
344
496
  paired: true,
345
- instance: ourInstance ? {
346
- id: ourInstance.id,
347
- publicKey: ourInstance.publicKey,
348
- role: ourInstance.role,
497
+ instance: identity.kind === "answer" ? {
498
+ id: identity.row.id,
499
+ publicKey: identity.row.publicKey,
500
+ role: identity.row.role,
349
501
  } : null,
350
502
  };
351
503
  }
@@ -358,7 +510,7 @@ export class FederationPair extends Resource {
358
510
  */
359
511
  export class FederationSync extends Resource {
360
512
  // Public endpoint by design: spokes have no Harper credentials. Body signature
361
- // (with timestamp + nonce, via verifyBodySignatureFresh) is the auth boundary.
513
+ // (with timestamp + nonce, via verifyFederationRequestBody) is the auth boundary.
362
514
  // Same pattern as FederationPair.
363
515
  allowCreate(_user, _record, _context) {
364
516
  return true;
@@ -385,15 +537,9 @@ export class FederationSync extends Resource {
385
537
  status: 401, headers: { "content-type": "application/json" },
386
538
  });
387
539
  }
388
- const verifyResult = verifyBodySignatureFresh(data, peer.publicKey, {
389
- windowMs: 30_000,
390
- nonceStore: federationNonceStore,
391
- });
392
- if (!verifyResult.ok) {
393
- return new Response(JSON.stringify({ error: `invalid signature — ${verifyResult.reason}` }), {
394
- status: 401, headers: { "content-type": "application/json" },
395
- });
396
- }
540
+ const verifyResult = await verifyFederationRequestBody(data, peer.publicKey);
541
+ if (!verifyResult.ok)
542
+ return federationVerifyRefusal(verifyResult.reason);
397
543
  const startTime = Date.now();
398
544
  let merged = 0;
399
545
  let skipped = 0;
@@ -431,6 +577,10 @@ export class FederationSync extends Resource {
431
577
  const knownTables = new Set(Object.keys(tableMap));
432
578
  for (const record of records) {
433
579
  try {
580
+ if (payloadIdMismatch(record)) {
581
+ recordSkip("id_mismatch");
582
+ continue;
583
+ }
434
584
  const table = (record.table in tableMap)
435
585
  ? tableMap[record.table]
436
586
  : undefined;
@@ -444,7 +594,7 @@ export class FederationSync extends Resource {
444
594
  // classifyRecord's "merge" verdict above only proves the record is
445
595
  // STRUCTURALLY eligible (known table, self-originated OR the sender
446
596
  // is a hub, not stale, not a no-op) — that hub bypass trusts the
447
- // BATCH-level signature (verifyBodySignatureFresh above, verified
597
+ // BATCH-level signature (verifyFederationRequestBody above, verified
448
598
  // against the SENDER's pinned key). It does NOT prove the record's
449
599
  // *claimed* originator actually produced it — a hub relaying on
450
600
  // behalf of many spokes could otherwise forge a record under any
@@ -502,6 +652,15 @@ export class FederationSync extends Resource {
502
652
  continue;
503
653
  }
504
654
  const mergedData = mergeRecord(local, record);
655
+ // ── flair#1940 A1'' item 8: the SAME declared-attribute whitelist the
656
+ // writers apply. A dirty pushed row (a legacy direct-insert, or a raw
657
+ // writer that slipped a pointer field past the writers) must not carry
658
+ // a pointer attribute onto the merged Memory row here either. The named
659
+ // federation bookkeeping fields (_originatorInstanceId, _syncedFrom,
660
+ // _syncedAt, meta, kind) are on the whitelist and survive.
661
+ if (record.table === "Memory") {
662
+ stripInboundMemoryRow(mergedData);
663
+ }
505
664
  // ── flair#1542: skills are not federated ──
506
665
  // A skill-tagged Memory is a local, gated artifact (SkillScan + forced
507
666
  // durability on the write path). Merging a pushed skill-tagged row RAW
@@ -538,6 +697,33 @@ export class FederationSync extends Resource {
538
697
  mergedData._originatorInstanceId = decision.originator;
539
698
  mergedData._syncedFrom = instanceId;
540
699
  mergedData._syncedAt = new Date().toISOString();
700
+ // Re-assert the whitelist AFTER stamping the bookkeeping fields, so a
701
+ // dirty inbound row cannot smuggle a pointer field through this merge
702
+ // even if it also carried one of the allowed keys.
703
+ if (record.table === "Memory") {
704
+ stripInboundMemoryRow(mergedData);
705
+ // A1-iv items 1/3: a federated receive is a LOCAL incarnation — the
706
+ // token is OURS, never the peer's. Drop a peer-supplied server-stamped
707
+ // field, then PRESERVE the local row's token on a merge (a new row
708
+ // gets a locally-generated one).
709
+ //
710
+ // Round 22: `provenance` is NOT a local incarnation stamp — it is the
711
+ // ORIGINATOR's signed stamp and must survive the merge. Capture the
712
+ // value mergeRecord SELECTED (the inbound data for a new row; the
713
+ // merge's LWW choice for an update — NOT always local.provenance)
714
+ // before stripping, then restore it in the same per-record apply.
715
+ // Pinned by test/unit-isolated/federation-merge-provenance.test.ts —
716
+ // RED if this capture/restore is removed.
717
+ const mergedProvenance = mergedData.provenance;
718
+ stripServerStampedFields(mergedData);
719
+ if (typeof mergedProvenance === "string") {
720
+ mergedData.provenance = mergedProvenance;
721
+ }
722
+ mergedData.instanceToken =
723
+ local && typeof local.instanceToken === "string" && local.instanceToken.length > 0
724
+ ? local.instanceToken
725
+ : randomUUID();
726
+ }
541
727
  await table.put(mergedData);
542
728
  // embedding-space-guard slice 1: a federation-merged Memory can carry a
543
729
  // FOREIGN embeddingModel (LWW remote-win) — trip the guard's latch so
@@ -660,21 +846,7 @@ if (typeof setTimeout !== "undefined") {
660
846
  // Swallow — in test/resource-env the Harper databases may not be bound.
661
847
  // In production, initFederationCleanup handles its own error paths.
662
848
  });
663
- // Nonce store hydration (slice 4) — load nonces persisted by a previous
664
- // process (if any) before this instance starts guarding live traffic.
665
- // Runs on the same deferred tick as the cleanup sweep above; there is a
666
- // narrow window between process start and hydration completing during
667
- // which a pre-restart nonce isn't yet visible — an accepted tradeoff
668
- // consistent with this file's existing deferred-init pattern (see the
669
- // cleanup sweep comment above).
670
- federationNonceStore.hydrate().catch((err) => {
671
- // Swallow — in test/resource-env the Harper databases may not be bound.
672
- });
673
- // Nonce table eviction sweep — runs on every instance (both hub and
674
- // spoke can be the receiving/verifying side of a signed federation
675
- // request), unlike PairingToken cleanup which is hub-only.
676
- initNonceStoreCleanup().catch((err) => {
677
- // Swallow — in test/resource-env the Harper databases may not be bound.
678
- });
849
+ // Nonce eviction is the ReplayNonce table's own expiration (one scan per
850
+ // instance, on Harper's last worker) — no sweep is started here.
679
851
  }, 0);
680
852
  }
@@ -1,6 +1,12 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
+ import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
5
+ // Owner-only read scope, applied through the shared by-id gate and scoped search
6
+ // (resources/record-type-kit.ts).
7
+ const integrationReadScope = makeReadScope("owner-only", "agentId");
8
+ const integrationByIdReadGate = makeByIdReadGate(integrationReadScope);
9
+ const integrationScopedSearch = makeScopedSearch(integrationReadScope);
4
10
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
5
11
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
6
12
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -33,30 +39,7 @@ export class Integration extends databases.flair.Integration {
33
39
  * integration ids.
34
40
  */
35
41
  async get(target) {
36
- // Collection / query reads arrive as a RequestTarget with
37
- // `isCollection === true`, and are governed by search() (same owner
38
- // scoping). Only a genuine by-id get is ownership-checked below — see
39
- // Memory.ts's get() for the full rationale (same bug class).
40
- if (!target || (typeof target === "object" && target.isCollection)) {
41
- return this.search(target);
42
- }
43
- const auth = await this._auth();
44
- // Anonymous by-id read is already blocked at the allowRead() gate (403);
45
- // this is defense-in-depth if get() is ever reached directly.
46
- if (auth.kind === "anonymous") {
47
- return NOT_FOUND();
48
- }
49
- // Trusted internal call or admin agent — unfiltered, unchanged behavior.
50
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
51
- return super.get(target);
52
- }
53
- // Non-admin agent: only its own integrations.
54
- const record = await super.get(target);
55
- if (!record)
56
- return NOT_FOUND();
57
- if (record.agentId !== auth.agentId)
58
- return NOT_FOUND();
59
- return record;
42
+ return integrationByIdReadGate.call(this, target, (t) => super.get(t));
60
43
  }
61
44
  async search(query) {
62
45
  const auth = await this._auth();
@@ -65,14 +48,7 @@ export class Integration extends databases.flair.Integration {
65
48
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
66
49
  return super.search(query);
67
50
  }
68
- const agentIdCondition = { attribute: "agentId", comparator: "equals", value: auth.agentId };
69
- if (query && typeof query === "object" && !Array.isArray(query)) {
70
- const existing = query.conditions ?? [];
71
- query.conditions = Array.isArray(existing) ? [agentIdCondition, ...existing] : [agentIdCondition, existing];
72
- return super.search(query);
73
- }
74
- const conditions = Array.isArray(query) && query.length > 0 ? [agentIdCondition, ...query] : [agentIdCondition];
75
- return super.search(conditions);
51
+ return integrationScopedSearch(auth.agentId, query, (q) => super.search(q));
76
52
  }
77
53
  async post(content, context) {
78
54
  const auth = await this._auth();