@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
@@ -5,7 +5,13 @@ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
6
  import { createRemoteJWKSet, jwtVerify } from "jose";
7
7
  import { stampOriginatorOnCreate } from "./originator-instance.js";
8
- import { claimIdJagJti, ReplayStoreUnavailable } from "./replay-store.js";
8
+ import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
9
+ import { credentialMapsPrincipal, credentialPrincipalId, isUsableCredential } from "../src/lib/credential-status-rule.js";
10
+ import { withKeyLock } from "./key-lock.js";
11
+ import { withOwnedTransaction } from "./request-transaction.js";
12
+ import { CommittedRowChanged, confirmCommittedRow, sameStoredRow } from "./write-back.js";
13
+ import { txnPausePoint } from "./txn-pause-point.js";
14
+ import { claimIdJagJti, idJagReplayDeps, ReplayStoreUnavailable, reportReplayStoreGapsAtBoot } from "./replay-store.js";
9
15
  /**
10
16
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
11
17
  *
@@ -44,6 +50,16 @@ export const ID_JAG_LONGEST_ACCEPTANCE_MS = ID_JAG_MAX_VALIDITY_MS + 2 * CLOCK_S
44
50
  * (both pinned by test/unit-isolated/xaa-jti-replay.test.ts).
45
51
  */
46
52
  export const ID_JAG_REPLAY_RETENTION_S = 90_000;
53
+ // Once per worker thread at boot, with the replay guards' own report: a
54
+ // misconfigured IdJagReplay table is named before the first jwt-bearer grant,
55
+ // not on the first claim.
56
+ export const XAA_JTI_REPLAY_BOOT_STORE = {
57
+ label: "XAA jti",
58
+ deps: idJagReplayDeps,
59
+ minRetentionMs: ID_JAG_LONGEST_ACCEPTANCE_MS,
60
+ retentionBasis: "an assertion can stay acceptable",
61
+ };
62
+ reportReplayStoreGapsAtBoot(XAA_JTI_REPLAY_BOOT_STORE);
47
63
  // JWKS remote key set cache per issuer (jose handles caching internally)
48
64
  const jwksSetCache = new Map();
49
65
  function sha256(input) {
@@ -126,83 +142,173 @@ export async function validateIdJag(assertion, expectedAudience) {
126
142
  throw new Error(`domain required but no hd/tid claim present — consumer account rejected`);
127
143
  }
128
144
  }
129
- // Replay prevention (jti): a jti claim, when present, must be a nonempty
130
- // string, and is then recorded once per instance, under a per-key lock,
131
- // before the grant has any effect. The record is kept
132
- // ID_JAG_REPLAY_RETENTION_S, so the assertion's validity is bounded first.
145
+ // A present jti must be a nonempty string with exp no further ahead than
146
+ // ID_JAG_MAX_VALIDITY_MS plus CLOCK_SKEW_MS. resolveOrCreatePrincipal claims
147
+ // it under the subject lock before provisioning and token issuance.
133
148
  if (payload.jti !== undefined) {
134
149
  if (typeof payload.jti !== "string" || payload.jti === "")
135
150
  throw new Error("jti claim must be a nonempty string");
136
151
  if (typeof payload.exp !== "number" || payload.exp * 1000 > Date.now() + ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS) {
137
152
  throw new Error(`an assertion with a jti must carry an exp at most ${ID_JAG_MAX_VALIDITY_MS / 3600_000} hours ahead`);
138
153
  }
139
- const claim = await claimIdJagJti(payload.jti, ID_JAG_LONGEST_ACCEPTANCE_MS);
140
- if (claim === "replay")
141
- throw new Error("token replay detected");
142
- if (claim !== "recorded")
143
- throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
144
154
  }
145
155
  return { payload: payload, idpConfig };
146
156
  }
147
157
  /**
148
158
  * Resolve or JIT-create a Principal from validated ID-JAG claims.
159
+ *
160
+ * Within one Harper process, the subject's per-key lock serializes the
161
+ * credential lookup and any JIT create. A lock miss refuses the grant (503).
162
+ */
163
+ async function resolveOrCreatePrincipal(payload, idpConfig, ctx) {
164
+ const store = databases?.flair?.Credential?.primaryStore;
165
+ const outcome = await withKeyLock(store, [XAA_PRINCIPAL_LOCK_NAMESPACE, idpConfig.id, String(payload.sub)], () => resolveOrCreatePrincipalLocked(payload, idpConfig, ctx), XAA_PRINCIPAL_LOCK_ATTEMPTS, XAA_PRINCIPAL_LOCK_WAIT_MS);
166
+ if (outcome.kind === "done")
167
+ return outcome.value;
168
+ throw new PrincipalProvisionBusy();
169
+ }
170
+ /** The subject's principal-provision lock namespace and wait (resources/key-lock.ts). */
171
+ export const XAA_PRINCIPAL_LOCK_NAMESPACE = "flair-xaa-principal";
172
+ const XAA_PRINCIPAL_LOCK_ATTEMPTS = 200;
173
+ const XAA_PRINCIPAL_LOCK_WAIT_MS = 10;
174
+ /** The named refusal of a grant that lost the principal-provision lock: refused, not retried into a second principal. */
175
+ export class PrincipalProvisionBusy extends Error {
176
+ constructor() {
177
+ super("principal provisioning for this subject is in progress; retry");
178
+ this.name = "PrincipalProvisionBusy";
179
+ }
180
+ }
181
+ /**
182
+ * `resolveOrCreatePrincipal`'s check-and-write, run while holding the subject's
183
+ * lock: the credential lookup, and the JIT principal + credential create it
184
+ * falls back to. Never called outside the lock.
149
185
  */
150
- async function resolveOrCreatePrincipal(payload, idpConfig) {
186
+ async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
187
+ // Claim jti after taking the subject lock, before provisioning and token
188
+ // issuance (flair#2333). A lock miss leaves it unclaimed; a retry can succeed
189
+ // if the assertion remains valid and the later grant steps succeed.
190
+ if (payload.jti !== undefined) {
191
+ const claim = await claimIdJagJti(payload.jti, ID_JAG_LONGEST_ACCEPTANCE_MS);
192
+ if (claim === "replay")
193
+ throw new Error("token replay detected");
194
+ if (claim !== "recorded")
195
+ throw new ReplayStoreUnavailable(`flair.IdJagReplay claim: ${claim}`);
196
+ }
151
197
  const idpSubject = payload.sub;
152
198
  const email = payload.email ?? payload.preferred_username;
153
199
  const displayName = payload.name ?? email ?? idpSubject;
154
- // Look for existing credential with this IdP subject
155
- for await (const cred of databases.flair.Credential.search({
156
- conditions: [
157
- { attribute: "kind", comparator: "equals", value: "idp" },
158
- { attribute: "idpSubject", comparator: "equals", value: idpSubject },
159
- { attribute: "idpProvider", comparator: "equals", value: idpConfig.id },
160
- ],
161
- })) {
162
- // Update last used
200
+ // Within one Harper process, the credential lookup and any JIT create run
201
+ // in an owned transaction that commits before the subject lock releases.
202
+ return withOwnedTransaction(ctx, async (owned) => {
203
+ // Look for existing credential with this IdP subject
204
+ for await (const cred of databases.flair.Credential.search({
205
+ conditions: [
206
+ { attribute: "kind", comparator: "equals", value: "idp" },
207
+ { attribute: "idpSubject", comparator: "equals", value: idpSubject },
208
+ { attribute: "idpProvider", comparator: "equals", value: idpConfig.id },
209
+ ],
210
+ }, owned)) {
211
+ // A matched credential completes a grant only when its status is
212
+ // "active" AND it names a principal (a non-empty string principalId): the
213
+ // rule the MCP resolver and the principal linker apply
214
+ // (src/lib/credential-status-rule.ts, `credentialMapsPrincipal`).
215
+ // `status` is a nullable String on schemas/agent.graphql whose documented
216
+ // values are "active" and "revoked" (a comment, not an enforced enum); the
217
+ // revoke path writes "revoked". Refuse it by name, naming the stored
218
+ // status, or that the credential names no principal: no credential touch
219
+ // and no OAuth token is written, so its lastUsedAt is left untouched. A
220
+ // present `jti` is claimed — and consumed — before this check, in its own
221
+ // transaction (the claim above, before the owned transaction).
222
+ if (!credentialMapsPrincipal(cred)) {
223
+ const state = isUsableCredential(cred) ? "names no principal" : `has status "${cred.status}"`;
224
+ throw new Error(`IdP credential for this subject ${state}; the jwt-bearer grant is refused`);
225
+ }
226
+ // Test-only: valid names are inert unless fault injection is enabled and
227
+ // armed (resources/txn-pause-point.ts). Holds this touch between the read
228
+ // above and the write below — the interleaving a revoke or delete of this
229
+ // credential would commit in.
230
+ const pause = txnPausePoint("xaa-credential-touch");
231
+ if (pause)
232
+ await pause;
233
+ // Update last used
234
+ await databases.flair.Credential.put({
235
+ ...cred,
236
+ lastUsedAt: nowISO(),
237
+ }, owned);
238
+ // A revoke or a delete committed while this touch was in flight (the
239
+ // read above through the write above) refuses the grant rather than
240
+ // being overwritten by the touch: re-read the COMMITTED row and abort
241
+ // the touch unless it is still this matched, active credential
242
+ // (resources/write-back.ts, confirmCommittedRow — the same confirmation
243
+ // the write-back helper runs once its write is staged). A change
244
+ // committed after this read and before the commit is not seen by it:
245
+ // Harper has no compare-and-set on a table write, so that sliver is
246
+ // outside what this grant can guarantee.
247
+ try {
248
+ await confirmCommittedRow(databases.flair.Credential, cred.id, (committed) => committed != null && credentialMapsPrincipal(committed) &&
249
+ sameStoredRow(committed, cred) &&
250
+ committed.principalId === cred.principalId &&
251
+ committed.kind === cred.kind &&
252
+ committed.idpSubject === cred.idpSubject &&
253
+ committed.idpProvider === cred.idpProvider);
254
+ }
255
+ catch (err) {
256
+ // Aborting this transaction discards the staged touch. Refuse the grant
257
+ // by name: the credential is gone, revoked, or no longer the one read.
258
+ if (err instanceof CommittedRowChanged) {
259
+ throw new Error("the matched IdP credential changed while the grant was in progress; the jwt-bearer grant is refused");
260
+ }
261
+ throw err;
262
+ }
263
+ return credentialPrincipalId(cred);
264
+ }
265
+ // No existing credential — JIT provision if enabled
266
+ if (!idpConfig.jitProvision) {
267
+ throw new Error(`no principal for IdP subject ${idpSubject} and JIT provisioning is disabled`);
268
+ }
269
+ // Test-only: pause after the lookup finds no credential, before JIT create.
270
+ const pause = txnPausePoint("xaa-principal-provision");
271
+ if (pause)
272
+ await pause;
273
+ const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
274
+ // flair#2359 — the shared agent-ID rule. The id above is built to conform,
275
+ // but the rule is enforced on the value that is actually written, so a future
276
+ // change to this construction cannot store an id AgentSeed would refuse.
277
+ if (!isValidAgentId(principalId))
278
+ throw new Error(invalidAgentIdMessage(principalId));
279
+ const now = nowISO();
280
+ // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
281
+ // stamp the local instance id (the Agent resource's post() does not run here).
282
+ const principalRow = {
283
+ id: principalId,
284
+ name: displayName,
285
+ displayName,
286
+ kind: "human",
287
+ type: "human",
288
+ status: "active",
289
+ publicKey: `idp:${idpConfig.id}:${idpSubject}`, // placeholder — humans don't have real Ed25519 keys
290
+ defaultTrustTier: idpConfig.defaultTrustTier ?? "unverified",
291
+ admin: false,
292
+ createdAt: now,
293
+ updatedAt: now,
294
+ };
295
+ await stampOriginatorOnCreate(principalRow);
296
+ await databases.flair.Agent.put(principalRow, owned);
297
+ // Create IdP credential
163
298
  await databases.flair.Credential.put({
164
- ...cred,
165
- lastUsedAt: nowISO(),
166
- });
167
- return cred.principalId;
168
- }
169
- // No existing credential — JIT provision if enabled
170
- if (!idpConfig.jitProvision) {
171
- throw new Error(`no principal for IdP subject ${idpSubject} and JIT provisioning is disabled`);
172
- }
173
- const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
174
- const now = nowISO();
175
- // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
176
- // stamp the local instance id (the Agent resource's post() does not run here).
177
- const principalRow = {
178
- id: principalId,
179
- name: displayName,
180
- displayName,
181
- kind: "human",
182
- type: "human",
183
- status: "active",
184
- publicKey: `idp:${idpConfig.id}:${idpSubject}`, // placeholder — humans don't have real Ed25519 keys
185
- defaultTrustTier: idpConfig.defaultTrustTier ?? "unverified",
186
- admin: false,
187
- createdAt: now,
188
- updatedAt: now,
189
- };
190
- await stampOriginatorOnCreate(principalRow);
191
- await databases.flair.Agent.put(principalRow);
192
- // Create IdP credential
193
- await databases.flair.Credential.put({
194
- id: `cred_idp_${randomBytes(8).toString("hex")}`,
195
- principalId,
196
- kind: "idp",
197
- label: idpConfig.name,
198
- status: "active",
199
- idpProvider: idpConfig.id,
200
- idpSubject,
201
- idpEmail: email,
202
- createdAt: now,
203
- lastUsedAt: now,
299
+ id: `cred_idp_${randomBytes(8).toString("hex")}`,
300
+ principalId,
301
+ kind: "idp",
302
+ label: idpConfig.name,
303
+ status: "active",
304
+ idpProvider: idpConfig.id,
305
+ idpSubject,
306
+ idpEmail: email,
307
+ createdAt: now,
308
+ lastUsedAt: now,
309
+ }, owned);
310
+ return principalId;
204
311
  });
205
- return principalId;
206
312
  }
207
313
  /**
208
314
  * Base URL an ID-JAG is validated against: `FLAIR_PUBLIC_URL` when set,
@@ -221,7 +327,7 @@ export function jwtBearerBaseUrl(env = process.env) {
221
327
  * Handle the jwt-bearer grant type at the token endpoint.
222
328
  * Called from OAuthToken when grant_type is urn:ietf:params:oauth:grant-type:jwt-bearer.
223
329
  */
224
- export async function handleJwtBearerGrant(data) {
330
+ export async function handleJwtBearerGrant(data, ctx) {
225
331
  const assertion = data?.assertion;
226
332
  if (!assertion) {
227
333
  return new Response(JSON.stringify({
@@ -233,7 +339,13 @@ export async function handleJwtBearerGrant(data) {
233
339
  try {
234
340
  const { payload, idpConfig } = await validateIdJag(assertion, baseUrl);
235
341
  // Resolve or create principal
236
- const principalId = await resolveOrCreatePrincipal(payload, idpConfig);
342
+ const principalId = await resolveOrCreatePrincipal(payload, idpConfig, ctx);
343
+ // Test-only: pause after the subject lock releases and the owned transaction
344
+ // commits, before this request's transaction commits (flair#2333).
345
+ const released = txnPausePoint("xaa-principal-lock-released");
346
+ if (released)
347
+ await released;
348
+ // Token writes follow the subject lock's release and can fail independently.
237
349
  // Determine scopes — intersection of ID-JAG scopes and IdP allowed scopes
238
350
  const requestedScopes = (payload.scope ?? "memory:read").split(" ");
239
351
  const allowedScopes = idpConfig.allowedScopes?.length
@@ -290,6 +402,12 @@ export async function handleJwtBearerGrant(data) {
290
402
  error_description: "replay_store_unavailable",
291
403
  }), { status: 503, headers: { "content-type": "application/json" } });
292
404
  }
405
+ if (err instanceof PrincipalProvisionBusy) {
406
+ return new Response(JSON.stringify({
407
+ error: "temporarily_unavailable",
408
+ error_description: "principal_provision_in_progress",
409
+ }), { status: 503, headers: { "content-type": "application/json" } });
410
+ }
293
411
  return new Response(JSON.stringify({
294
412
  error: "invalid_grant",
295
413
  error_description: err.message,
@@ -20,6 +20,7 @@ import { databases } from "harper";
20
20
  import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
21
21
  import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
22
22
  import { ADMIN_ROLE, agentRecordIsAdmin } from "./agent-admin.js";
23
+ import { isPrincipalDeactivated } from "../src/lib/principal-status.js";
23
24
  /**
24
25
  * Shared Harper user that verified Ed25519 agents resolve to (least-privilege
25
26
  * `flair_agent` role), replacing the old admin super_user elevation. Single
@@ -41,18 +42,28 @@ export const FLAIR_AGENT_USERNAME = "flair-agent";
41
42
  // nothing more. Existing tokens live until expiry or explicit revocation.
42
43
  // Do not read this as "deactivation now works" — it works for NEW auth only.
43
44
  /**
44
- * Single shared predicate: is this principal deactivated?
45
- *
46
- * Called from BOTH verify paths (Ed25519 and Basic/agent-auth) so the
47
- * deactivation check cannot drift. A nonexistent agent is not "deactivated" —
48
- * it will fail on other checks (missing publicKey, unknown user, etc.).
45
+ * Single shared predicate: re-exported from src/lib/principal-status.ts, which
46
+ * holds the rule. Called from BOTH verify paths (Ed25519 and Basic/agent-auth)
47
+ * and the human-readable `principal show`/`list` output (flair#2378).
49
48
  */
50
- export function isPrincipalDeactivated(agent) {
51
- if (agent == null)
52
- return false;
53
- if (agent.status === undefined)
54
- return false;
55
- return agent.status !== "active";
49
+ export { isPrincipalDeactivated };
50
+ /** Named refusal when a credentialed Basic-auth path cannot READ the Agent row. */
51
+ export const AGENT_LOOKUP_FAILED = "agent_lookup_failed";
52
+ /**
53
+ * Read the Agent row for a credentialed Basic-auth caller, distinguishing a read
54
+ * that SUCCEEDED and found no such row (`{ ok: true, agent: null }`) from a read
55
+ * that FAILED (`{ ok: false }`). A failed read is never an absent principal: the
56
+ * caller refuses with a named error rather than admitting a caller it could not
57
+ * check. The same rule resources/AgentSeed.ts and resources/originator-instance.ts
58
+ * apply to their own reads.
59
+ */
60
+ export async function readCredentialedPrincipal(agentId) {
61
+ try {
62
+ return { ok: true, agent: (await databases.flair.Agent.get(agentId)) ?? null };
63
+ }
64
+ catch (error) {
65
+ return { ok: false, error };
66
+ }
56
67
  }
57
68
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
58
69
  // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
@@ -176,6 +187,7 @@ export async function verifyAgentRequest(request) {
176
187
  catch { /* frozen request — fine, just no cache */ }
177
188
  return result;
178
189
  }
190
+ // (`error` names a refused unreadable lookup)
179
191
  /**
180
192
  * Three-way auth verdict for a resource — the safe replacement for the old
181
193
  * `if (!authAgent) → unfiltered/trusted` pattern that leaked to anonymous callers
@@ -322,6 +334,15 @@ function noteInternalVerdict(context) {
322
334
  const stack = (new Error().stack ?? "").split("\n").slice(2, 7).join("\n");
323
335
  console.error(INTERNAL_BY_OMISSION_WARNING + "\n" + stack);
324
336
  }
337
+ /**
338
+ * Refuse a credentialed Basic-auth caller whose Agent row could not be read:
339
+ * log the named error and return the deny verdict. A read that FAILED is never
340
+ * an absent principal and never admits (flair#2403).
341
+ */
342
+ function refuseUnreadablePrincipal(agentId, error) {
343
+ console.error("agent-auth: the credentialed principal lookup failed, so the request was refused", { agentId, error });
344
+ return { kind: "anonymous", error: AGENT_LOOKUP_FAILED };
345
+ }
325
346
  export async function resolveAgentAuth(context) {
326
347
  const c = context?.request ?? context;
327
348
  if (!c) {
@@ -348,15 +369,19 @@ export async function resolveAgentAuth(context) {
348
369
  const user = context?.user ?? c.user;
349
370
  if (credentialed && user?.role?.permission?.super_user === true) {
350
371
  const agentId = String(user.username ?? "admin");
351
- const agent = await databases.flair.Agent.get(agentId).catch(() => null);
352
- if (isPrincipalDeactivated(agent))
372
+ const read = await readCredentialedPrincipal(agentId);
373
+ if (!read.ok)
374
+ return refuseUnreadablePrincipal(agentId, read.error);
375
+ if (isPrincipalDeactivated(read.agent))
353
376
  return { kind: "anonymous" };
354
377
  return { kind: "agent", agentId, isAdmin: true };
355
378
  }
356
379
  if (credentialed && user?.username && user.username !== FLAIR_AGENT_USERNAME) {
357
380
  const agentId = String(user.username);
358
- const agent = await databases.flair.Agent.get(agentId).catch(() => null);
359
- if (isPrincipalDeactivated(agent))
381
+ const read = await readCredentialedPrincipal(agentId);
382
+ if (!read.ok)
383
+ return refuseUnreadablePrincipal(agentId, read.error);
384
+ if (isPrincipalDeactivated(read.agent))
360
385
  return { kind: "anonymous" };
361
386
  return { kind: "agent", agentId, isAdmin: false };
362
387
  }