@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -135,6 +135,8 @@
135
135
  */
136
136
  import { databases } from "harper";
137
137
  import { stripUndeclaredMemoryAttributes } from "../memory-declared-attributes.js";
138
+ import { writeBackCommittedRow as writeBackCommittedRowImpl } from "../write-back.js";
139
+ import { txnPausePoint } from "../txn-pause-point.js";
138
140
  function defaultMemoryTable() {
139
141
  return databases.flair.Memory;
140
142
  }
@@ -170,7 +172,7 @@ function pendingCondition() {
170
172
  * `embedding-stamp`, there is no separate HTTP mechanism to inject: the
171
173
  * write IS the table's own `.put()`, already covered by the same fake.
172
174
  */
173
- export function createVisibilityBackfillMigration(getTable = defaultMemoryTable) {
175
+ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable, writeBackCommittedRow = writeBackCommittedRowImpl) {
174
176
  return {
175
177
  id: VISIBILITY_BACKFILL_ID,
176
178
  riskClass: "derived-only",
@@ -200,34 +202,32 @@ export function createVisibilityBackfillMigration(getTable = defaultMemoryTable)
200
202
  const id = String(row.id ?? "");
201
203
  if (!id)
202
204
  continue;
203
- const existing = await table.get(id);
204
- if (!existing)
205
- continue; // deleted since the search above — nothing to fix
206
- // The write-gate: this is what actually enforces "never overwrite an
207
- // existing visibility value", independent of how precisely the
208
- // candidate query above narrowed things (see module doc — a
209
- // garbage third value would still be pulled in as a candidate).
210
- // Re-checks the FRESHLY-READ record, not the (possibly stale)
211
- // search-result row, and doubles as the idempotency/concurrent-
212
- // writer guard `embedding-stamp.ts` gets from its own analogous
213
- // pre-write check.
214
- if (existing.visibility !== undefined && existing.visibility !== null)
215
- continue;
216
- const derived = deriveVisibilityFromDurability(existing.durability);
217
- // Never-widen invariant, asserted, not just tested: the only two
218
- // values `deriveVisibilityFromDurability` can ever produce are
219
- // "private"/"shared" (see its own doc), so this can never fire
220
- // today — it exists to fail loudly (halting this migration via the
221
- // runner's mid-batch-throw path, never a silent bad write) if a
222
- // future edit to that function ever widens its return type or is
223
- // bypassed via a type-unsafe call.
224
- if (derived !== "private" && derived !== "shared") {
225
- throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
226
- }
227
- const backfillRow = { ...existing, visibility: derived };
228
- stripUndeclaredMemoryAttributes(backfillRow);
229
- await table.put(backfillRow);
230
- touchedIds.push(id);
205
+ const outcome = await writeBackCommittedRow(table, id, (existing) => {
206
+ if (!existing)
207
+ return { skip: true }; // deleted since the search above — nothing to fix
208
+ // The write-gate: this is what actually enforces "never overwrite an
209
+ // existing visibility value", independent of how precisely the
210
+ // candidate query above narrowed things (see module doc — a
211
+ // garbage third value would still be pulled in as a candidate).
212
+ if (existing.visibility !== undefined && existing.visibility !== null)
213
+ return { skip: true };
214
+ const derived = deriveVisibilityFromDurability(existing.durability);
215
+ // Never-widen invariant, asserted, not just tested: the only two
216
+ // values `deriveVisibilityFromDurability` can ever produce are
217
+ // "private"/"shared" (see its own doc), so this can never fire
218
+ // today — it exists to fail loudly (halting this migration via the
219
+ // runner's mid-batch-throw path, never a silent bad write) if a
220
+ // future edit to that function ever widens its return type or is
221
+ // bypassed via a type-unsafe call.
222
+ if (derived !== "private" && derived !== "shared") {
223
+ throw new Error(`visibility-backfill: derived an invalid visibility for row ${id} — refusing to write`);
224
+ }
225
+ const backfillRow = { ...existing, visibility: derived };
226
+ stripUndeclaredMemoryAttributes(backfillRow);
227
+ return { write: backfillRow };
228
+ }, { label: "visibility-backfill", pausePre: () => txnPausePoint("visibility-backfill-pre"), pausePoint: () => txnPausePoint("visibility-backfill"), expectedRow: row });
229
+ if ("write" in outcome)
230
+ touchedIds.push(id);
231
231
  }
232
232
  return { processed: touchedIds.length, touchedIds };
233
233
  },
@@ -0,0 +1,33 @@
1
+ /**
2
+ * object-body-guard.ts — the shared write-body shape check.
3
+ *
4
+ * `content` must be a non-null, non-array object. Arrays of records are admitted
5
+ * when `allowArrayObjects` is enabled. Anything else reaching this guard is
6
+ * refused with `body_must_be_object` (400).
7
+ */
8
+ export const BODY_MUST_BE_OBJECT_ERROR = "body_must_be_object";
9
+ /** True for a write body that is one record: a non-null object that is not an array. */
10
+ function isObjectRecord(value) {
11
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12
+ }
13
+ /** 400 for a write body that is neither a JSON object nor an allowed array of them. Echoes nothing. */
14
+ export function bodyMustBeObject() {
15
+ return new Response(JSON.stringify({
16
+ error: BODY_MUST_BE_OBJECT_ERROR,
17
+ message: "the write body must be a JSON object, or an array of them for a collection write",
18
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
19
+ }
20
+ /**
21
+ * Refuse a write body that is neither an object nor an allowed array of records.
22
+ *
23
+ * @param content the parsed request body
24
+ * @param opts `allowArrayObjects: true` admits arrays of records
25
+ * @returns the 400 `Response` to send, or null to proceed
26
+ */
27
+ export function guardObjectBody(content, opts = {}) {
28
+ if (isObjectRecord(content))
29
+ return null;
30
+ if (opts.allowArrayObjects && Array.isArray(content) && content.every(isObjectRecord))
31
+ return null;
32
+ return bodyMustBeObject();
33
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * org-event-created-at.ts — the createdAt check for OrgEvent writes: the server
3
+ * assigns an event's createdAt on create, and a write that reaches this check
4
+ * cannot change a stored row's createdAt.
5
+ *
6
+ * The check runs after the resource's earlier checks (authentication,
7
+ * ownership, attribution, entity validation), which answer first with their own
8
+ * responses, as Harper's own validation does for input it refuses before the
9
+ * resource runs. For each record that reaches it:
10
+ *
11
+ * - a record that is not an object, or whose id is not a non-empty string or
12
+ * a non-empty array of strings, is not read: it is refused with
13
+ * `invalid_event_id` (400) before any write. Before validation, an
14
+ * addressed POST binds a missing or null body id to the addressed id, and
15
+ * a string or number body id when its text matches the address; any other
16
+ * id type is left unchanged by this step. At the root collection, POST
17
+ * generates an id when the body's id is missing, null or empty. At the
18
+ * root collection, or an addressed path whose body id was not bound, a
19
+ * remaining id outside those shapes receives the same 400 before the
20
+ * ownership lookup;
21
+ * - otherwise the check reads the stored row under that id. With no stored
22
+ * row (a create), createdAt is the server's time, whatever the body says;
23
+ * - with a stored row, its createdAt is authoritative whatever its value, an
24
+ * empty string included. A body that omits createdAt keeps the stored
25
+ * value; a body whose createdAt differs from it is refused with
26
+ * `created_at_immutable` (409), and nothing is written.
27
+ *
28
+ * resources/OrgEvent.ts runs this check for writes from verified agents and
29
+ * administrators on POST, single-record PUT and PATCH, and for administrators
30
+ * on each element of a collection PUT. A non-admin agent's collection PUT or
31
+ * PATCH is refused before this check by the owner-scoped write guard
32
+ * (resources/owner-scoped-write-policy.ts), and a non-admin addressed
33
+ * array-body PUT that reaches the resource is refused before it by attribution. Trusted in-process
34
+ * writers that supply their own createdAt (the migration ledger, the graph-heal migration) write
35
+ * through the raw `databases.flair.OrgEvent` table, not the resource's verbs,
36
+ * and an `internal` verdict on the resource passes through unchanged.
37
+ *
38
+ * The stored row is read before the write and the two are not atomic: a row
39
+ * first written between the read and the write is treated as a create, so its
40
+ * createdAt becomes this write's server time.
41
+ *
42
+ * The decision is pure and has no Harper import, so it is unit-tested directly.
43
+ */
44
+ export const CREATED_AT_IMMUTABLE_ERROR = "created_at_immutable";
45
+ export const CREATED_AT_CHECK_UNAVAILABLE_ERROR = "created_at_check_unavailable";
46
+ export const INVALID_EVENT_ID_ERROR = "invalid_event_id";
47
+ /** 409 for a write that reaches the check and would change a stored event's createdAt. Echoes nothing. */
48
+ export function createdAtImmutable() {
49
+ return new Response(JSON.stringify({
50
+ error: CREATED_AT_IMMUTABLE_ERROR,
51
+ message: "this write would change the stored event's createdAt, which the server assigns on create",
52
+ }), { status: 409, headers: { "Content-Type": "application/json" } });
53
+ }
54
+ /**
55
+ * 503 when this check's own stored-event read fails, so the write was refused.
56
+ * Read failures in earlier checks keep their own responses.
57
+ */
58
+ export function createdAtCheckUnavailable(err) {
59
+ console.error("org-event-created-at: the stored event could not be read, so the write was refused", { err });
60
+ return new Response(JSON.stringify({
61
+ error: CREATED_AT_CHECK_UNAVAILABLE_ERROR,
62
+ message: "the stored event could not be read; the write was refused",
63
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
64
+ }
65
+ /**
66
+ * 400 for a record the check does not read: one that is not an object, or whose
67
+ * id is not a key the check reads (see isReadableEventId). Echoes nothing.
68
+ */
69
+ export function invalidEventId() {
70
+ return new Response(JSON.stringify({
71
+ error: INVALID_EVENT_ID_ERROR,
72
+ message: "each OrgEvent a write stores must be an object whose id is a non-empty string or a non-empty array of strings",
73
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
74
+ }
75
+ /**
76
+ * Whether the check reads the stored row under `id`: a non-empty string, or a
77
+ * non-empty array of strings (a composite key). The check refuses every other
78
+ * id with `invalid_event_id` before any write. Harper accepts some of those ids
79
+ * as keys (the empty string is one), so the refusal is this check's own rule,
80
+ * not something left to Harper's validation.
81
+ */
82
+ export function isReadableEventId(id) {
83
+ if (typeof id === "string")
84
+ return id !== "";
85
+ return Array.isArray(id) && id.length > 0 && id.every((part) => typeof part === "string");
86
+ }
87
+ /**
88
+ * Returns invalid_event_id (400) for anything but a non-empty string or a
89
+ * non-empty array of strings, or null. The refusal echoes no submitted value.
90
+ */
91
+ export function unreadableEventIdRefusal(id) {
92
+ return isReadableEventId(id) ? null : invalidEventId();
93
+ }
94
+ /**
95
+ * The same rule applied to a collection PUT's array body: the refusal for the
96
+ * first record element whose id it does not read, or null.
97
+ * The scan skips non-record elements.
98
+ */
99
+ export function collectionElementIdRefusal(body) {
100
+ if (!Array.isArray(body))
101
+ return null;
102
+ for (const element of body) {
103
+ if (element == null || typeof element !== "object" || Array.isArray(element))
104
+ continue;
105
+ const denial = unreadableEventIdRefusal(element.id);
106
+ if (denial)
107
+ return denial;
108
+ }
109
+ return null;
110
+ }
111
+ /**
112
+ * Assign or keep `content.createdAt` for one write, given the stored row the
113
+ * write lands on (`stored` null/undefined = no stored row, a create). Mutates
114
+ * `content`. Returns null to proceed, or the refusal to send.
115
+ *
116
+ * For a stored row, the stored createdAt is authoritative whatever its value,
117
+ * an empty string included: a body that names a different value is refused,
118
+ * and a body that omits it keeps the stored value.
119
+ */
120
+ export function applyServerCreatedAt(content, stored, mode, now = new Date()) {
121
+ if (stored == null) {
122
+ // No stored row: a create, so the server assigns createdAt.
123
+ content.createdAt = now.toISOString();
124
+ return null;
125
+ }
126
+ const storedAt = stored.createdAt;
127
+ if (Object.prototype.hasOwnProperty.call(content, "createdAt") && content.createdAt !== storedAt) {
128
+ return createdAtImmutable();
129
+ }
130
+ if (mode === "replace")
131
+ content.createdAt = storedAt;
132
+ return null;
133
+ }
@@ -56,12 +56,25 @@ function isStoredRow(value) {
56
56
  /**
57
57
  * CREATE path — stamp this instance's own federation id, ignoring any value the
58
58
  * request body carried. Used by `post()` (always a create) and by a
59
- * `put()`/`patch()` whose target id has no stored row yet.
59
+ * `put()`/`patch()` whose target id has no stored row yet. The id is this
60
+ * module's process-cached {@link localInstanceId}.
60
61
  */
61
62
  export async function stampOriginatorOnCreate(content) {
63
+ applyOriginatorInstanceIdWith(content, null, await localInstanceId());
64
+ }
65
+ /**
66
+ * CREATE path with a CALLER-RESOLVED local id: the same stamp as
67
+ * {@link stampOriginatorOnCreate}, but the id is one the caller read from the
68
+ * CURRENT `Instance` table (a fresh read), never this module's process cache. A
69
+ * caller that must agree with a second decision on the same write — the
70
+ * Presence local home guard (resources/Presence.ts) compares an agent's home
71
+ * against the same id — resolves it once and passes it here, so both use ONE
72
+ * read and cannot disagree. A null id stamps null (the local-origin state).
73
+ */
74
+ export function stampOriginatorOnCreateWith(content, localInstanceId) {
62
75
  if (!isPlainObject(content))
63
76
  return;
64
- content.originatorInstanceId = await localInstanceId();
77
+ content.originatorInstanceId = localInstanceId;
65
78
  }
66
79
  /**
67
80
  * UPDATE path — the STORED value stands. A body value is dropped (neither
@@ -87,7 +100,8 @@ export function keepStoredOriginator(content, stored) {
87
100
  /**
88
101
  * Apply the full create/update rule: `stored` is the row this write is over
89
102
  * (null/undefined ⇒ a create). This is the one call a `put()` or `patch()` needs
90
- * after it has resolved the pre-existing row.
103
+ * after it has resolved the pre-existing row. The create id is this module's
104
+ * process-cached {@link localInstanceId}.
91
105
  */
92
106
  export async function applyOriginatorInstanceId(content, stored) {
93
107
  if (isStoredRow(stored)) {
@@ -97,6 +111,22 @@ export async function applyOriginatorInstanceId(content, stored) {
97
111
  await stampOriginatorOnCreate(content);
98
112
  }
99
113
  }
114
+ /**
115
+ * Apply the full create/update rule with an explicitly resolved local id:
116
+ * `stored` is the row this write is over (null/undefined ⇒ a create, stamped
117
+ * with `localInstanceId`). The id is the caller's fresh read of the CURRENT
118
+ * `Instance` table, not this module's cache — used where a caller also decides
119
+ * the write by the current instance id (the Presence local home guard,
120
+ * resources/Presence.ts) so the two share ONE read.
121
+ */
122
+ export function applyOriginatorInstanceIdWith(content, stored, localInstanceId) {
123
+ if (isStoredRow(stored)) {
124
+ keepStoredOriginator(content, stored);
125
+ }
126
+ else {
127
+ stampOriginatorOnCreateWith(content, localInstanceId);
128
+ }
129
+ }
100
130
  /**
101
131
  * PATCH path — a patch MERGES into the stored row (Harper partial update), so a
102
132
  * body value can be dropped and the stored value stands untouched.
@@ -200,7 +230,8 @@ function storedRowLookupFailure(tableName, err) {
200
230
  * force a "create" that re-stamped an existing row.
201
231
  *
202
232
  * Rules:
203
- * - a body `id` that disagrees with the URL target id is REFUSED;
233
+ * - with a URL target id, a non-null body `id` that is not a string or
234
+ * number, or that disagrees with it, is REFUSED;
204
235
  * - the stored row is read by the URL target id (via the raw table reader,
205
236
  * falling back to the resource's own bound-record read when the table
206
237
  * exposes no static reader — an in-process harness);
@@ -209,10 +240,11 @@ function storedRowLookupFailure(tableName, err) {
209
240
  * An in-process call with no URL-bound id (a direct `new Resource().put(body)`)
210
241
  * falls back to the body `id`, which IS the write key on that path.
211
242
  */
212
- export async function resolveStoredRow(resource, tableName, content, getUrlBound) {
243
+ export async function resolveStoredRow(resource, tableName, content, getUrlBound, context) {
213
244
  const targetId = urlTargetId(resource);
214
245
  const bodyId = isPlainObject(content) && content.id != null ? content.id : undefined;
215
- if (targetId != null && bodyId !== undefined && String(bodyId) !== String(targetId)) {
246
+ if (targetId != null && bodyId !== undefined &&
247
+ ((typeof bodyId !== "string" && typeof bodyId !== "number") || String(bodyId) !== String(targetId))) {
216
248
  return { row: null, denial: idTargetMismatchDenial(bodyId, targetId) };
217
249
  }
218
250
  const id = targetId ?? bodyId;
@@ -221,7 +253,7 @@ export async function resolveStoredRow(resource, tableName, content, getUrlBound
221
253
  try {
222
254
  const table = databases.flair?.[tableName];
223
255
  if (table && typeof table.get === "function") {
224
- const row = await table.get(id);
256
+ const row = await table.get(id, context ?? resource?.getContext?.());
225
257
  return { row: isStoredRow(row) ? row : null };
226
258
  }
227
259
  // No static table reader (an in-process harness): read the resource's own
@@ -0,0 +1,78 @@
1
+ /**
2
+ * owner-delete-recheck.ts — the confirmation a non-admin owner-scoped delete
3
+ * runs before it removes a row (flair#2355).
4
+ *
5
+ * A non-admin delete reads the stored row, decides the caller owns it, then
6
+ * deletes it. Harper 5.2.8 has no compare-and-set on a table write: a
7
+ * transaction does not fail when a row it read is changed by another write
8
+ * before it commits; Harper applies both writes, ordered by transaction
9
+ * timestamp. So an owner change committed between that read and the
10
+ * confirmation read below — an admin/internal write, or a raw table write, as
11
+ * an operator or a migration would make — would let the delete remove a row
12
+ * that is no longer the caller's.
13
+ *
14
+ * This helper runs the read and the delete in ONE transaction the call OWNS
15
+ * (withOwnedTransaction), re-reads the row there, and, for a non-admin caller,
16
+ * pauses (a test-only point) between that read and the delete and re-reads the
17
+ * COMMITTED row before the delete is staged. A row whose owner had changed by
18
+ * that confirmation read is refused (`owner_changed`) and not deleted; a row
19
+ * absent at the first read is reported absent. A change committed after the
20
+ * confirmation read is not caught.
21
+ *
22
+ * The owner field is immutable to a non-admin's own writes
23
+ * (guardOwnerFieldImmutable, resources/owner-field-guard.ts), so the change this
24
+ * confirmation catches comes from an admin or internal write, or a raw table
25
+ * write — the writers that can re-point a stored row's owner.
26
+ *
27
+ * The confirmation read runs while the owned transaction is open, in an
28
+ * EXPLICIT fresh context (`{}`), never contextless: a contextless read joins the
29
+ * request's ambient operation transaction and reads that transaction's pinned
30
+ * read snapshot (flair#2147), and a by-id read on the request Resource
31
+ * instance reads that instance's request-time entry.
32
+ */
33
+ import { withOwnedTransaction } from "./request-transaction.js";
34
+ import { txnPausePoint } from "./txn-pause-point.js";
35
+ /** The named error for a delete refused because the row's owner changed (flair#2355). */
36
+ export const OWNER_CHANGED_ERROR = "owner_changed";
37
+ /** The named 409 for a delete refused because an owner confirmation failed. */
38
+ export function ownerChangedRefusal(tableName) {
39
+ return new Response(JSON.stringify({
40
+ error: OWNER_CHANGED_ERROR,
41
+ message: `${tableName} owner confirmation failed; not deleted`,
42
+ }), { status: 409, headers: { "content-type": "application/json" } });
43
+ }
44
+ /**
45
+ * Delete `spec.id` in a transaction this call owns, refusing when the row read
46
+ * at the re-read or at the confirmation read has an owner other than
47
+ * `spec.callerId` (flair#2355).
48
+ *
49
+ * Returns `deleted` with the table delete's result, `absent` when the first
50
+ * read finds no row (the caller decides the no-op), or `refused` with the
51
+ * named 409 when the stored or confirmed row's owner is not the caller. A
52
+ * delete whose row exists but reports no success throws rather than a silent
53
+ * partial.
54
+ */
55
+ export async function deleteOwnedRow(ctx, spec) {
56
+ return withOwnedTransaction(ctx, async (c) => {
57
+ const stored = await spec.table.get(spec.id, c);
58
+ if (!stored)
59
+ return { kind: "absent" };
60
+ if (stored[spec.ownerField] !== spec.callerId) {
61
+ return { kind: "refused", response: ownerChangedRefusal(spec.tableName) };
62
+ }
63
+ // Test-only: valid names are inert unless fault injection is enabled and armed.
64
+ const pause = txnPausePoint(spec.point);
65
+ if (pause)
66
+ await pause;
67
+ // Confirmation read: the committed row in an explicit fresh context (see
68
+ // this module's header — never contextless).
69
+ const confirmed = await spec.table.get(spec.id, {});
70
+ if (confirmed && confirmed[spec.ownerField] !== spec.callerId) {
71
+ return { kind: "refused", response: ownerChangedRefusal(spec.tableName) };
72
+ }
73
+ const result = await spec.table.delete(spec.id, c);
74
+ if (result !== true)
75
+ throw new Error(`${spec.tableName} row delete was not confirmed`);
76
+ return { kind: "deleted", result };
77
+ });
78
+ }
@@ -27,18 +27,43 @@
27
27
  * not this rule's business — no-forge attribution on creation is each resource's
28
28
  * own job. The decision itself is the pure `isForbiddenOwnerFieldChange`
29
29
  * (record-owner-guard.ts), so it is unit-tested without a Harper instance.
30
+ *
31
+ * ─── Read-failure scope ─────────────────────────────────────────────────────
32
+ *
33
+ * For addressed single-record HTTP PUT/PATCH, Harper loads the row through
34
+ * `Table.getResource` → `resource._loadRecord` before the resource method runs;
35
+ * a no-argument `super.get()` then returns the cached row. If reached before
36
+ * that load, the non-admin write guard checks string or number body ids before stored ownership.
37
+ * Its stored-row read failure returns `owner_check_unavailable`. The
38
+ * real-Harper test injects an initial load failure: a non-admin agent gets that
39
+ * named refusal, and an administrator gets Harper's own 500. It does not cover
40
+ * collection paths.
41
+ *
42
+ * This guard returns `owner_check_unavailable` only when a non-admin agent's
43
+ * `getExisting` thunk throws or rejects. Admin/internal callers return before
44
+ * the thunk; unauthenticated callers receive 401 before it.
45
+ *
46
+ * Soul first reads through `resolveStoredRow` and passes an already-resolved row
47
+ * to this guard. That resolver's `stored_row_lookup_failed` (500) is a separate
48
+ * refusal for a read this guard does not backstop.
30
49
  */
31
50
  import { resolveAgentAuth } from "./agent-auth.js";
32
- import { isForbiddenOwnerFieldChange } from "./record-owner-guard.js";
51
+ import { isForbiddenOwnerFieldChange, ownerCheckUnavailable } from "./record-owner-guard.js";
52
+ // The named refusal and its constant live in record-owner-guard.ts, which has
53
+ // no authentication-module dependency, so the owner-scoped write guard can use
54
+ // them without importing this module;
55
+ // re-exported here for this module's existing importers.
56
+ export { OWNER_CHECK_UNAVAILABLE_ERROR, ownerCheckUnavailable } from "./record-owner-guard.js";
33
57
  /**
34
58
  * Enforce owner-field immutability for one write.
35
59
  *
36
60
  * @param self the resource instance (`this`)
37
- * @param getExisting a thunk that returns the STORED record — pass `() => super.get()`
38
- * so the raw base-table read is used rather than any get() override
61
+ * @param getExisting a thunk returning stored state, e.g. `() => super.get()`
62
+ * or Soul's already-resolved row
39
63
  * @param content the write content (the caller's claim)
40
64
  * @param ownerField the column naming the owning principal for this table
41
- * @returns a 403 Response to send, or null to proceed
65
+ * @returns a Response to send (401 unauthenticated, 403 owner-field change,
66
+ * 400/503 non-admin agent's guard-thunk failure), or null to proceed
42
67
  */
43
68
  export async function guardOwnerFieldImmutable(self, getExisting, content, ownerField) {
44
69
  const auth = await resolveAgentAuth(self.getContext?.());
@@ -54,7 +79,16 @@ export async function guardOwnerFieldImmutable(self, getExisting, content, owner
54
79
  if (auth.kind !== "agent") {
55
80
  return new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "content-type": "application/json" } });
56
81
  }
57
- const existing = (await Promise.resolve(getExisting()).catch(() => null));
82
+ // A read that RESOLVED to null/undefined is "no stored row" (a create, which
83
+ // this rule leaves to each resource). A read that THREW or rejected is a
84
+ // FAILURE, and the guard refuses it rather than reading it as "no stored row".
85
+ let existing;
86
+ try {
87
+ existing = ((await Promise.resolve(getExisting())) ?? null);
88
+ }
89
+ catch (err) {
90
+ return ownerCheckUnavailable(err);
91
+ }
58
92
  if (isForbiddenOwnerFieldChange(existing, content, ownerField, auth.agentId)) {
59
93
  return new Response(JSON.stringify({ error: "forbidden: the owner of a record cannot be changed" }), { status: 403, headers: { "content-type": "application/json" } });
60
94
  }