@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
@@ -39,17 +39,8 @@ type Peer @table(database: "flair") @export {
39
39
  updatedAt: String
40
40
  }
41
41
 
42
- # Anti-replay nonce store (federation-edge-hardening slice 4).
43
- # Persists nonces recorded by verifyBodySignatureFresh (federation-crypto.ts)
44
- # so an instance restart doesn't wipe recently-seen nonces — closes the
45
- # ±30s freshness-window replay gap a restart would otherwise reopen. Nonces
46
- # are already globally unique (128-bit random, generated per request by
47
- # signBodyFresh), so the nonce string itself is the primary key — no scope
48
- # prefix needed. Internal bookkeeping only: never served, never replicated.
49
- type Nonce @table(database: "flair") {
50
- id: ID @primaryKey # the nonce string (base64url, 128-bit random)
51
- seenAt: Int! @indexed # ms-epoch when first recorded — eviction cutoff
52
- }
42
+ # Federation body-signature nonces are recorded in `ReplayNonce`
43
+ # (schemas/replay.graphql), shared with agent auth (flair#2061).
53
44
 
54
45
  # Sync log — audit trail for federation operations.
55
46
  type SyncLog @table(database: "flair") {
@@ -42,8 +42,22 @@ type Memory @table(database: "flair") {
42
42
  tags: [String] @indexed
43
43
  durability: String @indexed
44
44
  source: String
45
+ type: String # flair#1940 A1'' item 1: declared from MEASURED data, not derived from the schema. A live
46
+ # store (3,963 Memory rows) really carries `type` on 62% of rows — the client filters
47
+ # on it and MemoryMaintenance archives `type === "session"`. Declaring it here is what
48
+ # lets the declared-only whitelist (resources/memory-declared-attributes.ts) KEEP it on a
49
+ # full-row write instead of stripping it. Nullable/additive — existing rows keep their
50
+ # value, rows without it stay without it.
45
51
  createdAt: String! @indexed
46
52
  updatedAt: String
53
+ instanceToken: String @indexed # flair#1940 A1-iv: a server-stamped row INCARNATION token (UUID). The named
54
+ # application create paths stamp a local `instanceToken`; existing legacy rows may have
55
+ # none. Memory's REST write paths remove client-supplied `instanceToken` and
56
+ # `provenance`. The named update paths retain a stored token when their existing-row read
57
+ # succeeds. The host-pointer join binds on it: a pointer is returned only when
58
+ # memoryId, authorId === agentId, instanceToken and "not archived" all hold, so a
59
+ # deleted-and-recreated id (which gets a NEW token) can never re-bind a stale pointer.
60
+ # Nullable/additive: existing rows read back null (clean-upgrade-path gate).
47
61
  expiresAt: String @indexed
48
62
  retrievalCount: Int # Observable search-hit counter. Authoritative increments live on
49
63
  # MemoryHitStat (resources/hit-tracking.ts, flair#1528); GET/search
@@ -84,16 +98,28 @@ type Memory @table(database: "flair") {
84
98
  validFrom: String @indexed # ISO timestamp — when this fact became true
85
99
  validTo: String @indexed # ISO timestamp — when this fact stopped being true (null = still valid)
86
100
  _safetyFlags: [String] # content safety flags from scanContent()
87
- provenance: String # JSON blob (memory-provenance slice 1; claimed.client added by flair#718): { v, verified: { agentId, timestamp }, claimed?: { model, client } }
88
- # Nullable by design — existing rows read back provenance = null, unchanged behavior (clean-upgrade-path gate).
89
- # Same idiom as Soul.metadata below. Stamped server-side in resources/Memory.ts; never client-writable.
90
- originatorInstanceId: String @indexed # federation-edge-hardening slice 1: WRITE-TIME instance identity, stamped server-side in
91
- # resources/Memory.ts from resources/instance-identity.ts's localInstanceId() — never client-writable.
92
- # Nullable (existing rows read null = clean upgrade). Distinct from the legacy _originatorInstanceId
93
- # (Federation.ts's mergeRecord — stamped by the RECEIVER at merge time, forgeable/lossy); this field is
94
- # stamped by the ORIGINATING instance itself and preserved (never re-stamped) as the record flows through
95
- # sync merges. @indexed for the later sync push-query filter (per-record signature verification and the
96
- # classifier org-gate are separate, later slices — not built here).
101
+ provenance: String # JSON blob (memory-provenance slice 1; claimed.client added by flair#718): { v, verified: { agentId, timestamp, receivedAt }, claimed?: { model, client } }
102
+ # Server-STAMPED (receivedAt is the server's receipt time, never client-writable — flair#1940 A4).
103
+ # flair#1940 A1' — The Memory schema does not declare a pointer attribute.
104
+ # Supported Memory writes store accepted pointers in `MemoryHostSource`
105
+ # (below); the named non-admin reads use its gated join. Client and adapter
106
+ # transport is outside this slice. The three write-body inputs (hostSource,
107
+ # hostSourceScope, hostSourceVisibility) are consumed by Memory.post()/put()
108
+ # and are never persisted here.
109
+ originatorInstanceId: String @indexed # federation-edge-hardening slice 1: WRITE-TIME instance identity, stamped server-side on every
110
+ # application write via resources/originator-instance.ts from resources/instance-identity.ts's localInstanceId()
111
+ # (Memory/Soul/Agent/Relationship post()/put()/patch(), Memory's _reindex re-PUT, the FeedMemories ingest, AgentSeed
112
+ # and the MCP/IdP principal provisioning). On CREATE the local id is stamped and any request-body value is
113
+ # ignored; on UPDATE the STORED value stands (a body value neither replaces nor clears it, and an update that
114
+ # omits the field leaves it). Nullable (existing rows read null = clean upgrade).
115
+ # NOT client-writable through a resource write. Distinct from the legacy _originatorInstanceId (Federation.ts's
116
+ # mergeRecord — stamped by the RECEIVER at merge time, forgeable/lossy); this field is stamped by the ORIGINATING
117
+ # instance itself and preserved (never re-stamped) as the record flows through sync merges. Federation and Harper's
118
+ # administrator ops API are EXCEPTIONS to the rule, not the field's only raw writers: the SIGNED federation merge
119
+ # (FederationSync.post, which accepts a signed HTTP body from a known, non-revoked peer; a record's own signature,
120
+ # when present, is verified against the pinned key of the record's envelope originator) and the administrator ops
121
+ # API (:9925, admin auth). @indexed for the
122
+ # later sync push-query filter (per-record signature verification and the classifier org-gate are separate slices).
97
123
  metadata: String # JSON blob (flair#1332/#1202): ADK custom_metadata, store-and-return. CLIENT-WRITABLE
98
124
  # (unlike provenance above, which is server-stamped) and OPAQUE TO THE SERVER by
99
125
  # contract: stored verbatim, returned verbatim, never parsed server-side, never
@@ -141,14 +167,20 @@ type Relationship @table(database: "flair") {
141
167
  updatedAt: String
142
168
  originatorInstanceId: String @indexed # federation-edge-hardening slice 1 — see Memory.originatorInstanceId's doc above
143
169
  # for the full contract (write-time stamp, nullable, preserved across sync merges).
144
- # Stamped server-side in resources/Relationship.ts's put().
145
- provenance: String # JSON blob (relationship-write-path, folded K&S refinement): SAME shape as
146
- # Memory.provenance above — { v, verified: { agentId, timestamp }, claimed?: { model, client } }
147
- # — via the shared resources/provenance.ts buildProvenance(), never a
148
- # Relationship-specific format. Nullable by design — pre-existing rows read back
170
+ # Stamped server-side in resources/Relationship.ts's post() and put() via resources/originator-instance.ts
171
+ # (create stamps the local id; update keeps the stored value; never client-writable).
172
+ provenance: String # JSON blob (relationship-write-path, folded K&S refinement; re-stamped on
173
+ # the semantic PATCH path by flair#1960 r2): SAME shape as
174
+ # Memory.provenance above — { v, verified: { agentId, timestamp, receivedAt },
175
+ # claimed?: { createdAt, model, client } } — via the shared
176
+ # resources/provenance.ts buildProvenance(), never a
177
+ # Relationship-specific format. On a newly stamped local write, every
178
+ # field under `verified` is server-derived (the resolved auth verdict
179
+ # + one server clock read), never client-writable. Nullable by design — pre-existing rows read back
149
180
  # provenance = null, unchanged behavior (migration-equivalence gate, same
150
181
  # discipline as Memory.usageCount/flair#684). Stamped server-side in
151
- # resources/Relationship.ts's put(); never client-writable.
182
+ # resources/Relationship.ts's post() and put() (and re-stamped on a semantic patch());
183
+ # never client-writable.
152
184
  }
153
185
 
154
186
  type Soul @table(database: "flair") {
@@ -164,7 +196,8 @@ type Soul @table(database: "flair") {
164
196
  updatedAt: String
165
197
  originatorInstanceId: String @indexed # federation-edge-hardening slice 1 — see Memory.originatorInstanceId's doc above
166
198
  # for the full contract (write-time stamp, nullable, preserved across sync merges).
167
- # Stamped server-side in resources/Soul.ts's post()/put().
199
+ # Stamped server-side in resources/Soul.ts's post()/put() via resources/originator-instance.ts
200
+ # (create stamps the local id; update keeps the stored value; never client-writable).
168
201
  }
169
202
 
170
203
  type MemoryGrant @table(database: "flair") @export {
@@ -221,6 +254,62 @@ type MemoryHitStat @table(database: "flair") {
221
254
  lastRetrieved: String
222
255
  }
223
256
 
257
+ # MemoryHostSource — the host pointer, IN ITS OWN TABLE (flair#1940 slice 1 /
258
+ # A1', confirmed by Kern and Sherlock). The pointer is a host-object pointer —
259
+ # versioned JSON { v: 1, host, kind, id, url? } — The Memory schema does not
260
+ # declare a pointer attribute. Supported Memory writes store accepted pointers in
261
+ # `MemoryHostSource`; the named non-admin reads use its gated join. Client and
262
+ # adapter transport is outside this slice.
263
+ #
264
+ # Writes are NOT a REST surface for any caller: Memory.post()/put() write the row
265
+ # in the SAME transaction as the Memory row — a request's open transaction, or
266
+ # one created with transaction(ctx, cb) when an internal caller has no request
267
+ # context — so the row and its pointer commit together or not at all (real-
268
+ # Harper t1/t2: a failed pointer write leaves no row, and a failed PUT leaves
269
+ # the pre-existing row byte-identical). This resource refuses its OWN
270
+ # post()/put()/patch()/delete() for EVERY caller (r4-http), so no REST caller
271
+ # can plant a pointer; a superuser Harper operation against the table (an
272
+ # operator export, backup or reseed) is the operator path.
273
+ #
274
+ # Direct resource reads permit admin agents and trusted in-process callers;
275
+ # non-admin agents cannot read this table directly. The author
276
+ # reads their own pointer only through the gated join INTO Memory results (A1'
277
+ # item 4), never from this table directly. Bootstrap does not render pointers in
278
+ # this slice.
279
+ #
280
+ # NOT federated (A1' item 5/A1'' item 8): the table is absent from
281
+ # FEDERATION_TABLE_POLICY, so it is never in the sync's table set, an inbound row
282
+ # carrying a pointer field is REFUSED (resources/federation-classify.ts). The
283
+ # outbound reader projects declared Memory attributes. The inbound merge removes
284
+ # undeclared attributes except the named bookkeeping fields (f1-out/f1-in).
285
+ #
286
+ # Cascade (A1' item 6 / A1'' item 2): `Memory.delete` and maintenance expiry or
287
+ # age-based archival delete the pointer with their Memory operation. `MemoryArchive`
288
+ # basement/restore retains the pointer row; the join suppresses it while the Memory
289
+ # is archived. `Memory.delete` joins a request transaction when present; maintenance
290
+ # uses an owned transaction per item (c3). An orphan sweep re-checks inside the
291
+ # transaction before deleting; a cleanup failure makes the maintenance run report a
292
+ # failure, not "complete".
293
+ #
294
+ # hostSource is a writer claim attributed to the authenticated agent on agent
295
+ # writes — a claimed external source. Flair does not verify the host object and
296
+ # does not cryptographically sign the pointer body (the Ed25519 request
297
+ # signature covers method and URL, not the body).
298
+ # scopeAtWrite is the record's visibility AT WRITE (null → author-only). The join
299
+ # takes the narrower of the stored pointer scope and the Memory row's current
300
+ # visibility. A partial PUT carries the stored visibility it read at the start of
301
+ # the request (p2). receivedAt is server-stamped.
302
+ type MemoryHostSource @table(database: "flair") @export {
303
+ memoryId: ID @primaryKey # the Memory.id this pointer belongs to
304
+ hostSource: String! # canonical v1 JSON: { v:1, host, kind, id, url? }
305
+ scopeAtWrite: String # the record's visibility at write when the write opted in; null = author-only
306
+ authorId: String! @indexed # server-stamped from the authenticated principal, NEVER the body
307
+ memoryInstanceToken: String # the Memory row's server-stamped `instanceToken` at pointer-write time (A1-iv). The
308
+ # join returns this pointer only when it still equals the Memory row's token, so a
309
+ # deleted-and-recreated id (new token) never re-binds it.
310
+ receivedAt: String! # server receipt time
311
+ }
312
+
224
313
  # MemoryCandidate — staged distillations from the FLAIR-NIGHTLY-REM cycle.
225
314
  # Per docs/rem.md. Slice 1 of ops-2qq adds the schema +
226
315
  # `flair rem candidates` listing command. Future slices wire the nightly
@@ -0,0 +1,18 @@
1
+ # Replay store shared by agent auth (TPS-Ed25519) and federation body
2
+ # signatures (flair#2061). One row per accepted nonce, written once by
3
+ # resources/replay-store.ts under a per-key lock, and read by every Harper
4
+ # worker thread of this instance:
5
+ # a:<agentId>:<nonce> agent auth
6
+ # f:<nonce> federation
7
+ #
8
+ # replicate: false — local to this instance.
9
+ # expiration: 120 — seconds a row is kept. Harper's expiration scan runs once
10
+ # per instance (on the last worker) and removes a row no earlier than this
11
+ # after it was written. It MUST equal REPLAY_RETENTION_S in
12
+ # resources/replay-store.ts and stay longer than twice every replay window
13
+ # (30 s each today); test/unit-isolated/replay-store.test.ts pins both.
14
+ # Internal bookkeeping only: no @export, never served.
15
+ type ReplayNonce @table(database: "flair", replicate: false, expiration: 120) {
16
+ id: ID @primaryKey # scope-prefixed key (see above)
17
+ seenAt: Long! # ms-epoch when recorded
18
+ }
@@ -25,6 +25,28 @@ ADMIN_PASS_FILE="$1"
25
25
  NODE="$2"
26
26
  HARPER_BIN="$3"
27
27
 
28
+ # flair#2040: never start a SECOND instance on a data directory that a live
29
+ # process already serves. `flair init`, and a `flair start`/`doctor --fix` that
30
+ # fell back to a direct start, leave the instance running outside launchd with
31
+ # this plist on disk (RunAtLoad + KeepAlive). When launchd later starts the job
32
+ # — at the next console login, say — Harper's own "already running" check
33
+ # (hdb.pid) would refuse, but only AFTER it has loaded its config and applied
34
+ # HARPER_SET_CONFIG to the data directory's config state. Refuse here, before
35
+ # Harper runs at all: no config load, no hdb.pid write, no port bind, no store
36
+ # open, and the admin password is never read. Exit 0 — a deliberate no-op, not a
37
+ # crash. KeepAlive makes launchd retry after its throttle interval (10 s by
38
+ # default); once the direct process has exited, the next attempt starts Harper
39
+ # and launchd owns the instance.
40
+ # Mirrors Harper's getHdbPid(): a pid that is ours, 1, or not alive is no
41
+ # evidence. ROOTPATH comes from the plist's EnvironmentVariables.
42
+ if [ -n "${ROOTPATH:-}" ] && [ -f "$ROOTPATH/hdb.pid" ]; then
43
+ LIVE_PID="$(tr -cd '0-9' < "$ROOTPATH/hdb.pid" 2>/dev/null || true)"
44
+ if [ -n "$LIVE_PID" ] && [ "$LIVE_PID" != "$$" ] && [ "$LIVE_PID" -gt 1 ] 2>/dev/null && kill -0 "$LIVE_PID" 2>/dev/null; then
45
+ echo "start-flair-with-admin-pass: $ROOTPATH is already served by pid $LIVE_PID (not started by this launchd job); not starting a second instance. launchd retries after its throttle interval and starts Flair once that process has exited." >&2
46
+ exit 0
47
+ fi
48
+ fi
49
+
28
50
  if [ ! -f "$ADMIN_PASS_FILE" ]; then
29
51
  echo "start-flair-with-admin-pass: admin-pass file not found: $ADMIN_PASS_FILE" >&2
30
52
  exit 1
@@ -1,195 +0,0 @@
1
- /**
2
- * federation-nonce-store.ts — persistent backing for the federation
3
- * anti-replay NonceStore (federation-edge-hardening slice 4).
4
- *
5
- * The gap: `federationNonceStore` in Federation.ts was a bare in-memory Map
6
- * (`createNonceStore()` in federation-crypto.ts). On process restart it's
7
- * wiped, so a signed federation request captured within its ±30s freshness
8
- * window (verifyBodySignatureFresh) could be replayed once, post-restart.
9
- * This module closes that window by backing the SAME `NonceStore` interface
10
- * with the `Nonce` Harper table, while keeping every method synchronous —
11
- * `verifyBodySignatureFresh` and its 2 call sites in Federation.ts are
12
- * UNCHANGED (they still call `.has()` / `.set()` / `.evict()` with no
13
- * `await`), so the entire existing federation-crypto-replay test suite
14
- * (all synchronous assertions) keeps working unmodified.
15
- *
16
- * How the sync interface stays sync against an inherently-async DB API:
17
- * - `has()` / `evict()` read/mutate an in-memory Map (via the existing
18
- * `createNonceStore()`), exactly as before — no DB round trip.
19
- * - `set()` updates that same in-memory Map synchronously (so replay
20
- * detection within THIS process's lifetime is unchanged), and fires an
21
- * async `Nonce.put()` in the background (not awaited) to persist the
22
- * nonce for the NEXT restart. A failed/slow persist never blocks or
23
- * fails request handling — see the perf/durability tradeoff note below.
24
- * - `hydrate()` is the new piece: an explicit async step that loads
25
- * not-yet-expired rows from the `Nonce` table into the in-memory Map.
26
- * Call it once, on startup, BEFORE the store starts guarding live
27
- * traffic — that's what makes a nonce recorded by the PREVIOUS process
28
- * visible to a FRESH store instance after a restart (the whole point).
29
- *
30
- * Known tradeoff (flagged, not fixed here — would require making NonceStore
31
- * async, which ripples into ~40 synchronous call sites across
32
- * federation-crypto-replay.test.ts + federation-sync-e2e.test.ts):
33
- * `set()`'s persistence is fire-and-forget. A crash in the narrow gap
34
- * between "response sent" and "async put() resolved" can still lose that
35
- * one nonce — narrowing the replay window to that gap, not eliminating it
36
- * outright. Defense-in-depth: the ±30s freshness check + signature
37
- * verification are still the primary guards; this closes the common case
38
- * (graceful restart / redeploy), not the crash-mid-request edge case.
39
- */
40
- import { createNonceStore } from "./federation-crypto.js";
41
- /** 2x the standard 30s freshness window — matches the in-memory `evict()` cutoff already used by verifyBodySignatureFresh. */
42
- export const DEFAULT_RETENTION_MS = 60_000;
43
- async function resolveDb(opts, cache) {
44
- if (opts.db)
45
- return opts.db;
46
- if (!cache.db) {
47
- cache.db = import("harper").then((h) => h.databases);
48
- }
49
- return cache.db;
50
- }
51
- /**
52
- * Create a `NonceStore` backed by the `Nonce` Harper table.
53
- *
54
- * Wraps the existing in-memory `createNonceStore()` (unchanged behavior for
55
- * `has()`/`set()`/`evict()` within this process) and adds:
56
- * - background persistence of newly-set nonces (`set()`)
57
- * - an explicit `hydrate()` to reload previously-persisted nonces (used
58
- * at startup, and by tests simulating a restart with a fresh instance)
59
- */
60
- export function createPersistentNonceStore(opts = {}) {
61
- const memory = createNonceStore();
62
- const dbCache = {};
63
- return {
64
- has(key) {
65
- return memory.has(key);
66
- },
67
- evict(olderThan) {
68
- memory.evict(olderThan);
69
- },
70
- set(key, value) {
71
- memory.set(key, value);
72
- // Fire-and-forget persistence — see module header for the tradeoff.
73
- void (async () => {
74
- try {
75
- const db = await resolveDb(opts, dbCache);
76
- await db.flair.Nonce.put({ id: key, seenAt: value });
77
- }
78
- catch (err) {
79
- console.error("[federation-nonce-store] failed to persist nonce (in-memory record already made — this process's replay guard is unaffected):", err?.message ?? err);
80
- }
81
- })();
82
- },
83
- async hydrate(hydrateOpts) {
84
- const retentionMs = hydrateOpts?.retentionMs ?? DEFAULT_RETENTION_MS;
85
- const now = hydrateOpts?.now ?? Date.now();
86
- const cutoff = now - retentionMs;
87
- try {
88
- const db = await resolveDb(opts, dbCache);
89
- for await (const row of db.flair.Nonce.search()) {
90
- if (row?.id != null && typeof row.seenAt === "number" && row.seenAt >= cutoff) {
91
- memory.set(String(row.id), row.seenAt);
92
- }
93
- }
94
- }
95
- catch (err) {
96
- console.error("[federation-nonce-store] failed to hydrate from Nonce table (starting with an empty replay guard):", err?.message ?? err);
97
- }
98
- },
99
- };
100
- }
101
- // ─── Eviction sweep — periodic Nonce table hygiene ─────────────────────────
102
- //
103
- // Mirrors federation-cleanup.ts's 5-min setInterval hub-pattern. Decoupled
104
- // from the in-memory `evict()` above (which runs per-request and only trims
105
- // the local Map): this sweep deletes rows from the `Nonce` TABLE itself so
106
- // it doesn't grow unbounded across restarts. No native TTL in this repo —
107
- // same app-managed-sweep idiom as PairingToken cleanup.
108
- //
109
- // Runs on every instance (hub AND spoke) — unlike PairingToken cleanup
110
- // (hub-only, since only hubs issue pairing tokens), both FederationPair and
111
- // FederationSync can be the RECEIVING side of a signed request on either
112
- // role, so both roles accumulate rows in the Nonce table and both need the
113
- // sweep.
114
- const NONCE_CLEANUP_INTERVAL_MS = 300_000; // 5 minutes
115
- let nonceCleanupTimer = null;
116
- /**
117
- * Core sweep logic — exposed for unit testing. Deletes `Nonce` rows with
118
- * `seenAt` older than `retentionMs` (default: 2x the 30s freshness window).
119
- */
120
- export async function runNonceCleanupTick(opts = {}) {
121
- let db;
122
- if (opts.db) {
123
- db = opts.db;
124
- }
125
- else {
126
- const harper = await import("harper");
127
- db = harper.databases;
128
- }
129
- const retentionMs = opts.retentionMs ?? DEFAULT_RETENTION_MS;
130
- const now = opts.now ?? Date.now();
131
- const cutoff = now - retentionMs;
132
- const toDelete = [];
133
- let scanned = 0;
134
- try {
135
- for await (const row of db.flair.Nonce.search()) {
136
- scanned++;
137
- if (typeof row?.seenAt === "number" && row.seenAt < cutoff) {
138
- toDelete.push(row.id);
139
- }
140
- }
141
- }
142
- catch (err) {
143
- console.error("[federation-nonce-store] failed to query Nonce records:", err?.message ?? err);
144
- return { deleted: 0, scanned: 0 };
145
- }
146
- let deleted = 0;
147
- for (const id of toDelete) {
148
- try {
149
- await db.flair.Nonce.delete(id);
150
- deleted++;
151
- }
152
- catch (err) {
153
- console.error("[federation-nonce-store] failed to delete expired nonce:", err?.message ?? err);
154
- }
155
- }
156
- return { deleted, scanned };
157
- }
158
- /**
159
- * Initialise the periodic Nonce-table eviction sweep (5-min cadence).
160
- *
161
- * In test environments, callers pass a mock `db` via `opts` so this module
162
- * never imports harper at the top level (mirrors
163
- * federation-cleanup.ts's `initFederationCleanup`).
164
- */
165
- export async function initNonceStoreCleanup(opts) {
166
- const immediate = opts?.immediateTick ?? true;
167
- let db;
168
- if (opts?.db) {
169
- db = opts.db;
170
- }
171
- else {
172
- try {
173
- const harper = await import("harper");
174
- db = harper.databases;
175
- }
176
- catch (err) {
177
- console.error("[federation-nonce-store] failed to load harper:", err?.message ?? err);
178
- return;
179
- }
180
- }
181
- const retentionMs = opts?.retentionMs ?? DEFAULT_RETENTION_MS;
182
- console.log("[federation-nonce-store] starting nonce eviction sweep (5-min cadence)");
183
- if (nonceCleanupTimer)
184
- clearInterval(nonceCleanupTimer);
185
- nonceCleanupTimer = setInterval(() => {
186
- runNonceCleanupTick({ db, retentionMs }).catch((err) => {
187
- console.error("[federation-nonce-store] cleanup tick error:", err?.message ?? err);
188
- });
189
- }, NONCE_CLEANUP_INTERVAL_MS);
190
- if (immediate) {
191
- runNonceCleanupTick({ db, retentionMs }).catch((err) => {
192
- console.error("[federation-nonce-store] initial cleanup tick error:", err?.message ?? err);
193
- });
194
- }
195
- }