@tpsdev-ai/flair 0.58.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -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 +1030 -343
  10. package/dist/commands/agent.js +384 -45
  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 +601 -163
  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 +146 -53
  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 +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  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 +120 -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 +27 -2
  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 +1775 -338
  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 +103 -7
  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 +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  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 +227 -64
  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/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -2,8 +2,12 @@ import { Resource, databases } from "harper";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { handleJwtBearerGrant } from "./XAA.js";
4
4
  import { resolveAgentAuth } from "./agent-auth.js";
5
+ import { claimOAuthSingleUse, oauthSingleUseDeps, reportReplayStoreGapsAtBoot, } from "./replay-store.js";
5
6
  import { decideRegistration } from "./dcr-gate.js";
6
7
  import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
8
+ import { txnPausePoint } from "./txn-pause-point.js";
9
+ import { withKeyLock } from "./key-lock.js";
10
+ import { withOwnedTransaction } from "./request-transaction.js";
7
11
  import { esc } from "./admin-layout.js";
8
12
  /**
9
13
  * OAuth 2.1 Authorization Server for Flair.
@@ -31,6 +35,68 @@ const ALLOWED_REDIRECT_ORIGIN = new URL(ALLOWED_REDIRECT_URI).origin;
31
35
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
32
36
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
33
37
  const AUTH_CODE_TTL_MS = 600_000; // 10 minutes
38
+ /**
39
+ * Seconds before a claim to redeem a code or rotate a refresh token may be
40
+ * removed (schemas/oauth.graphql: `expiration:` on `OAuthSingleUse`). MUST
41
+ * equal that value — both pinned by
42
+ * test/unit-isolated/oauth-single-use-2145.test.ts. It must outlive the longest
43
+ * either can be presented after its row is recorded: AUTH_CODE_TTL_MS, and
44
+ * REFRESH_TOKEN_TTL_MS.
45
+ */
46
+ export const OAUTH_SINGLE_USE_RETENTION_S = 691_200; // 8 days
47
+ /**
48
+ * The longest a code or refresh token can be presented after its row is
49
+ * recorded (AUTH_CODE_TTL_MS for a code, REFRESH_TOKEN_TTL_MS for a refresh
50
+ * token): the store must outlive this, and the boot report names a table that
51
+ * does not.
52
+ */
53
+ export const OAUTH_SINGLE_USE_MIN_RETENTION_MS = Math.max(AUTH_CODE_TTL_MS, REFRESH_TOKEN_TTL_MS);
54
+ // Once per worker thread at boot, with the replay guards' own report: a
55
+ // misconfigured OAuthSingleUse table is named before the first redemption.
56
+ export const OAUTH_SINGLE_USE_BOOT_STORE = {
57
+ label: "OAuth single-use",
58
+ deps: oauthSingleUseDeps,
59
+ minRetentionMs: OAUTH_SINGLE_USE_MIN_RETENTION_MS,
60
+ retentionBasis: "a redeemed authorization code or refresh token can be presented",
61
+ };
62
+ reportReplayStoreGapsAtBoot(OAUTH_SINGLE_USE_BOOT_STORE);
63
+ /** A store error: nothing is issued, and the caller may retry (fail closed). */
64
+ function storeUnavailable() {
65
+ return new Response(JSON.stringify({ error: "temporarily_unavailable", error_description: "replay_store_unavailable" }), {
66
+ status: 503,
67
+ headers: { "content-type": "application/json" },
68
+ });
69
+ }
70
+ /**
71
+ * Within one Harper process, rotation and revoke share a per-refresh-token
72
+ * lock (resources/key-lock.ts). Rotation holds it across its claim, committed
73
+ * row re-read, write and issuance; revoke takes it before writing `revokedAt`.
74
+ */
75
+ const OAUTH_TOKEN_LOCK_NAMESPACE = "flair-oauth-token";
76
+ /** The wait for the token's other holder: at most OAUTH_TOKEN_LOCK_ATTEMPTS × OAUTH_TOKEN_LOCK_WAIT_MS. */
77
+ const OAUTH_TOKEN_LOCK_ATTEMPTS = 200;
78
+ const OAUTH_TOKEN_LOCK_WAIT_MS = 10;
79
+ /** 503: this process's lock for this token's rotation and revoke stayed held. */
80
+ function tokenLifecycleBusy() {
81
+ return new Response(JSON.stringify({
82
+ error: "temporarily_unavailable",
83
+ error_description: "token_lifecycle_in_progress",
84
+ }), { status: 503, headers: { "content-type": "application/json" } });
85
+ }
86
+ /**
87
+ * Run `fn` holding this process's lock on refresh token `tokenHash`. A caller
88
+ * that cannot take the lock is refused — 503 `busy` when the lock stayed held
89
+ * elsewhere, 503 when the store has no lock — and `fn` does not run.
90
+ */
91
+ async function withTokenLifecycleLock(tokenHash, fn) {
92
+ const store = databases?.flair?.OAuthToken?.primaryStore;
93
+ const outcome = await withKeyLock(store, [OAUTH_TOKEN_LOCK_NAMESPACE, tokenHash], fn, OAUTH_TOKEN_LOCK_ATTEMPTS, OAUTH_TOKEN_LOCK_WAIT_MS);
94
+ if (outcome.kind === "done")
95
+ return { ok: true, value: outcome.value };
96
+ if (outcome.kind === "busy")
97
+ return { ok: false, response: tokenLifecycleBusy() };
98
+ return { ok: false, response: storeUnavailable() };
99
+ }
34
100
  /**
35
101
  * The scopes this server can issue, straight from the authorization-server
36
102
  * metadata — ONE source of truth, so the consent page can never render a scope
@@ -387,7 +453,7 @@ export class OAuthToken extends Resource {
387
453
  return this.handleRefreshToken(data);
388
454
  }
389
455
  else if (grantType === "urn:ietf:params:oauth:grant-type:jwt-bearer") {
390
- return handleJwtBearerGrant(data);
456
+ return handleJwtBearerGrant(data, this.getContext?.());
391
457
  }
392
458
  return new Response(JSON.stringify({ error: "unsupported_grant_type" }), {
393
459
  status: 400, headers: { "content-type": "application/json" },
@@ -445,6 +511,16 @@ export class OAuthToken extends Resource {
445
511
  });
446
512
  }
447
513
  }
514
+ // Claim to redeem once per instance under a per-key lock before any token
515
+ // is issued (resources/replay-store.ts).
516
+ const claim = await claimOAuthSingleUse("code", sha256(code), AUTH_CODE_TTL_MS);
517
+ if (claim === "unavailable")
518
+ return storeUnavailable();
519
+ if (claim === "replay") {
520
+ return new Response(JSON.stringify({ error: "invalid_grant", error_description: "code already used" }), {
521
+ status: 400, headers: { "content-type": "application/json" },
522
+ });
523
+ }
448
524
  // Mark code as used
449
525
  await databases.flair.OAuthAuthCode.put({ ...authCode, used: true });
450
526
  // Issue tokens
@@ -490,20 +566,93 @@ export class OAuthToken extends Resource {
490
566
  status: 400, headers: { "content-type": "application/json" },
491
567
  });
492
568
  }
493
- // Rotate: revoke old refresh token, issue new pair
494
- await databases.flair.OAuthToken.put({
495
- ...refreshRecord,
496
- revokedAt: nowISO(),
569
+ // Test-only: valid names are inert unless fault injection is enabled and
570
+ // armed (resources/txn-pause-point.ts). Holds this rotation between the
571
+ // read above and the claim below — the interleaving where a revoke of the
572
+ // same token commits first. Such a revoke records the token's single-use
573
+ // claim (`r:<hash>`), so the rotation's own claim below is a replay and
574
+ // refuses it there, before the committed-row re-read is reached.
575
+ const pause = txnPausePoint("oauth-refresh-pre-claim");
576
+ if (pause)
577
+ await pause;
578
+ // Within one Harper process, claim, re-read, write and issuance hold the
579
+ // same token lock OAuthRevoke takes. A revoke's recorded claim refuses a
580
+ // later rotation; the re-read also covers a committed row change that did
581
+ // not record that claim. A rotation that cannot take the lock is refused.
582
+ const outcome = await withTokenLifecycleLock(tokenHash, async () => {
583
+ // Claim to rotate once per instance under a per-key lock before the new
584
+ // pair is issued (resources/replay-store.ts). A revoke of this refresh
585
+ // token records the same claim (OAuthRevoke below), so a revoke that
586
+ // committed before this claim makes it a replay.
587
+ const claim = await claimOAuthSingleUse("refresh", tokenHash, REFRESH_TOKEN_TTL_MS);
588
+ if (claim === "unavailable")
589
+ return storeUnavailable();
590
+ if (claim === "replay") {
591
+ return new Response(JSON.stringify({ error: "invalid_grant", error_description: "token revoked" }), {
592
+ status: 400, headers: { "content-type": "application/json" },
593
+ });
594
+ }
595
+ // Test-only: holds this rotation between its single-use claim above and
596
+ // its committed-row re-read below, while it holds the token lock. A
597
+ // competing write of `revokedAt` that does NOT take this lock and does
598
+ // NOT record the claim (so the claim above could not refuse it) can
599
+ // commit here; the re-read below is then the only check that refuses the
600
+ // rotation.
601
+ const midClaimPause = txnPausePoint("oauth-refresh-mid-claim");
602
+ if (midClaimPause)
603
+ await midClaimPause;
604
+ // The committed-row re-read, the old row's write and the new pair's
605
+ // issuance run in a FRESH OWNED transaction (withOwnedTransaction,
606
+ // resources/request-transaction.ts) that COMMITS before this token's lock
607
+ // releases. Harper wraps this POST in a REQUEST transaction that commits
608
+ // only after the handler returns, so writes that joined it would still be
609
+ // invisible when the lock frees — a request that looked at the row right
610
+ // after release would read it unrevoked. The re-read reads the row IN that
611
+ // owned transaction: committed state, never this request's earlier
612
+ // snapshot. (The single-use claim above is its own awaited transaction.)
613
+ const ctx = this.getContext?.() ?? {};
614
+ return await withOwnedTransaction(ctx, async (owned) => {
615
+ // Re-read the COMMITTED row and refuse unless it is still this token,
616
+ // unrevoked, including row changes that did not record the claim.
617
+ const committed = await databases.flair.OAuthToken.get(refreshRecord.id, owned);
618
+ if (!committed || committed.tokenHash !== tokenHash || committed.revokedAt) {
619
+ return new Response(JSON.stringify({ error: "invalid_grant", error_description: "token revoked" }), {
620
+ status: 400, headers: { "content-type": "application/json" },
621
+ });
622
+ }
623
+ // Test-only: holds this rotation between the re-read above and the write
624
+ // and issuance below, while it holds the token lock — the interleaving
625
+ // where a revoke of this token would commit between them.
626
+ const postClaimPause = txnPausePoint("oauth-refresh-post-claim");
627
+ if (postClaimPause)
628
+ await postClaimPause;
629
+ // Rotate: revoke old refresh token, issue new pair — both in `owned`, so
630
+ // they commit before the lock releases.
631
+ await databases.flair.OAuthToken.put({
632
+ ...committed,
633
+ revokedAt: nowISO(),
634
+ }, owned);
635
+ return this.issueTokenPair(committed.clientId, committed.principalId, committed.scope, owned);
636
+ });
497
637
  });
498
- return this.issueTokenPair(refreshRecord.clientId, refreshRecord.principalId, refreshRecord.scope);
638
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
639
+ // Pauses AFTER the token lock released (and, with the owned transaction
640
+ // above, after the rotation's writes committed) but BEFORE this request's own
641
+ // transaction commits (Harper commits it when the handler returns). A request
642
+ // that looks at the token right here must see the committed revocation.
643
+ const claimDone = txnPausePoint("oauth-refresh-claim-done");
644
+ if (claimDone)
645
+ await claimDone;
646
+ return outcome.ok ? outcome.value : outcome.response;
499
647
  }
500
- async issueTokenPair(clientId, principalId, scope) {
648
+ async issueTokenPair(clientId, principalId, scope, ctx) {
649
+ const put = (row) => ctx ? databases.flair.OAuthToken.put(row, ctx) : databases.flair.OAuthToken.put(row);
501
650
  const now = nowISO();
502
651
  const accessTokenRaw = randomToken("flair_at_");
503
652
  const refreshTokenRaw = randomToken("flair_rt_");
504
653
  const accessId = `at_${randomBytes(8).toString("hex")}`;
505
654
  const refreshId = `rt_${randomBytes(8).toString("hex")}`;
506
- await databases.flair.OAuthToken.put({
655
+ await put({
507
656
  id: accessId,
508
657
  tokenHash: sha256(accessTokenRaw),
509
658
  tokenType: "access",
@@ -513,7 +662,7 @@ export class OAuthToken extends Resource {
513
662
  expiresAt: futureISO(ACCESS_TOKEN_TTL_MS),
514
663
  createdAt: now,
515
664
  });
516
- await databases.flair.OAuthToken.put({
665
+ await put({
517
666
  id: refreshId,
518
667
  tokenHash: sha256(refreshTokenRaw),
519
668
  tokenType: "refresh",
@@ -549,6 +698,34 @@ export class OAuthRevoke extends Resource {
549
698
  for await (const t of databases.flair.OAuthToken.search({
550
699
  conditions: [{ attribute: "tokenHash", comparator: "equals", value: tokenHash }],
551
700
  })) {
701
+ // Within one Harper process, a refresh rotation takes this token's lock
702
+ // across its claim, committed-row re-read, write and issuance, recording the
703
+ // single-use claim `r:<hash>` (OAuthToken above). The revoke takes the
704
+ // same lock before it records `revokedAt`, so it is serialized with an
705
+ // in-flight rotation and cannot commit between that rotation's re-read
706
+ // and its issuance. A claim that is already recorded — the token was
707
+ // already rotated, or this is a repeat revoke — is not an error: the
708
+ // revoke still records `revokedAt` below. An access token has no rotation
709
+ // to serialize with.
710
+ if (t.tokenType === "refresh") {
711
+ const outcome = await withTokenLifecycleLock(tokenHash, async () => {
712
+ // If this refresh-token revoke cannot record its claim, return 503
713
+ // without writing `revokedAt`.
714
+ const claim = await claimOAuthSingleUse("refresh", tokenHash, REFRESH_TOKEN_TTL_MS);
715
+ if (claim === "unavailable")
716
+ return storeUnavailable();
717
+ await databases.flair.OAuthToken.put({
718
+ ...t,
719
+ revokedAt: nowISO(),
720
+ });
721
+ return undefined;
722
+ });
723
+ if (!outcome.ok)
724
+ return outcome.response;
725
+ if (outcome.value)
726
+ return outcome.value;
727
+ continue;
728
+ }
552
729
  await databases.flair.OAuthToken.put({
553
730
  ...t,
554
731
  revokedAt: nowISO(),
@@ -4,16 +4,23 @@
4
4
  * Auth (self-enforced now that the global gate is non-rejecting):
5
5
  * Read — any verified agent/admin (org-scoped); anonymous denied.
6
6
  * Write — authorId must match the authenticated agent (or admin); anonymous denied.
7
+ * createdAt — assigned by the server on create; a write that reaches the
8
+ * createdAt check cannot change a stored row's value, and a
9
+ * record whose id the check does not read is refused there
10
+ * (resources/org-event-created-at.ts).
7
11
  *
8
12
  * The previous version read context.request.tpsAgent and treated a MISSING agent
9
13
  * as trusted (`if (agentId && …)` / `if (!agentId) super.delete`), so anonymous
10
14
  * requests slipped through once the gate stopped rejecting. resolveAgentAuth
11
15
  * distinguishes internal/agent/anonymous explicitly.
12
16
  */
17
+ import { randomUUID } from "node:crypto";
13
18
  import { databases } from "harper";
14
19
  import { resolveAgentAuth } from "./agent-auth.js";
20
+ import { guardObjectBody } from "./object-body-guard.js";
15
21
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
16
22
  import { invalidEntitiesResponse } from "./entity-vocab.js";
23
+ import { applyServerCreatedAt, collectionElementIdRefusal, createdAtCheckUnavailable, invalidEventId, unreadableEventIdRefusal, } from "./org-event-created-at.js";
17
24
  import { makeAuthGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
18
25
  import { RECORD_TYPES } from "./record-types.js";
19
26
  // See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
@@ -22,10 +29,59 @@ import { RECORD_TYPES } from "./record-types.js";
22
29
  const orgEventAuthGate = makeAuthGate();
23
30
  export class OrgEvent extends databases.flair.OrgEvent {
24
31
  allowRead() { return orgEventAuthGate.call(this); }
32
+ /**
33
+ * Scans the collection body on the initial collection-PUT call, before
34
+ * Harper's per-element dispatch. The scan skips non-record elements.
35
+ */
36
+ static getResource(target, request, options) {
37
+ const admitted = super.getResource(target, request, options);
38
+ if (this !== OrgEvent || !options?.isCollection || options.method !== "put")
39
+ return admitted;
40
+ return Promise.resolve(admitted).then(async (resource) => {
41
+ const denial = collectionElementIdRefusal(await request?.data);
42
+ if (denial)
43
+ throw denial;
44
+ return resource;
45
+ });
46
+ }
25
47
  _auth() {
26
48
  return resolveAgentAuth(this.getContext?.());
27
49
  }
50
+ /**
51
+ * The createdAt check (resources/org-event-created-at.ts), run after this
52
+ * verb's earlier checks. Applies to each record the write stores — the
53
+ * content itself, or each element of an array body — reading the stored row
54
+ * at the id the write lands on: server time with no stored row, the stored
55
+ * value (whatever it is) with one. A record that is not an object, or whose
56
+ * id the check does not read (isReadableEventId), is refused with
57
+ * `invalid_event_id` (400) before any write.
58
+ */
59
+ async _assignCreatedAt(content, mode, idOf) {
60
+ const records = Array.isArray(content) ? content : [content];
61
+ for (const record of records) {
62
+ if (record == null || typeof record !== "object" || Array.isArray(record))
63
+ return invalidEventId();
64
+ const id = idOf(record);
65
+ const idDenial = unreadableEventIdRefusal(id);
66
+ if (idDenial)
67
+ return idDenial;
68
+ let stored;
69
+ try {
70
+ stored = ((await databases.flair.OrgEvent.get(id, {})) ?? null);
71
+ }
72
+ catch (err) {
73
+ return createdAtCheckUnavailable(err);
74
+ }
75
+ const denial = applyServerCreatedAt(record, stored, mode);
76
+ if (denial)
77
+ return denial;
78
+ }
79
+ return null;
80
+ }
28
81
  async post(content) {
82
+ const bodyDenial = guardObjectBody(content);
83
+ if (bodyDenial)
84
+ return bodyDenial;
29
85
  const auth = await this._auth();
30
86
  if (auth.kind === "anonymous")
31
87
  return UNAUTH();
@@ -44,27 +100,85 @@ export class OrgEvent extends databases.flair.OrgEvent {
44
100
  // the forbiddenMessage arg is dead for this mode, passed for signature
45
101
  // completeness only.
46
102
  stampAttribution(auth, content, RECORD_TYPES.OrgEvent.ownerField, RECORD_TYPES.OrgEvent.attribution.post, "forbidden: unreachable for stamp-default");
47
- if (!content.id)
48
- content.id = `${content.authorId}-${new Date().toISOString()}`;
49
- content.createdAt = new Date().toISOString();
103
+ // An addressed POST binds a missing or null body id, and a string or number
104
+ // body id whose text matches the address, to getId(); any other id type is
105
+ // left unchanged by this step.
106
+ // At /OrgEvent/, an absent, null or empty body id generates an id.
107
+ // At /OrgEvent/<prefix>/, a missing body id takes the target id (<prefix>/).
108
+ const addressedId = this.getId?.();
109
+ const addressed = typeof addressedId === "string" || typeof addressedId === "number";
110
+ // A missing or null body id binds to the address; a string or number body id
111
+ // binds when its text matches the address. Any other id type is left
112
+ // unchanged by this binding step. Later checks apply to it where the write reaches
113
+ // them: isReadableEventId first (an invalid id is refused there), then the
114
+ // ownership check and, outside internal calls, the createdAt check.
115
+ if (content && typeof content === "object" && addressed &&
116
+ (content.id == null ||
117
+ ((typeof content.id === "string" || typeof content.id === "number") &&
118
+ String(content.id) === String(addressedId)))) {
119
+ content.id = addressedId;
120
+ }
121
+ // flair#2333 (H9): avoids deterministic same-millisecond collisions (random UUID).
122
+ if (!addressed && (content.id == null || content.id === ""))
123
+ content.id = `${content.authorId}-${new Date().toISOString()}-${randomUUID()}`;
124
+ // Binding runs before validation. At the root collection, or an addressed
125
+ // path whose body id was not bound, a remaining id the shared id rule does
126
+ // not read is refused with invalid_event_id (400) before the ownership lookup.
127
+ const idDenial = unreadableEventIdRefusal(content.id);
128
+ if (idDenial)
129
+ return idDenial;
130
+ // A trusted in-process call keeps its existing stamp; every verified agent's
131
+ // createdAt is assigned below, once the write passes its other checks.
132
+ if (auth.kind === "internal")
133
+ content.createdAt = new Date().toISOString();
50
134
  // attention-plane vocabulary gate (flair#675): `entities`, if present,
51
135
  // must be well-formed vocabulary strings — see resources/entity-vocab.ts.
52
136
  // Field is additive/optional; absent entities is not an error.
53
137
  const entitiesError = invalidEntitiesResponse(content.entities);
54
138
  if (entitiesError)
55
139
  return entitiesError;
140
+ // flair#2333 (N2): refuses a non-admin POST naming a row observed at the
141
+ // guard's lookup as owned by another agent. This read-then-write check is
142
+ // not atomic; a row appearing after the lookup is not covered.
143
+ const ownerDenial = await guardOwnerFieldImmutable(this, () => databases.flair.OrgEvent.get(content.id, {}), content, RECORD_TYPES.OrgEvent.ownerField);
144
+ if (ownerDenial)
145
+ return ownerDenial;
146
+ // createdAt: server time with no stored row; the stored value with one; a
147
+ // record whose id the check does not read is refused. (The id rule above
148
+ // means only a non-empty string or a non-empty array of strings reaches it.)
149
+ if (auth.kind !== "internal") {
150
+ const createdAtDenial = await this._assignCreatedAt(content, "replace", (record) => record.id);
151
+ if (createdAtDenial)
152
+ return createdAtDenial;
153
+ }
56
154
  // Harper 5: table resources use put() for create/upsert (post() removed).
57
155
  return databases.flair.OrgEvent.put(content);
58
156
  }
59
157
  // PATCH routes past put(), so authorId immutability is enforced on both verbs
60
158
  // via the one shared delegate.
61
159
  async patch(content, query) {
160
+ const bodyDenial = guardObjectBody(content);
161
+ if (bodyDenial)
162
+ return bodyDenial;
62
163
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "authorId");
63
164
  if (denial)
64
165
  return denial;
166
+ // createdAt: PATCH writes the row its URL names, so the stored value is read
167
+ // there; a URL with no id the check reads (the collection) is refused. An
168
+ // omitted createdAt is left out of the merge and keeps that value.
169
+ const auth = await this._auth();
170
+ if (auth.kind !== "internal") {
171
+ const pathId = this.getId?.();
172
+ const createdAtDenial = await this._assignCreatedAt(content, "merge", () => pathId);
173
+ if (createdAtDenial)
174
+ return createdAtDenial;
175
+ }
65
176
  return super.patch(content, query);
66
177
  }
67
178
  async put(content) {
179
+ const bodyDenial = guardObjectBody(content, { allowArrayObjects: true });
180
+ if (bodyDenial)
181
+ throw bodyDenial;
68
182
  const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "authorId");
69
183
  if (__ownerDenial)
70
184
  return __ownerDenial;
@@ -82,6 +196,15 @@ export class OrgEvent extends databases.flair.OrgEvent {
82
196
  const entitiesError = invalidEntitiesResponse(content.entities);
83
197
  if (entitiesError)
84
198
  return entitiesError;
199
+ // createdAt: server time with no stored row; the stored value with one,
200
+ // read under each record's own id; a record whose id the check does not
201
+ // read is refused. A refusal is thrown, so one refused record fails the whole
202
+ // request and nothing in it is written.
203
+ if (auth.kind !== "internal") {
204
+ const createdAtDenial = await this._assignCreatedAt(content, "replace", (record) => record.id);
205
+ if (createdAtDenial)
206
+ throw createdAtDenial;
207
+ }
85
208
  return databases.flair.OrgEvent.put(content);
86
209
  }
87
210
  async delete(id, context) {
@@ -0,0 +1,209 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { databases } from "harper";
3
+ import { resolveAgentAuth } from "./agent-auth.js";
4
+ import { resolveStoredRow } from "./originator-instance.js";
5
+ import { FORBIDDEN, NOT_FOUND, UNAUTH, makeAuthGate } from "./record-type-kit.js";
6
+ import { withKeyLock } from "./key-lock.js";
7
+ import { withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
8
+ import { PRIORITY_RANK } from "./skill-provenance.js";
9
+ import { soulWriteSource } from "./soul-write-policy.js";
10
+ /**
11
+ * OrgSkillAssignment — org-scope skill assignments (flair#2141 S1).
12
+ *
13
+ * A row assigns `skillRef` under `skillName` and `priority`;
14
+ * bootstrap's skills manifest resolves it for an agent that receives org
15
+ * skills (resources/skill-manifest.ts).
16
+ *
17
+ * Writes: post, put, patch and delete each require the operator source
18
+ * (`soulWriteSource`: verified Basic admin auth, or the deliberate internal
19
+ * marker). Agent keys, admin agent keys included, are refused. `writer`,
20
+ * `sourceClass`, `createdAt` and `updatedAt` are server-stamped; other body
21
+ * fields are not stored. Reads: any verified agent.
22
+ *
23
+ * History: each accepted write appends an OrgSkillAssignmentHistory row
24
+ * (actor, source class, a hash of the stored row before the write) in the
25
+ * write's transaction. put, patch and delete hold a per-assignment lock shared
26
+ * by the threads of this Harper process (`withAssignmentLock`) while they read
27
+ * the stored row and commit. Writes on other replicated nodes are not covered
28
+ * by that lock.
29
+ */
30
+ const TABLE = "OrgSkillAssignment";
31
+ /** The stored fields, in the order `previousHash` covers them. */
32
+ const HASHED_FIELDS = ["id", "skillName", "skillRef", "priority", "createdAt", "updatedAt", "writer", "sourceClass"];
33
+ /** sha256 over a stored row's fields (HASHED_FIELDS), for `previousHash`. */
34
+ export function assignmentHash(row) {
35
+ const canonical = JSON.stringify(HASHED_FIELDS.map((field) => [field, row[field] ?? null]));
36
+ return createHash("sha256").update(canonical).digest("hex");
37
+ }
38
+ function badRequest(error, message) {
39
+ return new Response(JSON.stringify({ error, message }), {
40
+ status: 400, headers: { "Content-Type": "application/json" },
41
+ });
42
+ }
43
+ async function authorizeOperator(self) {
44
+ const context = self.getContext?.();
45
+ const auth = await resolveAgentAuth(context);
46
+ if (auth.kind === "anonymous")
47
+ return UNAUTH();
48
+ const sourceClass = soulWriteSource(context, auth);
49
+ if (!sourceClass)
50
+ return FORBIDDEN("org_skill_assignment_requires_operator: use operator credentials");
51
+ return { writer: auth.kind === "agent" ? auth.agentId : null, sourceClass };
52
+ }
53
+ /** The URL-bound row id, or null on a collection address. */
54
+ function boundId(self) {
55
+ try {
56
+ const id = self.getId?.();
57
+ if (typeof id === "string" && id.length > 0)
58
+ return id;
59
+ if (typeof id === "number")
60
+ return String(id);
61
+ }
62
+ catch {
63
+ /* no bound id */
64
+ }
65
+ return null;
66
+ }
67
+ function isRecord(value) {
68
+ return !!value && typeof value === "object" && !Array.isArray(value);
69
+ }
70
+ function validFields(body) {
71
+ const { skillName, skillRef, priority = "standard" } = body;
72
+ if (typeof skillName !== "string" || skillName.trim() === "") {
73
+ return badRequest("skill_name_required", "skillName must be a non-empty string");
74
+ }
75
+ if (typeof skillRef !== "string" || skillRef.trim() === "") {
76
+ return badRequest("skill_ref_required", "skillRef must be a non-empty string");
77
+ }
78
+ if (typeof priority !== "string" || !Object.hasOwn(PRIORITY_RANK, priority)) {
79
+ return badRequest("invalid_priority", `priority must be one of ${Object.keys(PRIORITY_RANK).join(", ")}`);
80
+ }
81
+ return { skillName, skillRef, priority };
82
+ }
83
+ async function appendHistory(context, assignmentId, op, previous, who, at) {
84
+ await databases.flair.OrgSkillAssignmentHistory.put({
85
+ id: randomUUID(),
86
+ assignmentId,
87
+ op,
88
+ actor: who.writer,
89
+ sourceClass: who.sourceClass,
90
+ previousHash: previous ? assignmentHash(previous) : null,
91
+ at,
92
+ }, context);
93
+ }
94
+ const LOCK_NAMESPACE = "flair-org-skill-assignment";
95
+ /** The wait for another write to the same assignment: at most LOCK_ATTEMPTS × LOCK_WAIT_MS. */
96
+ const LOCK_ATTEMPTS = 200;
97
+ const LOCK_WAIT_MS = 10;
98
+ /**
99
+ * Run `fn` holding this process's lock on assignment `id` (resources/key-lock.ts).
100
+ * `fn` must commit before it returns. 409 when the lock stays held
101
+ * past the wait; 503 when the store has no lock.
102
+ */
103
+ async function withAssignmentLock(id, fn) {
104
+ const store = databases.flair.OrgSkillAssignment?.primaryStore;
105
+ const outcome = await withKeyLock(store, [LOCK_NAMESPACE, id], fn, LOCK_ATTEMPTS, LOCK_WAIT_MS);
106
+ if (outcome.kind === "done")
107
+ return outcome.value;
108
+ if (outcome.kind === "busy") {
109
+ return new Response(JSON.stringify({
110
+ error: "org_skill_assignment_busy",
111
+ message: "another write to this assignment is still in progress; retry",
112
+ }), { status: 409, headers: { "Content-Type": "application/json" } });
113
+ }
114
+ return new Response(JSON.stringify({
115
+ error: "org_skill_assignment_lock_unavailable",
116
+ message: "the OrgSkillAssignment store has no per-key lock, so the write was refused",
117
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
118
+ }
119
+ const authGate = makeAuthGate();
120
+ export class OrgSkillAssignment extends databases.flair.OrgSkillAssignment {
121
+ allowRead() { return authGate.call(this); }
122
+ async post(content, context) {
123
+ const who = await authorizeOperator(this);
124
+ if (who instanceof Response)
125
+ return who;
126
+ if (boundId(this))
127
+ return badRequest("org_skill_assignment_post_to_collection", "create an assignment with POST /OrgSkillAssignment/");
128
+ if (!isRecord(content))
129
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
130
+ const fields = validFields(content);
131
+ if (fields instanceof Response)
132
+ return fields;
133
+ const at = new Date().toISOString();
134
+ const record = { id: randomUUID(), ...fields, createdAt: at, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
135
+ return withSharedWriteTransaction(this.getContext?.(), async (shared) => {
136
+ await appendHistory(shared, record.id, "create", null, who, at);
137
+ return super.post(record, context);
138
+ });
139
+ }
140
+ async put(content, context) {
141
+ const who = await authorizeOperator(this);
142
+ if (who instanceof Response)
143
+ return who;
144
+ const id = boundId(this);
145
+ if (!id)
146
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PUT /OrgSkillAssignment/<id>");
147
+ if (!isRecord(content))
148
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
149
+ const fields = validFields(content);
150
+ if (fields instanceof Response)
151
+ return fields;
152
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
153
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
154
+ if (stored.denial)
155
+ return stored.denial;
156
+ const at = new Date().toISOString();
157
+ const createdAt = typeof stored.row?.createdAt === "string" ? stored.row.createdAt : at;
158
+ const record = { id, ...fields, createdAt, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
159
+ await appendHistory(shared, id, stored.row ? "update" : "create", stored.row, who, at);
160
+ return super.put(record, context);
161
+ }));
162
+ }
163
+ async patch(content, query) {
164
+ const who = await authorizeOperator(this);
165
+ if (who instanceof Response)
166
+ return who;
167
+ const id = boundId(this);
168
+ if (!id)
169
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PATCH /OrgSkillAssignment/<id>");
170
+ if (!isRecord(content))
171
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
172
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
173
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
174
+ if (stored.denial)
175
+ return stored.denial;
176
+ if (!stored.row)
177
+ return NOT_FOUND();
178
+ const merged = {};
179
+ for (const field of ["skillName", "skillRef", "priority"]) {
180
+ merged[field] = Object.hasOwn(content, field) ? content[field] : stored.row[field];
181
+ }
182
+ const fields = validFields(merged);
183
+ if (fields instanceof Response)
184
+ return fields;
185
+ const at = new Date().toISOString();
186
+ const changes = { ...fields, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
187
+ await appendHistory(shared, id, "update", stored.row, who, at);
188
+ return super.patch(changes, query);
189
+ }));
190
+ }
191
+ async delete(target) {
192
+ const who = await authorizeOperator(this);
193
+ if (who instanceof Response)
194
+ return who;
195
+ const id = boundId(this);
196
+ if (!id)
197
+ return badRequest("org_skill_assignment_id_required", "address one assignment: DELETE /OrgSkillAssignment/<id>");
198
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
199
+ const stored = await resolveStoredRow(this, TABLE, undefined, () => super.get());
200
+ if (stored.denial)
201
+ return stored.denial;
202
+ if (!stored.row)
203
+ return NOT_FOUND();
204
+ const at = new Date().toISOString();
205
+ await appendHistory(shared, id, "delete", stored.row, who, at);
206
+ return super.delete(target);
207
+ }));
208
+ }
209
+ }