@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
@@ -5,6 +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 { 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";
8
15
  /**
9
16
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
10
17
  *
@@ -24,7 +31,35 @@ import { stampOriginatorOnCreate } from "./originator-instance.js";
24
31
  */
25
32
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
26
33
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
27
- const CLOCK_SKEW_MS = 30_000; // 30 seconds
34
+ export const CLOCK_SKEW_MS = 30_000; // 30 seconds
35
+ /**
36
+ * An assertion that carries a `jti` is refused unless its `exp` is at most this
37
+ * far ahead of now, plus CLOCK_SKEW_MS (flair#2073).
38
+ */
39
+ export const ID_JAG_MAX_VALIDITY_MS = 24 * 3600_000;
40
+ /**
41
+ * The longest an accepted assertion stays acceptable after its jti is recorded.
42
+ * jose compares exp with the current whole second, so it accepts an assertion
43
+ * only before exp + CLOCK_SKEW_MS + 1 s, and exp is at most
44
+ * ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS ahead when it is recorded.
45
+ */
46
+ export const ID_JAG_LONGEST_ACCEPTANCE_MS = ID_JAG_MAX_VALIDITY_MS + 2 * CLOCK_SKEW_MS + 1000;
47
+ /**
48
+ * Seconds a newly recorded jti row is kept: 25 h, longer than ID_JAG_LONGEST_ACCEPTANCE_MS.
49
+ * MUST equal `expiration:` on `type IdJagReplay` in schemas/oauth.graphql
50
+ * (both pinned by test/unit-isolated/xaa-jti-replay.test.ts).
51
+ */
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);
28
63
  // JWKS remote key set cache per issuer (jose handles caching internally)
29
64
  const jwksSetCache = new Map();
30
65
  function sha256(input) {
@@ -107,79 +142,173 @@ export async function validateIdJag(assertion, expectedAudience) {
107
142
  throw new Error(`domain required but no hd/tid claim present — consumer account rejected`);
108
143
  }
109
144
  }
110
- // Replay prevention (jti)
111
- if (payload.jti) {
112
- const existing = await databases.flair.IdJagReplay.get(payload.jti);
113
- if (existing)
114
- throw new Error("token replay detected");
115
- const now = Date.now();
116
- await databases.flair.IdJagReplay.put({
117
- id: payload.jti,
118
- expiresAt: futureISO(Math.max((payload.exp ?? 0) * 1000 - now + CLOCK_SKEW_MS, 300_000)),
119
- createdAt: nowISO(),
120
- });
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.
148
+ if (payload.jti !== undefined) {
149
+ if (typeof payload.jti !== "string" || payload.jti === "")
150
+ throw new Error("jti claim must be a nonempty string");
151
+ if (typeof payload.exp !== "number" || payload.exp * 1000 > Date.now() + ID_JAG_MAX_VALIDITY_MS + CLOCK_SKEW_MS) {
152
+ throw new Error(`an assertion with a jti must carry an exp at most ${ID_JAG_MAX_VALIDITY_MS / 3600_000} hours ahead`);
153
+ }
121
154
  }
122
155
  return { payload: payload, idpConfig };
123
156
  }
124
157
  /**
125
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.
126
185
  */
127
- 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
+ }
128
197
  const idpSubject = payload.sub;
129
198
  const email = payload.email ?? payload.preferred_username;
130
199
  const displayName = payload.name ?? email ?? idpSubject;
131
- // Look for existing credential with this IdP subject
132
- for await (const cred of databases.flair.Credential.search({
133
- conditions: [
134
- { attribute: "kind", comparator: "equals", value: "idp" },
135
- { attribute: "idpSubject", comparator: "equals", value: idpSubject },
136
- { attribute: "idpProvider", comparator: "equals", value: idpConfig.id },
137
- ],
138
- })) {
139
- // 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
140
298
  await databases.flair.Credential.put({
141
- ...cred,
142
- lastUsedAt: nowISO(),
143
- });
144
- return cred.principalId;
145
- }
146
- // No existing credential — JIT provision if enabled
147
- if (!idpConfig.jitProvision) {
148
- throw new Error(`no principal for IdP subject ${idpSubject} and JIT provisioning is disabled`);
149
- }
150
- const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
151
- const now = nowISO();
152
- // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
153
- // stamp the local instance id (the Agent resource's post() does not run here).
154
- const principalRow = {
155
- id: principalId,
156
- name: displayName,
157
- displayName,
158
- kind: "human",
159
- type: "human",
160
- status: "active",
161
- publicKey: `idp:${idpConfig.id}:${idpSubject}`, // placeholder — humans don't have real Ed25519 keys
162
- defaultTrustTier: idpConfig.defaultTrustTier ?? "unverified",
163
- admin: false,
164
- createdAt: now,
165
- updatedAt: now,
166
- };
167
- await stampOriginatorOnCreate(principalRow);
168
- await databases.flair.Agent.put(principalRow);
169
- // Create IdP credential
170
- await databases.flair.Credential.put({
171
- id: `cred_idp_${randomBytes(8).toString("hex")}`,
172
- principalId,
173
- kind: "idp",
174
- label: idpConfig.name,
175
- status: "active",
176
- idpProvider: idpConfig.id,
177
- idpSubject,
178
- idpEmail: email,
179
- createdAt: now,
180
- 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;
181
311
  });
182
- return principalId;
183
312
  }
184
313
  /**
185
314
  * Base URL an ID-JAG is validated against: `FLAIR_PUBLIC_URL` when set,
@@ -198,7 +327,7 @@ export function jwtBearerBaseUrl(env = process.env) {
198
327
  * Handle the jwt-bearer grant type at the token endpoint.
199
328
  * Called from OAuthToken when grant_type is urn:ietf:params:oauth:grant-type:jwt-bearer.
200
329
  */
201
- export async function handleJwtBearerGrant(data) {
330
+ export async function handleJwtBearerGrant(data, ctx) {
202
331
  const assertion = data?.assertion;
203
332
  if (!assertion) {
204
333
  return new Response(JSON.stringify({
@@ -210,7 +339,13 @@ export async function handleJwtBearerGrant(data) {
210
339
  try {
211
340
  const { payload, idpConfig } = await validateIdJag(assertion, baseUrl);
212
341
  // Resolve or create principal
213
- 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.
214
349
  // Determine scopes — intersection of ID-JAG scopes and IdP allowed scopes
215
350
  const requestedScopes = (payload.scope ?? "memory:read").split(" ");
216
351
  const allowedScopes = idpConfig.allowedScopes?.length
@@ -261,6 +396,18 @@ export async function handleJwtBearerGrant(data) {
261
396
  };
262
397
  }
263
398
  catch (err) {
399
+ if (err instanceof ReplayStoreUnavailable) {
400
+ return new Response(JSON.stringify({
401
+ error: "temporarily_unavailable",
402
+ error_description: "replay_store_unavailable",
403
+ }), { status: 503, headers: { "content-type": "application/json" } });
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
+ }
264
411
  return new Response(JSON.stringify({
265
412
  error: "invalid_grant",
266
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
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * agent-status-guard.ts — the `Agent.status` write rule for the Agent resource.
3
+ *
4
+ * `status` is the principal's LIFECYCLE state: any present value other than
5
+ * "active" means deactivated, and a missing or undefined `status` is treated as
6
+ * active (resources/agent-auth.ts's isPrincipalDeactivated). So a principal that
7
+ * may write its own `status` can deactivate itself. Liveness belongs on the
8
+ * Presence beacon, not on this column.
9
+ *
10
+ * resources/Agent.ts's PUT and PATCH admit a trusted internal call and an
11
+ * administrator, and refuse anonymous and any verdict kind the auth resolver
12
+ * does not define. A non-admin agent's PUT or PATCH whose body carries the
13
+ * `status` key is refused whole, on any row including its own, so the other
14
+ * fields in that request are not written either; without `status`, it goes on
15
+ * to Agent.ts's other per-record rules. A non-admin agent's POST (create) is
16
+ * refused earlier, at allowCreate(). (A federation peer's record is merged
17
+ * through the raw table, not this resource; resources/Federation.ts skips an
18
+ * inbound Agent record whose `status` differs from an existing local
19
+ * principal's stored value.)
20
+ *
21
+ * Deliberately dependency-free (no `harper`, no resource) so resources/Agent.ts
22
+ * and the unit lane decide this from one place.
23
+ */
24
+ /** The lifecycle field this module guards. */
25
+ export const AGENT_STATUS_FIELD = "status";
26
+ /**
27
+ * The feature's lifecycle rule applied to a value: a principal's effective
28
+ * `status` is its stored value, or "active" when it is missing or undefined
29
+ * (resources/agent-auth.ts's isPrincipalDeactivated applies the same rule to a
30
+ * principal). Federation's status comparison uses it on both sides
31
+ * (resources/federation-classify.ts).
32
+ */
33
+ export function effectiveAgentStatus(status) {
34
+ return status === undefined ? "active" : status;
35
+ }
36
+ /** The refusal text: names the field, the internal exception, and Presence. */
37
+ export const AGENT_STATUS_ADMIN_ONLY_ERROR = "forbidden: status is administrator-only (a trusted internal call is excepted); report liveness through Presence";
38
+ /** True iff a write body carries the `status` field. */
39
+ export function writeIncludesStatus(content) {
40
+ return content != null && typeof content === "object" && Object.hasOwn(content, AGENT_STATUS_FIELD);
41
+ }
42
+ export function admitPrincipalWrite(auth) {
43
+ if (auth == null || typeof auth !== "object")
44
+ return "deny";
45
+ if (auth.kind === "internal")
46
+ return "internal";
47
+ if (auth.kind === "agent")
48
+ return auth.isAdmin === true ? "admin" : "non-admin";
49
+ return "deny";
50
+ }
51
+ /**
52
+ * The 403 for a write whose body includes `status` from a caller who is not an
53
+ * administrator, or null when the caller is an administrator or the body has no
54
+ * `status`. resources/Agent.ts admits a trusted internal call without calling
55
+ * this helper.
56
+ */
57
+ export function statusWriteRefusal(content, callerIsAdmin) {
58
+ if (callerIsAdmin || !writeIncludesStatus(content))
59
+ return null;
60
+ return new Response(JSON.stringify({ error: AGENT_STATUS_ADMIN_ONLY_ERROR }), {
61
+ status: 403, headers: { "content-type": "application/json" },
62
+ });
63
+ }