@sentropic/cluster-mesh 0.25.0 → 0.27.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 (555) hide show
  1. package/dist/comments/storage-schema.d.ts +1 -1
  2. package/dist/comments/transport-contracts.d.ts +1 -1
  3. package/dist/compile/contract/diagnostics.d.ts +9 -0
  4. package/dist/compile/contract/diagnostics.d.ts.map +1 -0
  5. package/dist/compile/contract/diagnostics.js +82 -0
  6. package/dist/compile/contract/diagnostics.js.map +1 -0
  7. package/dist/compile/contract/encoding.d.ts +12 -0
  8. package/dist/compile/contract/encoding.d.ts.map +1 -0
  9. package/dist/compile/contract/encoding.js +95 -0
  10. package/dist/compile/contract/encoding.js.map +1 -0
  11. package/dist/compile/contract/index.d.ts +9 -0
  12. package/dist/compile/contract/index.d.ts.map +1 -0
  13. package/dist/compile/contract/index.js +9 -0
  14. package/dist/compile/contract/index.js.map +1 -0
  15. package/dist/compile/contract/json.d.ts +3 -0
  16. package/dist/compile/contract/json.d.ts.map +1 -0
  17. package/dist/compile/contract/json.js +75 -0
  18. package/dist/compile/contract/json.js.map +1 -0
  19. package/dist/compile/contract/output.d.ts +5 -0
  20. package/dist/compile/contract/output.d.ts.map +1 -0
  21. package/dist/compile/contract/output.js +57 -0
  22. package/dist/compile/contract/output.js.map +1 -0
  23. package/dist/compile/contract/recipe.d.ts +5 -0
  24. package/dist/compile/contract/recipe.d.ts.map +1 -0
  25. package/dist/compile/contract/recipe.js +86 -0
  26. package/dist/compile/contract/recipe.js.map +1 -0
  27. package/dist/compile/contract/schema.d.ts +26 -0
  28. package/dist/compile/contract/schema.d.ts.map +1 -0
  29. package/dist/compile/contract/schema.js +92 -0
  30. package/dist/compile/contract/schema.js.map +1 -0
  31. package/dist/compile/contract/types.d.ts +166 -0
  32. package/dist/compile/contract/types.d.ts.map +1 -0
  33. package/dist/compile/contract/types.js +21 -0
  34. package/dist/compile/contract/types.js.map +1 -0
  35. package/dist/compile/contract/vectors.d.ts +38 -0
  36. package/dist/compile/contract/vectors.d.ts.map +1 -0
  37. package/dist/compile/contract/vectors.js +29 -0
  38. package/dist/compile/contract/vectors.js.map +1 -0
  39. package/dist/forge/contracts.d.ts +60 -0
  40. package/dist/forge/contracts.d.ts.map +1 -0
  41. package/dist/forge/contracts.js +19 -0
  42. package/dist/forge/contracts.js.map +1 -0
  43. package/dist/forge/custody.d.ts +7 -0
  44. package/dist/forge/custody.d.ts.map +1 -0
  45. package/dist/forge/custody.js +76 -0
  46. package/dist/forge/custody.js.map +1 -0
  47. package/dist/forge/enrollment.d.ts +151 -0
  48. package/dist/forge/enrollment.d.ts.map +1 -0
  49. package/dist/forge/enrollment.js +98 -0
  50. package/dist/forge/enrollment.js.map +1 -0
  51. package/dist/forge/github-api.d.ts +6 -0
  52. package/dist/forge/github-api.d.ts.map +1 -0
  53. package/dist/forge/github-api.js +131 -0
  54. package/dist/forge/github-api.js.map +1 -0
  55. package/dist/forge/hono.d.ts +14 -0
  56. package/dist/forge/hono.d.ts.map +1 -0
  57. package/dist/forge/hono.js +141 -0
  58. package/dist/forge/hono.js.map +1 -0
  59. package/dist/forge/lifecycle.d.ts +108 -0
  60. package/dist/forge/lifecycle.d.ts.map +1 -0
  61. package/dist/forge/lifecycle.js +160 -0
  62. package/dist/forge/lifecycle.js.map +1 -0
  63. package/dist/forge/records.d.ts +70 -0
  64. package/dist/forge/records.d.ts.map +1 -0
  65. package/dist/forge/records.js +2 -0
  66. package/dist/forge/records.js.map +1 -0
  67. package/dist/forge/rotation.d.ts +46 -0
  68. package/dist/forge/rotation.d.ts.map +1 -0
  69. package/dist/forge/rotation.js +62 -0
  70. package/dist/forge/rotation.js.map +1 -0
  71. package/dist/identity/auth-abort.d.ts +9 -0
  72. package/dist/identity/auth-abort.d.ts.map +1 -0
  73. package/dist/identity/auth-abort.js +59 -0
  74. package/dist/identity/auth-abort.js.map +1 -0
  75. package/dist/identity/auth-binding.d.ts +3 -0
  76. package/dist/identity/auth-binding.d.ts.map +1 -0
  77. package/dist/identity/auth-binding.js +87 -0
  78. package/dist/identity/auth-binding.js.map +1 -0
  79. package/dist/identity/auth-boundary.d.ts +11 -0
  80. package/dist/identity/auth-boundary.d.ts.map +1 -0
  81. package/dist/identity/auth-boundary.js +73 -0
  82. package/dist/identity/auth-boundary.js.map +1 -0
  83. package/dist/identity/auth-completion.d.ts +9 -0
  84. package/dist/identity/auth-completion.d.ts.map +1 -0
  85. package/dist/identity/auth-completion.js +24 -0
  86. package/dist/identity/auth-completion.js.map +1 -0
  87. package/dist/identity/auth-credentials.d.ts +5 -0
  88. package/dist/identity/auth-credentials.d.ts.map +1 -0
  89. package/dist/identity/auth-credentials.js +82 -0
  90. package/dist/identity/auth-credentials.js.map +1 -0
  91. package/dist/identity/auth-email.d.ts +8 -0
  92. package/dist/identity/auth-email.d.ts.map +1 -0
  93. package/dist/identity/auth-email.js +104 -0
  94. package/dist/identity/auth-email.js.map +1 -0
  95. package/dist/identity/auth-hono.d.ts +5 -0
  96. package/dist/identity/auth-hono.d.ts.map +1 -0
  97. package/dist/identity/auth-hono.js +10 -0
  98. package/dist/identity/auth-hono.js.map +1 -0
  99. package/dist/identity/auth-proofs.d.ts +11 -0
  100. package/dist/identity/auth-proofs.d.ts.map +1 -0
  101. package/dist/identity/auth-proofs.js +107 -0
  102. package/dist/identity/auth-proofs.js.map +1 -0
  103. package/dist/identity/auth-service-tenant.d.ts +4 -0
  104. package/dist/identity/auth-service-tenant.d.ts.map +1 -0
  105. package/dist/identity/auth-service-tenant.js +54 -0
  106. package/dist/identity/auth-service-tenant.js.map +1 -0
  107. package/dist/identity/auth-sessions.d.ts +8 -0
  108. package/dist/identity/auth-sessions.d.ts.map +1 -0
  109. package/dist/identity/auth-sessions.js +141 -0
  110. package/dist/identity/auth-sessions.js.map +1 -0
  111. package/dist/identity/auth-social.d.ts +4 -0
  112. package/dist/identity/auth-social.d.ts.map +1 -0
  113. package/dist/identity/auth-social.js +82 -0
  114. package/dist/identity/auth-social.js.map +1 -0
  115. package/dist/identity/auth-users.d.ts +9 -0
  116. package/dist/identity/auth-users.d.ts.map +1 -0
  117. package/dist/identity/auth-users.js +116 -0
  118. package/dist/identity/auth-users.js.map +1 -0
  119. package/dist/identity/auth-webauthn.d.ts +22 -0
  120. package/dist/identity/auth-webauthn.d.ts.map +1 -0
  121. package/dist/identity/auth-webauthn.js +108 -0
  122. package/dist/identity/auth-webauthn.js.map +1 -0
  123. package/dist/identity/cascade.d.ts +12 -0
  124. package/dist/identity/cascade.d.ts.map +1 -0
  125. package/dist/identity/cascade.js +19 -0
  126. package/dist/identity/cascade.js.map +1 -0
  127. package/dist/identity/connector-custody.d.ts +85 -0
  128. package/dist/identity/connector-custody.d.ts.map +1 -0
  129. package/dist/identity/connector-custody.js +288 -0
  130. package/dist/identity/connector-custody.js.map +1 -0
  131. package/dist/identity/conversation.d.ts +50 -0
  132. package/dist/identity/conversation.d.ts.map +1 -0
  133. package/dist/identity/conversation.js +102 -0
  134. package/dist/identity/conversation.js.map +1 -0
  135. package/dist/identity/custody-crypto.d.ts +37 -0
  136. package/dist/identity/custody-crypto.d.ts.map +1 -0
  137. package/dist/identity/custody-crypto.js +173 -0
  138. package/dist/identity/custody-crypto.js.map +1 -0
  139. package/dist/identity/decision.d.ts +28 -0
  140. package/dist/identity/decision.d.ts.map +1 -0
  141. package/dist/identity/decision.js +97 -0
  142. package/dist/identity/decision.js.map +1 -0
  143. package/dist/identity/index.d.ts +9 -0
  144. package/dist/identity/index.d.ts.map +1 -0
  145. package/dist/identity/index.js +13 -0
  146. package/dist/identity/index.js.map +1 -0
  147. package/dist/identity/ledger.d.ts +120 -0
  148. package/dist/identity/ledger.d.ts.map +1 -0
  149. package/dist/identity/ledger.js +226 -0
  150. package/dist/identity/ledger.js.map +1 -0
  151. package/dist/identity/postgres.d.ts +13 -0
  152. package/dist/identity/postgres.d.ts.map +1 -0
  153. package/dist/identity/postgres.js +207 -0
  154. package/dist/identity/postgres.js.map +1 -0
  155. package/dist/identity/sqlite.d.ts +14 -0
  156. package/dist/identity/sqlite.d.ts.map +1 -0
  157. package/dist/identity/sqlite.js +193 -0
  158. package/dist/identity/sqlite.js.map +1 -0
  159. package/dist/identity-contracts/accounts.d.ts.map +1 -1
  160. package/dist/identity-contracts/accounts.js +4 -3
  161. package/dist/identity-contracts/accounts.js.map +1 -1
  162. package/dist/identity-contracts/boundary-resolution.d.ts +31 -0
  163. package/dist/identity-contracts/boundary-resolution.d.ts.map +1 -0
  164. package/dist/identity-contracts/boundary-resolution.js +56 -0
  165. package/dist/identity-contracts/boundary-resolution.js.map +1 -0
  166. package/dist/identity-contracts/composition-descriptors.d.ts +17 -0
  167. package/dist/identity-contracts/composition-descriptors.d.ts.map +1 -0
  168. package/dist/identity-contracts/composition-descriptors.js +77 -0
  169. package/dist/identity-contracts/composition-descriptors.js.map +1 -0
  170. package/dist/identity-contracts/custody-auth.d.ts +122 -0
  171. package/dist/identity-contracts/custody-auth.d.ts.map +1 -0
  172. package/dist/identity-contracts/custody-auth.js +2 -0
  173. package/dist/identity-contracts/custody-auth.js.map +1 -0
  174. package/dist/identity-contracts/custody-descriptors.d.ts +18 -0
  175. package/dist/identity-contracts/custody-descriptors.d.ts.map +1 -0
  176. package/dist/identity-contracts/custody-descriptors.js +83 -0
  177. package/dist/identity-contracts/custody-descriptors.js.map +1 -0
  178. package/dist/identity-contracts/custody-errors.d.ts +21 -0
  179. package/dist/identity-contracts/custody-errors.d.ts.map +1 -0
  180. package/dist/identity-contracts/custody-errors.js +80 -0
  181. package/dist/identity-contracts/custody-errors.js.map +1 -0
  182. package/dist/identity-contracts/custody-operations.d.ts +79 -0
  183. package/dist/identity-contracts/custody-operations.d.ts.map +1 -0
  184. package/dist/identity-contracts/custody-operations.js +2 -0
  185. package/dist/identity-contracts/custody-operations.js.map +1 -0
  186. package/dist/identity-contracts/custody.d.ts +587 -0
  187. package/dist/identity-contracts/custody.d.ts.map +1 -0
  188. package/dist/identity-contracts/custody.js +7 -0
  189. package/dist/identity-contracts/custody.js.map +1 -0
  190. package/dist/identity-contracts/doubles.d.ts +11 -2
  191. package/dist/identity-contracts/doubles.d.ts.map +1 -1
  192. package/dist/identity-contracts/doubles.js +20 -0
  193. package/dist/identity-contracts/doubles.js.map +1 -1
  194. package/dist/identity-contracts/index.d.ts +10 -0
  195. package/dist/identity-contracts/index.d.ts.map +1 -1
  196. package/dist/identity-contracts/index.js +10 -0
  197. package/dist/identity-contracts/index.js.map +1 -1
  198. package/dist/identity-contracts/oauth-reads.d.ts +42 -0
  199. package/dist/identity-contracts/oauth-reads.d.ts.map +1 -0
  200. package/dist/identity-contracts/oauth-reads.js +38 -0
  201. package/dist/identity-contracts/oauth-reads.js.map +1 -0
  202. package/dist/identity-contracts/replica-sync.d.ts +89 -0
  203. package/dist/identity-contracts/replica-sync.d.ts.map +1 -0
  204. package/dist/identity-contracts/replica-sync.js +7 -0
  205. package/dist/identity-contracts/replica-sync.js.map +1 -0
  206. package/dist/identity-contracts/service-tenancy.d.ts +43 -0
  207. package/dist/identity-contracts/service-tenancy.d.ts.map +1 -0
  208. package/dist/identity-contracts/service-tenancy.js +75 -0
  209. package/dist/identity-contracts/service-tenancy.js.map +1 -0
  210. package/dist/identity-contracts/workspace-deletion.d.ts +56 -0
  211. package/dist/identity-contracts/workspace-deletion.d.ts.map +1 -0
  212. package/dist/identity-contracts/workspace-deletion.js +7 -0
  213. package/dist/identity-contracts/workspace-deletion.js.map +1 -0
  214. package/dist/identity-stores/index.d.ts +4 -0
  215. package/dist/identity-stores/index.d.ts.map +1 -0
  216. package/dist/identity-stores/index.js +7 -0
  217. package/dist/identity-stores/index.js.map +1 -0
  218. package/dist/identity-stores/tenancy-postgres.d.ts +23 -0
  219. package/dist/identity-stores/tenancy-postgres.d.ts.map +1 -0
  220. package/dist/identity-stores/tenancy-postgres.js +294 -0
  221. package/dist/identity-stores/tenancy-postgres.js.map +1 -0
  222. package/dist/identity-stores/tenancy-schema.d.ts +11 -0
  223. package/dist/identity-stores/tenancy-schema.d.ts.map +1 -0
  224. package/dist/identity-stores/tenancy-schema.js +74 -0
  225. package/dist/identity-stores/tenancy-schema.js.map +1 -0
  226. package/dist/identity-stores/tenancy-sqlite.d.ts +24 -0
  227. package/dist/identity-stores/tenancy-sqlite.d.ts.map +1 -0
  228. package/dist/identity-stores/tenancy-sqlite.js +288 -0
  229. package/dist/identity-stores/tenancy-sqlite.js.map +1 -0
  230. package/dist/index.d.ts +17 -0
  231. package/dist/index.d.ts.map +1 -1
  232. package/dist/index.js +16 -0
  233. package/dist/index.js.map +1 -1
  234. package/dist/loaders/notifications/index.d.ts +5 -0
  235. package/dist/loaders/notifications/index.d.ts.map +1 -0
  236. package/dist/loaders/notifications/index.js +6 -0
  237. package/dist/loaders/notifications/index.js.map +1 -0
  238. package/dist/mcp/stateful-preflight.d.ts +1 -1
  239. package/dist/messaging/email-port.d.ts +49 -0
  240. package/dist/messaging/email-port.d.ts.map +1 -0
  241. package/dist/messaging/email-port.js +92 -0
  242. package/dist/messaging/email-port.js.map +1 -0
  243. package/dist/messaging/index.d.ts +1 -0
  244. package/dist/messaging/index.d.ts.map +1 -1
  245. package/dist/messaging/index.js +1 -0
  246. package/dist/messaging/index.js.map +1 -1
  247. package/dist/modules/catalog.d.ts +5 -4
  248. package/dist/modules/catalog.d.ts.map +1 -1
  249. package/dist/modules/catalog.js +10 -5
  250. package/dist/modules/catalog.js.map +1 -1
  251. package/dist/modules/contracts.d.ts +1 -1
  252. package/dist/modules/contracts.d.ts.map +1 -1
  253. package/dist/modules/contracts.js +1 -0
  254. package/dist/modules/contracts.js.map +1 -1
  255. package/dist/notifications/incident-policy.d.ts +6 -0
  256. package/dist/notifications/incident-policy.d.ts.map +1 -0
  257. package/dist/notifications/incident-policy.js +119 -0
  258. package/dist/notifications/incident-policy.js.map +1 -0
  259. package/dist/notifications/incident-schedule.d.ts +14 -0
  260. package/dist/notifications/incident-schedule.d.ts.map +1 -0
  261. package/dist/notifications/incident-schedule.js +36 -0
  262. package/dist/notifications/incident-schedule.js.map +1 -0
  263. package/dist/notifications/incident-state.d.ts +72 -0
  264. package/dist/notifications/incident-state.d.ts.map +1 -0
  265. package/dist/notifications/incident-state.js +72 -0
  266. package/dist/notifications/incident-state.js.map +1 -0
  267. package/dist/notifications/index.d.ts +9 -0
  268. package/dist/notifications/index.d.ts.map +1 -0
  269. package/dist/notifications/index.js +9 -0
  270. package/dist/notifications/index.js.map +1 -0
  271. package/dist/notifications/ops-job-failure-contract.d.ts +19 -0
  272. package/dist/notifications/ops-job-failure-contract.d.ts.map +1 -0
  273. package/dist/notifications/ops-job-failure-contract.js +183 -0
  274. package/dist/notifications/ops-job-failure-contract.js.map +1 -0
  275. package/dist/notifications/ops-job-failure-types.d.ts +81 -0
  276. package/dist/notifications/ops-job-failure-types.d.ts.map +1 -0
  277. package/dist/notifications/ops-job-failure-types.js +73 -0
  278. package/dist/notifications/ops-job-failure-types.js.map +1 -0
  279. package/dist/notifications/recipients-http.d.ts +66 -0
  280. package/dist/notifications/recipients-http.d.ts.map +1 -0
  281. package/dist/notifications/recipients-http.js +148 -0
  282. package/dist/notifications/recipients-http.js.map +1 -0
  283. package/dist/notifications/recipients.d.ts +50 -0
  284. package/dist/notifications/recipients.d.ts.map +1 -0
  285. package/dist/notifications/recipients.js +59 -0
  286. package/dist/notifications/recipients.js.map +1 -0
  287. package/dist/prompts/registry.d.ts +55 -0
  288. package/dist/prompts/registry.d.ts.map +1 -0
  289. package/dist/prompts/registry.js +76 -0
  290. package/dist/prompts/registry.js.map +1 -0
  291. package/dist/remote/assembly-contract.d.ts +96 -0
  292. package/dist/remote/assembly-contract.d.ts.map +1 -0
  293. package/dist/remote/assembly-contract.js +150 -0
  294. package/dist/remote/assembly-contract.js.map +1 -0
  295. package/dist/remote/contract-receipt.d.ts +36 -0
  296. package/dist/remote/contract-receipt.d.ts.map +1 -0
  297. package/dist/remote/contract-receipt.js +109 -0
  298. package/dist/remote/contract-receipt.js.map +1 -0
  299. package/dist/remote/credit-baseline.d.ts +60 -0
  300. package/dist/remote/credit-baseline.d.ts.map +1 -0
  301. package/dist/remote/credit-baseline.js +117 -0
  302. package/dist/remote/credit-baseline.js.map +1 -0
  303. package/dist/runtime/heavy-phase-queue.d.ts +101 -0
  304. package/dist/runtime/heavy-phase-queue.d.ts.map +1 -0
  305. package/dist/runtime/heavy-phase-queue.js +129 -0
  306. package/dist/runtime/heavy-phase-queue.js.map +1 -0
  307. package/dist/sessions/content-policy.d.ts +55 -0
  308. package/dist/sessions/content-policy.d.ts.map +1 -0
  309. package/dist/sessions/content-policy.js +133 -0
  310. package/dist/sessions/content-policy.js.map +1 -0
  311. package/dist/sessions/registry-admin.d.ts +19 -0
  312. package/dist/sessions/registry-admin.d.ts.map +1 -0
  313. package/dist/sessions/registry-admin.js +42 -0
  314. package/dist/sessions/registry-admin.js.map +1 -0
  315. package/dist/sessions/registry-freshness.d.ts +8 -0
  316. package/dist/sessions/registry-freshness.d.ts.map +1 -0
  317. package/dist/sessions/registry-freshness.js +108 -0
  318. package/dist/sessions/registry-freshness.js.map +1 -0
  319. package/dist/sessions/registry-ingest.d.ts +5 -0
  320. package/dist/sessions/registry-ingest.d.ts.map +1 -0
  321. package/dist/sessions/registry-ingest.js +113 -0
  322. package/dist/sessions/registry-ingest.js.map +1 -0
  323. package/dist/sessions/registry-publish.d.ts +18 -0
  324. package/dist/sessions/registry-publish.d.ts.map +1 -0
  325. package/dist/sessions/registry-publish.js +134 -0
  326. package/dist/sessions/registry-publish.js.map +1 -0
  327. package/dist/sessions/registry-store.d.ts +51 -0
  328. package/dist/sessions/registry-store.d.ts.map +1 -0
  329. package/dist/sessions/registry-store.js +134 -0
  330. package/dist/sessions/registry-store.js.map +1 -0
  331. package/dist/sessions/registry-types.d.ts +180 -0
  332. package/dist/sessions/registry-types.d.ts.map +1 -0
  333. package/dist/sessions/registry-types.js +32 -0
  334. package/dist/sessions/registry-types.js.map +1 -0
  335. package/dist/sessions/registry.d.ts +45 -0
  336. package/dist/sessions/registry.d.ts.map +1 -0
  337. package/dist/sessions/registry.js +74 -0
  338. package/dist/sessions/registry.js.map +1 -0
  339. package/dist/sessions/relay-bind.d.ts +38 -0
  340. package/dist/sessions/relay-bind.d.ts.map +1 -0
  341. package/dist/sessions/relay-bind.js +74 -0
  342. package/dist/sessions/relay-bind.js.map +1 -0
  343. package/dist/sessions/relay-brand.d.ts +2 -0
  344. package/dist/sessions/relay-brand.d.ts.map +1 -0
  345. package/dist/sessions/relay-brand.js +7 -0
  346. package/dist/sessions/relay-brand.js.map +1 -0
  347. package/dist/sessions/relay-capsule.d.ts +50 -0
  348. package/dist/sessions/relay-capsule.d.ts.map +1 -0
  349. package/dist/sessions/relay-capsule.js +72 -0
  350. package/dist/sessions/relay-capsule.js.map +1 -0
  351. package/dist/sessions/relay-chain-failure.d.ts +25 -0
  352. package/dist/sessions/relay-chain-failure.d.ts.map +1 -0
  353. package/dist/sessions/relay-chain-failure.js +23 -0
  354. package/dist/sessions/relay-chain-failure.js.map +1 -0
  355. package/dist/sessions/relay-chain.d.ts +74 -0
  356. package/dist/sessions/relay-chain.d.ts.map +1 -0
  357. package/dist/sessions/relay-chain.js +71 -0
  358. package/dist/sessions/relay-chain.js.map +1 -0
  359. package/dist/sessions/relay-composition.d.ts +8 -0
  360. package/dist/sessions/relay-composition.d.ts.map +1 -0
  361. package/dist/sessions/relay-composition.js +65 -0
  362. package/dist/sessions/relay-composition.js.map +1 -0
  363. package/dist/sessions/relay-credit.d.ts +40 -0
  364. package/dist/sessions/relay-credit.d.ts.map +1 -0
  365. package/dist/sessions/relay-credit.js +68 -0
  366. package/dist/sessions/relay-credit.js.map +1 -0
  367. package/dist/sessions/relay-engine.d.ts +19 -0
  368. package/dist/sessions/relay-engine.d.ts.map +1 -0
  369. package/dist/sessions/relay-engine.js +34 -0
  370. package/dist/sessions/relay-engine.js.map +1 -0
  371. package/dist/sessions/relay-frames.d.ts +28 -0
  372. package/dist/sessions/relay-frames.d.ts.map +1 -0
  373. package/dist/sessions/relay-frames.js +72 -0
  374. package/dist/sessions/relay-frames.js.map +1 -0
  375. package/dist/sessions/relay-lane-client.d.ts +7 -0
  376. package/dist/sessions/relay-lane-client.d.ts.map +1 -0
  377. package/dist/sessions/relay-lane-client.js +137 -0
  378. package/dist/sessions/relay-lane-client.js.map +1 -0
  379. package/dist/sessions/relay-lane-lease.d.ts +20 -0
  380. package/dist/sessions/relay-lane-lease.d.ts.map +1 -0
  381. package/dist/sessions/relay-lane-lease.js +74 -0
  382. package/dist/sessions/relay-lane-lease.js.map +1 -0
  383. package/dist/sessions/relay-lane-record.d.ts +28 -0
  384. package/dist/sessions/relay-lane-record.d.ts.map +1 -0
  385. package/dist/sessions/relay-lane-record.js +28 -0
  386. package/dist/sessions/relay-lane-record.js.map +1 -0
  387. package/dist/sessions/relay-lane-stream.d.ts +13 -0
  388. package/dist/sessions/relay-lane-stream.d.ts.map +1 -0
  389. package/dist/sessions/relay-lane-stream.js +148 -0
  390. package/dist/sessions/relay-lane-stream.js.map +1 -0
  391. package/dist/sessions/relay-routes.d.ts +368 -0
  392. package/dist/sessions/relay-routes.d.ts.map +1 -0
  393. package/dist/sessions/relay-routes.js +46 -0
  394. package/dist/sessions/relay-routes.js.map +1 -0
  395. package/dist/sessions/relay-skeleton.d.ts +4 -0
  396. package/dist/sessions/relay-skeleton.d.ts.map +1 -0
  397. package/dist/sessions/relay-skeleton.js +85 -0
  398. package/dist/sessions/relay-skeleton.js.map +1 -0
  399. package/dist/sessions/relay-types.d.ts +107 -0
  400. package/dist/sessions/relay-types.d.ts.map +1 -0
  401. package/dist/sessions/relay-types.js +2 -0
  402. package/dist/sessions/relay-types.js.map +1 -0
  403. package/dist/sessions/relay-validate.d.ts +8 -0
  404. package/dist/sessions/relay-validate.d.ts.map +1 -0
  405. package/dist/sessions/relay-validate.js +169 -0
  406. package/dist/sessions/relay-validate.js.map +1 -0
  407. package/dist/sessions/relay-wire.d.ts +8 -0
  408. package/dist/sessions/relay-wire.d.ts.map +1 -0
  409. package/dist/sessions/relay-wire.js +37 -0
  410. package/dist/sessions/relay-wire.js.map +1 -0
  411. package/dist/sessions/relay-wiring.d.ts +26 -0
  412. package/dist/sessions/relay-wiring.d.ts.map +1 -0
  413. package/dist/sessions/relay-wiring.js +13 -0
  414. package/dist/sessions/relay-wiring.js.map +1 -0
  415. package/dist/sessions/relay.d.ts +11 -0
  416. package/dist/sessions/relay.d.ts.map +1 -0
  417. package/dist/sessions/relay.js +71 -0
  418. package/dist/sessions/relay.js.map +1 -0
  419. package/dist/storage/artifact-blob.d.ts +50 -0
  420. package/dist/storage/artifact-blob.d.ts.map +1 -0
  421. package/dist/storage/artifact-blob.js +2 -0
  422. package/dist/storage/artifact-blob.js.map +1 -0
  423. package/dist/storage/descriptor.d.ts +1 -1
  424. package/dist/storage/errors.d.ts +1 -1
  425. package/dist/storage/identity/atomic-deletion.d.ts +4 -0
  426. package/dist/storage/identity/atomic-deletion.d.ts.map +1 -0
  427. package/dist/storage/identity/atomic-deletion.js +235 -0
  428. package/dist/storage/identity/atomic-deletion.js.map +1 -0
  429. package/dist/storage/identity/custody-composition.d.ts +9 -0
  430. package/dist/storage/identity/custody-composition.d.ts.map +1 -0
  431. package/dist/storage/identity/custody-composition.js +31 -0
  432. package/dist/storage/identity/custody-composition.js.map +1 -0
  433. package/dist/storage/identity/custody-delivery-record.d.ts +4 -0
  434. package/dist/storage/identity/custody-delivery-record.d.ts.map +1 -0
  435. package/dist/storage/identity/custody-delivery-record.js +11 -0
  436. package/dist/storage/identity/custody-delivery-record.js.map +1 -0
  437. package/dist/storage/identity/custody-host.d.ts +16 -0
  438. package/dist/storage/identity/custody-host.d.ts.map +1 -0
  439. package/dist/storage/identity/custody-host.js +5 -0
  440. package/dist/storage/identity/custody-host.js.map +1 -0
  441. package/dist/storage/identity/custody-import-deliveries.d.ts +6 -0
  442. package/dist/storage/identity/custody-import-deliveries.d.ts.map +1 -0
  443. package/dist/storage/identity/custody-import-deliveries.js +46 -0
  444. package/dist/storage/identity/custody-import-deliveries.js.map +1 -0
  445. package/dist/storage/identity/custody-import.d.ts +4 -0
  446. package/dist/storage/identity/custody-import.d.ts.map +1 -0
  447. package/dist/storage/identity/custody-import.js +364 -0
  448. package/dist/storage/identity/custody-import.js.map +1 -0
  449. package/dist/storage/identity/custody-journal-postgres.d.ts +125 -0
  450. package/dist/storage/identity/custody-journal-postgres.d.ts.map +1 -0
  451. package/dist/storage/identity/custody-journal-postgres.js +428 -0
  452. package/dist/storage/identity/custody-journal-postgres.js.map +1 -0
  453. package/dist/storage/identity/custody-journal-sqlite.d.ts +121 -0
  454. package/dist/storage/identity/custody-journal-sqlite.d.ts.map +1 -0
  455. package/dist/storage/identity/custody-journal-sqlite.js +345 -0
  456. package/dist/storage/identity/custody-journal-sqlite.js.map +1 -0
  457. package/dist/storage/identity/custody-lifecycle.d.ts +4 -0
  458. package/dist/storage/identity/custody-lifecycle.d.ts.map +1 -0
  459. package/dist/storage/identity/custody-lifecycle.js +42 -0
  460. package/dist/storage/identity/custody-lifecycle.js.map +1 -0
  461. package/dist/storage/identity/custody-postgres.d.ts +96 -0
  462. package/dist/storage/identity/custody-postgres.d.ts.map +1 -0
  463. package/dist/storage/identity/custody-postgres.js +726 -0
  464. package/dist/storage/identity/custody-postgres.js.map +1 -0
  465. package/dist/storage/identity/custody-records.d.ts +17 -0
  466. package/dist/storage/identity/custody-records.d.ts.map +1 -0
  467. package/dist/storage/identity/custody-records.js +260 -0
  468. package/dist/storage/identity/custody-records.js.map +1 -0
  469. package/dist/storage/identity/custody-shared.d.ts +28 -0
  470. package/dist/storage/identity/custody-shared.d.ts.map +1 -0
  471. package/dist/storage/identity/custody-shared.js +24 -0
  472. package/dist/storage/identity/custody-shared.js.map +1 -0
  473. package/dist/storage/identity/custody-sqlite.d.ts +93 -0
  474. package/dist/storage/identity/custody-sqlite.d.ts.map +1 -0
  475. package/dist/storage/identity/custody-sqlite.js +568 -0
  476. package/dist/storage/identity/custody-sqlite.js.map +1 -0
  477. package/dist/storage/identity/custody-tombstone-record.d.ts +3 -0
  478. package/dist/storage/identity/custody-tombstone-record.d.ts.map +1 -0
  479. package/dist/storage/identity/custody-tombstone-record.js +8 -0
  480. package/dist/storage/identity/custody-tombstone-record.js.map +1 -0
  481. package/dist/storage/identity/custody-transaction-guards.d.ts +16 -0
  482. package/dist/storage/identity/custody-transaction-guards.d.ts.map +1 -0
  483. package/dist/storage/identity/custody-transaction-guards.js +64 -0
  484. package/dist/storage/identity/custody-transaction-guards.js.map +1 -0
  485. package/dist/storage/identity/custody-transaction-ports.d.ts +9 -0
  486. package/dist/storage/identity/custody-transaction-ports.d.ts.map +1 -0
  487. package/dist/storage/identity/custody-transaction-ports.js +106 -0
  488. package/dist/storage/identity/custody-transaction-ports.js.map +1 -0
  489. package/dist/storage/identity/deletion-planes.d.ts +10 -0
  490. package/dist/storage/identity/deletion-planes.d.ts.map +1 -0
  491. package/dist/storage/identity/deletion-planes.js +54 -0
  492. package/dist/storage/identity/deletion-planes.js.map +1 -0
  493. package/dist/storage/identity/index.d.ts +18 -0
  494. package/dist/storage/identity/index.d.ts.map +1 -0
  495. package/dist/storage/identity/index.js +22 -0
  496. package/dist/storage/identity/index.js.map +1 -0
  497. package/dist/storage/identity/postgres.d.ts +16 -0
  498. package/dist/storage/identity/postgres.d.ts.map +1 -0
  499. package/dist/storage/identity/postgres.js +345 -0
  500. package/dist/storage/identity/postgres.js.map +1 -0
  501. package/dist/storage/identity/records.d.ts +12 -0
  502. package/dist/storage/identity/records.d.ts.map +1 -0
  503. package/dist/storage/identity/records.js +84 -0
  504. package/dist/storage/identity/records.js.map +1 -0
  505. package/dist/storage/identity/replica-sync.d.ts +4 -0
  506. package/dist/storage/identity/replica-sync.d.ts.map +1 -0
  507. package/dist/storage/identity/replica-sync.js +402 -0
  508. package/dist/storage/identity/replica-sync.js.map +1 -0
  509. package/dist/storage/identity/schema.d.ts +13 -0
  510. package/dist/storage/identity/schema.d.ts.map +1 -0
  511. package/dist/storage/identity/schema.js +418 -0
  512. package/dist/storage/identity/schema.js.map +1 -0
  513. package/dist/storage/identity/sqlite-schema.d.ts +4 -0
  514. package/dist/storage/identity/sqlite-schema.d.ts.map +1 -0
  515. package/dist/storage/identity/sqlite-schema.js +17 -0
  516. package/dist/storage/identity/sqlite-schema.js.map +1 -0
  517. package/dist/storage/identity/sqlite.d.ts +25 -0
  518. package/dist/storage/identity/sqlite.d.ts.map +1 -0
  519. package/dist/storage/identity/sqlite.js +233 -0
  520. package/dist/storage/identity/sqlite.js.map +1 -0
  521. package/dist/storage/identity/stores.d.ts +10 -0
  522. package/dist/storage/identity/stores.d.ts.map +1 -0
  523. package/dist/storage/identity/stores.js +5 -0
  524. package/dist/storage/identity/stores.js.map +1 -0
  525. package/dist/storage/identity/wiring.d.ts +20 -0
  526. package/dist/storage/identity/wiring.d.ts.map +1 -0
  527. package/dist/storage/identity/wiring.js +26 -0
  528. package/dist/storage/identity/wiring.js.map +1 -0
  529. package/dist/storage/identity/workspace-deletion.d.ts +3 -0
  530. package/dist/storage/identity/workspace-deletion.d.ts.map +1 -0
  531. package/dist/storage/identity/workspace-deletion.js +100 -0
  532. package/dist/storage/identity/workspace-deletion.js.map +1 -0
  533. package/dist/storage/index.d.ts +1 -0
  534. package/dist/storage/index.d.ts.map +1 -1
  535. package/dist/storage/postgres/journal.d.ts +1 -1
  536. package/dist/storage/postgres/profiles.d.ts +2 -2
  537. package/dist/storage/postgres/scope.d.ts +1 -1
  538. package/dist/storage/root-facade.d.ts +1 -1
  539. package/dist/storage/root-journal.d.ts +1 -1
  540. package/dist/storage/root-profiles.d.ts +1 -1
  541. package/package.json +56 -4
  542. package/ui/AdminUsersScreen.svelte +197 -0
  543. package/ui/AdminUsersScreen.svelte.d.ts +4 -0
  544. package/ui/LoginScreen.svelte +15 -0
  545. package/ui/LoginScreen.svelte.d.ts +4 -0
  546. package/ui/MembershipDecisionsScreen.svelte +76 -0
  547. package/ui/MembershipDecisionsScreen.svelte.d.ts +4 -0
  548. package/ui/RegistrationScreen.svelte +15 -0
  549. package/ui/RegistrationScreen.svelte.d.ts +4 -0
  550. package/ui/WorkspaceMembersScreen.svelte +86 -0
  551. package/ui/WorkspaceMembersScreen.svelte.d.ts +4 -0
  552. package/ui/auth-flow.ts +44 -0
  553. package/ui/management-ports.ts +36 -0
  554. package/ui/management-transport.ts +29 -0
  555. package/contracts/engram-memory-neutral-contract-v1.d.ts +0 -367
@@ -0,0 +1,726 @@
1
+ // A2.0b custody stores on the PostgreSQL profile. Every method below runs on
2
+ // a caller-supplied PgSession and never begins, commits or migrates on its
3
+ // own: the host unit of work owns the transaction. Standalone per-method
4
+ // wrappers are provided for direct store tests.
5
+ import { IdentityCustodyErrorV1 } from '../../identity-contracts/custody-errors.js';
6
+ import { composeIdentityTransaction } from './custody-composition.js';
7
+ import { identityTransactionGuard, requireIdentityRunOptions, rebindIdentityTransactionHost } from './custody-transaction-guards.js';
8
+ import { subjectLifecycle } from './custody-lifecycle.js';
9
+ import { decodeSession } from './records.js';
10
+ import { InvitationError, ProofVerificationError } from '../../identity-contracts/errors.js';
11
+ import { IDENTITY_TABLES, identitySchemaStatements, identityTable } from './schema.js';
12
+ import { identityCustodySchemaAssetV1, isSocialRaceRetry, } from './custody-shared.js';
13
+ import { PostgresCustodyJournal } from './custody-journal-postgres.js';
14
+ import { decodeAccountProfile, decodeBoundSession, decodeDigestInvitation, decodeEmailTicket, decodeSingleUseProof, decodeSocialLink, decodeWebAuthnCredential, } from './custody-records.js';
15
+ export const CUSTODY_TX_DEADLINE_MS = 5000;
16
+ export const custodyTable = (schema, table) => identityTable('postgres', schema, table);
17
+ const SERIALIZATION_CODES = new Set(['40001', '40P01']);
18
+ const isSerializationFailure = (error) => {
19
+ const fields = (error ?? {});
20
+ return SERIALIZATION_CODES.has(String(fields.code ?? fields.sqlState ?? ''));
21
+ };
22
+ const isUniqueViolation = (error) => {
23
+ const fields = (error ?? {});
24
+ return String(fields.code ?? '') === '23505';
25
+ };
26
+ export const requireWriteOptions = (options) => {
27
+ if (options.mode !== 'write') {
28
+ throw new IdentityCustodyErrorV1('identity_transaction_unbound');
29
+ }
30
+ if (!Number.isInteger(options.deadlineMs) || options.deadlineMs <= 0) {
31
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
32
+ }
33
+ };
34
+ const toBool = (value) => value;
35
+ /** Transaction-scoped custody bundle: all SQL runs on the bound session. */
36
+ export class PostgresCustodyTx {
37
+ schema;
38
+ session;
39
+ subjects;
40
+ profiles;
41
+ credentials;
42
+ singleUseProofs;
43
+ emailTickets;
44
+ invitations;
45
+ sessions;
46
+ social;
47
+ constructor(schema, session) {
48
+ this.schema = schema;
49
+ this.session = session;
50
+ this.subjects = subjectLifecycle({ profile: 'postgres', schema, raw: session, stores: this, journal: new PostgresCustodyJournal(schema, session) });
51
+ this.profiles = {
52
+ find: (userId) => this.one(decodeAccountProfile, `SELECT * FROM ${this.t('identity_account_profiles')} WHERE "user_id" = $1`, [userId]),
53
+ put: async (record) => {
54
+ await session.execute({
55
+ text: `INSERT INTO ${this.t('identity_account_profiles')} ("user_id","email_verified","display_name","approval_due_at","approved_at","approved_by_user_id","disabled_at","disabled_reason","legacy_account_status") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
56
+ ON CONFLICT ("user_id") DO UPDATE SET "email_verified" = EXCLUDED."email_verified", "display_name" = EXCLUDED."display_name", "approval_due_at" = EXCLUDED."approval_due_at", "approved_at" = EXCLUDED."approved_at", "approved_by_user_id" = EXCLUDED."approved_by_user_id", "disabled_at" = EXCLUDED."disabled_at", "disabled_reason" = EXCLUDED."disabled_reason", "legacy_account_status" = EXCLUDED."legacy_account_status"`,
57
+ values: [record.userId, toBool(record.emailVerified), record.displayName, record.approvalDueAt, record.approvedAt, record.approvedByUserId, record.disabledAt, record.disabledReason, record.legacyAccountStatus],
58
+ });
59
+ },
60
+ };
61
+ this.credentials = {
62
+ insert: async (record) => {
63
+ try {
64
+ await session.execute({
65
+ text: `INSERT INTO ${this.t('identity_webauthn_credentials')} ("proof_id","user_id","credential_id","public_key_cose","counter","revision","rp_id","device_name","transports_json","uv","device_type","backed_up","created_at","last_used_at","revoked_at") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)`,
66
+ values: [record.proofId, record.userId, record.credentialId, record.publicKeyCose, record.counter, record.revision, record.rpId, record.deviceName, record.transports === null ? null : JSON.stringify(record.transports), toBool(record.uv), record.deviceType, record.backedUp === null ? null : toBool(record.backedUp), record.createdAt, record.lastUsedAt, record.revokedAt],
67
+ });
68
+ }
69
+ catch (error) {
70
+ if (isUniqueViolation(error))
71
+ throw new IdentityCustodyErrorV1('webauthn_credential_conflict');
72
+ throw error;
73
+ }
74
+ },
75
+ findById: (proofId) => this.one(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "proof_id" = $1`, [proofId]),
76
+ findByCredentialId: (credentialId) => this.one(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "credential_id" = $1`, [credentialId]),
77
+ listForUser: (userId) => this.all(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "user_id" = $1 ORDER BY "created_at", "proof_id"`, [userId]),
78
+ compareAndSwapCounter: (input) => this.casCounter(input),
79
+ rename: async (proofId, userId, deviceName) => {
80
+ const result = await session.execute({
81
+ text: `UPDATE ${this.t('identity_webauthn_credentials')} SET "device_name" = $3, "revision" = "revision" + 1 WHERE "proof_id" = $1 AND "user_id" = $2 AND "revoked_at" IS NULL`,
82
+ values: [proofId, userId, deviceName],
83
+ });
84
+ if ((result.rowCount ?? 0) === 0)
85
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
86
+ },
87
+ revoke: async (proofId, userId, at) => {
88
+ const current = await this.one(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "proof_id" = $1`, [proofId]);
89
+ if (!current || current.userId !== userId)
90
+ throw new IdentityCustodyErrorV1('identity_material_missing');
91
+ if (current.revokedAt !== null)
92
+ return;
93
+ await session.execute({
94
+ text: `UPDATE ${this.t('identity_webauthn_credentials')} SET "revoked_at" = $3, "revision" = "revision" + 1 WHERE "proof_id" = $1 AND "user_id" = $2`,
95
+ values: [proofId, userId, at],
96
+ });
97
+ },
98
+ };
99
+ this.singleUseProofs = {
100
+ insert: (record) => this.insertProof(record),
101
+ find: (key) => this.findProof(key),
102
+ findChallenge: (challenge, purpose) => this.findChallengeRow(challenge, purpose),
103
+ findLatestEmailCode: (email, candidates, now) => this.findLatestEmailCodeRow(email, candidates, now),
104
+ findMagicLink: (tokenHash) => this.findMagicLinkRow(tokenHash),
105
+ countEmailCodes: async (email, since) => {
106
+ const rows = (await session.execute({
107
+ text: `SELECT COUNT(*) AS "count" FROM ${this.t('identity_single_use_proofs')} WHERE "kind" = 'email_code' AND "email" = $1 AND "created_at" >= $2`,
108
+ values: [email, since],
109
+ })).rows;
110
+ const value = rows[0]?.['count'];
111
+ return typeof value === 'number' ? value : Number(value ?? 0);
112
+ },
113
+ consume: (input) => this.consumeProof(input),
114
+ revoke: async (key, expectedRevision, at) => {
115
+ const result = await session.execute({
116
+ text: `UPDATE ${this.t('identity_single_use_proofs')} SET "state" = 'revoked', "revoked_at" = $4, "revision" = "revision" + 1 WHERE "kind" = $1 AND "proof_id" = $2 AND "state" = 'pending' AND "revision" = $3`,
117
+ values: [key.kind, key.proofId, expectedRevision, at],
118
+ });
119
+ if ((result.rowCount ?? 0) === 0)
120
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
121
+ },
122
+ purgeExpired: async (now) => {
123
+ await session.execute({
124
+ text: `DELETE FROM ${this.t('identity_email_registration_tickets')} WHERE "expires_at" < $1`,
125
+ values: [now],
126
+ });
127
+ const result = await session.execute({
128
+ text: `DELETE FROM ${this.t('identity_single_use_proofs')} AS proof WHERE "expires_at" < $1 AND "state" != 'pending'
129
+ AND NOT ("kind" = 'magic_link' AND "state" = 'consumed' AND "user_id" IS NOT NULL)
130
+ AND NOT EXISTS (SELECT 1 FROM ${this.t('identity_email_registration_tickets')} AS ticket
131
+ WHERE ticket."code_kind" = proof."kind" AND ticket."code_proof_id" = proof."proof_id")`,
132
+ values: [now],
133
+ });
134
+ return result.rowCount ?? 0;
135
+ },
136
+ };
137
+ this.emailTickets = {
138
+ findByTokenHash: (tokenHash) => this.one(decodeEmailTicket, `SELECT * FROM ${this.t('identity_email_registration_tickets')} WHERE "token_hash" = $1`, [tokenHash]),
139
+ importTicket: async (record) => {
140
+ try {
141
+ await session.execute({
142
+ text: `INSERT INTO ${this.t('identity_email_registration_tickets')} ("code_kind","code_proof_id","email","token_hash","user_id","state","revision","created_at","expires_at","consumed_at","revoked_at") VALUES ('email_code',$1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
143
+ values: [record.codeProofId, record.email, record.tokenHash, record.userId, record.state, record.revision, record.createdAt, record.expiresAt, record.consumedAt, record.revokedAt],
144
+ });
145
+ }
146
+ catch (error) {
147
+ if (isUniqueViolation(error))
148
+ throw new IdentityCustodyErrorV1('identity_record_conflict');
149
+ throw error;
150
+ }
151
+ },
152
+ exchangeCode: (input) => this.exchangeCode(input),
153
+ consume: (input) => this.consumeTicket(input),
154
+ revoke: async (codeProofId, expectedRevision, at) => {
155
+ const result = await session.execute({
156
+ text: `UPDATE ${this.t('identity_email_registration_tickets')} SET "state" = 'revoked', "revoked_at" = $3, "revision" = "revision" + 1 WHERE "code_proof_id" = $1 AND "state" = 'pending' AND "revision" = $2`,
157
+ values: [codeProofId, expectedRevision, at],
158
+ });
159
+ if ((result.rowCount ?? 0) === 0)
160
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
161
+ },
162
+ };
163
+ this.invitations = {
164
+ insert: async (record) => {
165
+ try {
166
+ await session.execute({
167
+ text: `INSERT INTO ${this.t('identity_invitation_digests')} ("invitation_id","email","tenant_id","workspace_id","client_id","token_hash","status","expires_at","created_at","consumed_at","consumed_by_user_id","revision") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,
168
+ values: [record.invitationId, record.email, record.tenantId, record.workspaceId, record.clientId, record.tokenHash, record.status, record.expiresAt, record.createdAt, record.consumedAt, record.consumedByUserId, record.revision],
169
+ });
170
+ }
171
+ catch (error) {
172
+ if (isUniqueViolation(error))
173
+ throw new IdentityCustodyErrorV1('identity_record_conflict');
174
+ throw error;
175
+ }
176
+ },
177
+ findById: (invitationId) => this.one(decodeDigestInvitation, `SELECT * FROM ${this.t('identity_invitation_digests')} WHERE "invitation_id" = $1`, [invitationId]),
178
+ findByDigest: (tokenHash) => this.one(decodeDigestInvitation, `SELECT * FROM ${this.t('identity_invitation_digests')} WHERE "token_hash" = $1`, [tokenHash]),
179
+ consumeByDigest: (input) => this.consumeInvitation(input),
180
+ revoke: async (invitationId, expectedRevision, at) => {
181
+ const result = await session.execute({
182
+ text: `UPDATE ${this.t('identity_invitation_digests')} SET "status" = 'revoked', "revision" = "revision" + 1 WHERE "invitation_id" = $1 AND "status" = 'pending' AND "revision" = $2`,
183
+ values: [invitationId, expectedRevision, at],
184
+ });
185
+ if ((result.rowCount ?? 0) === 0)
186
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
187
+ },
188
+ };
189
+ this.sessions = {
190
+ insert: (record) => this.insertBoundSession(record),
191
+ findById: (sessionId) => this.findBoundSession(sessionId),
192
+ findBySessionTokenHash: (hash) => this.findBoundSessionByHash('session_token_hash', hash),
193
+ findByRefreshTokenHash: (hash) => this.findBoundSessionByHash('refresh_token_hash', hash),
194
+ rotate: (input) => this.rotateBoundSession(input),
195
+ touchActivity: async (sessionId, at) => {
196
+ await session.execute({
197
+ text: `UPDATE ${this.t('identity_login_token_bindings')} SET "last_activity_at" = $2 WHERE "session_id" = $1`,
198
+ values: [sessionId, at],
199
+ });
200
+ },
201
+ revoke: (sessionId, at) => this.revokeBoundSession(sessionId, at),
202
+ revokeAllForUser: async (userId, at) => {
203
+ const rows = (await session.execute({
204
+ text: `SELECT "session_id" FROM ${this.t('identity_login_sessions')} WHERE "user_id" = $1 AND "status" = 'active'`,
205
+ values: [userId],
206
+ })).rows;
207
+ let revoked = 0;
208
+ for (const row of rows) {
209
+ await this.revokeBoundSession(String(row['session_id']), at);
210
+ revoked += 1;
211
+ }
212
+ return revoked;
213
+ },
214
+ listForUser: (userId) => this.listBoundSessions(userId),
215
+ };
216
+ this.social = {
217
+ insert: async (record) => {
218
+ try {
219
+ await session.execute({
220
+ text: `INSERT INTO ${this.t('identity_social_links')} ("proof_id","user_id","provider","provider_subject","provider_tenant","email_at_link","email_verified_by_provider","linked_at","last_login_at","revoked_at","revision") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
221
+ values: [record.proofId, record.userId, record.provider, record.providerSubject, record.providerTenant, record.emailAtLink, toBool(record.emailVerifiedByProvider), record.linkedAt, record.lastLoginAt, record.revokedAt, record.revision],
222
+ });
223
+ }
224
+ catch (error) {
225
+ if (isUniqueViolation(error))
226
+ throw new IdentityCustodyErrorV1('social_subject_conflict');
227
+ throw error;
228
+ }
229
+ },
230
+ findById: (proofId) => this.one(decodeSocialLink, `SELECT * FROM ${this.t('identity_social_links')} WHERE "proof_id" = $1`, [proofId]),
231
+ findBySubject: (provider, providerSubject) => this.one(decodeSocialLink, `SELECT * FROM ${this.t('identity_social_links')} WHERE "provider" = $1 AND "provider_subject" = $2`, [provider, providerSubject]),
232
+ listForUser: (userId) => this.all(decodeSocialLink, `SELECT * FROM ${this.t('identity_social_links')} WHERE "user_id" = $1 ORDER BY "linked_at", "proof_id"`, [userId]),
233
+ touchLogin: async (proofId, expectedRevision, at) => {
234
+ const result = await session.execute({
235
+ text: `UPDATE ${this.t('identity_social_links')} SET "last_login_at" = $3, "revision" = "revision" + 1 WHERE "proof_id" = $1 AND "revoked_at" IS NULL AND "revision" = $2`,
236
+ values: [proofId, expectedRevision, at],
237
+ });
238
+ if ((result.rowCount ?? 0) === 0)
239
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
240
+ },
241
+ unlink: async (proofId, userId, expectedRevision, at) => {
242
+ void at;
243
+ const result = await session.execute({
244
+ text: `DELETE FROM ${this.t('identity_social_links')} WHERE "proof_id" = $1 AND "user_id" = $2 AND "revision" = $3`,
245
+ values: [proofId, userId, expectedRevision],
246
+ });
247
+ if ((result.rowCount ?? 0) === 0)
248
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
249
+ },
250
+ };
251
+ }
252
+ t = (table) => custodyTable(this.schema, table);
253
+ one = async (decode, text, values) => {
254
+ const result = await this.session.execute({ text, values });
255
+ return result.rows.length > 0 ? decode(result.rows[0]) : null;
256
+ };
257
+ all = async (decode, text, values) => (await this.session.execute({ text, values })).rows.map(decode);
258
+ casCounter = async (input) => {
259
+ if (![input.expectedCounter, input.newCounter].every((value) => Number.isInteger(value) && value >= 0 && value <= 4294967295)
260
+ || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0 || input.expectedRevision === Number.MAX_SAFE_INTEGER
261
+ || !input.proofId || !input.userId || !Number.isFinite(Date.parse(input.at))) {
262
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
263
+ }
264
+ if ((input.newCounter !== 0 || input.expectedCounter !== 0) && input.newCounter <= input.expectedCounter) {
265
+ const snapshot = await this.one(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "proof_id" = $1`, [input.proofId]);
266
+ if (snapshot && snapshot.userId === input.userId && snapshot.revokedAt === null && snapshot.revision === input.expectedRevision && snapshot.counter === input.expectedCounter) {
267
+ throw new IdentityCustodyErrorV1('webauthn_counter_rejected');
268
+ }
269
+ }
270
+ const updated = await this.one(decodeWebAuthnCredential, `UPDATE ${this.t('identity_webauthn_credentials')} SET "counter" = $5, "last_used_at" = $6, "revision" = "revision" + 1
271
+ WHERE "proof_id" = $1 AND "user_id" = $2 AND "revoked_at" IS NULL AND "revision" = $3 AND "counter" = $4 RETURNING *`, [input.proofId, input.userId, input.expectedRevision, input.expectedCounter, input.newCounter, input.at]);
272
+ if (updated)
273
+ return updated;
274
+ const current = await this.one(decodeWebAuthnCredential, `SELECT * FROM ${this.t('identity_webauthn_credentials')} WHERE "proof_id" = $1`, [input.proofId]);
275
+ if (!current)
276
+ throw new ProofVerificationError('not_found');
277
+ if (current.userId !== input.userId)
278
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
279
+ if (current.revokedAt !== null)
280
+ throw new ProofVerificationError('revoked');
281
+ throw new IdentityCustodyErrorV1('webauthn_credential_stale');
282
+ };
283
+ proofColumns = '"kind","proof_id","user_id","state","revision","created_at","expires_at","consumed_at","revoked_at","challenge","challenge_purpose","rp_id","allowed_origins_json","user_verification","email","secret_digest","digest_algorithm","digest_key_ref"';
284
+ proofValues = (record) => {
285
+ const base = [record.kind, record.proofId, record.userId, record.state, record.revision, record.createdAt, record.expiresAt, record.consumedAt, record.revokedAt];
286
+ if (record.kind === 'webauthn_challenge') {
287
+ return [...base, record.challenge, record.purpose, record.rpId, JSON.stringify(record.allowedOrigins), record.userVerification, null, null, null, null];
288
+ }
289
+ if (record.kind === 'email_code') {
290
+ return [...base, null, null, null, null, null, record.email, record.codeDigest.value, record.codeDigest.algorithm, record.codeDigest.algorithm === 'hmac-sha256' ? record.codeDigest.keyRef : null];
291
+ }
292
+ return [...base, null, null, null, null, null, record.email, record.tokenHash, 'sha256', null];
293
+ };
294
+ insertProof = async (record) => {
295
+ try {
296
+ await this.session.execute({
297
+ text: `INSERT INTO ${this.t('identity_single_use_proofs')} (${this.proofColumns}) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`,
298
+ values: this.proofValues(record),
299
+ });
300
+ }
301
+ catch (error) {
302
+ if (isUniqueViolation(error))
303
+ throw new IdentityCustodyErrorV1('identity_record_conflict');
304
+ throw error;
305
+ }
306
+ };
307
+ findProof = (key) => this.one(decodeSingleUseProof, `SELECT ${this.proofColumns} FROM ${this.t('identity_single_use_proofs')} WHERE "kind" = $1 AND "proof_id" = $2`, [key.kind, key.proofId]);
308
+ findChallengeRow = (challenge, purpose) => this.one(decodeSingleUseProof, `SELECT ${this.proofColumns} FROM ${this.t('identity_single_use_proofs')} WHERE "kind" = 'webauthn_challenge' AND "challenge" = $1 AND "challenge_purpose" = $2`, [challenge, purpose]).then((row) => (row && row.kind === 'webauthn_challenge' ? row : null));
309
+ findLatestEmailCodeRow = async (email, candidates, now) => {
310
+ const rows = await this.all(decodeSingleUseProof, `SELECT ${this.proofColumns} FROM ${this.t('identity_single_use_proofs')} WHERE "kind" = 'email_code' AND "email" = $1 AND "state" = 'pending' AND "expires_at" > $2 ORDER BY "created_at" DESC, "proof_id" DESC`, [email, now]);
311
+ for (const row of rows) {
312
+ if (row.kind !== 'email_code')
313
+ continue;
314
+ for (const candidate of candidates) {
315
+ const keyRef = candidate.algorithm === 'hmac-sha256' ? (candidate.keyRef ?? null) : null;
316
+ const rowKeyRef = row.codeDigest.algorithm === 'hmac-sha256' ? row.codeDigest.keyRef : null;
317
+ if (row.codeDigest.algorithm === candidate.algorithm && rowKeyRef === keyRef && row.codeDigest.value === candidate.value) {
318
+ return row;
319
+ }
320
+ }
321
+ }
322
+ return null;
323
+ };
324
+ findMagicLinkRow = (tokenHash) => this.one(decodeSingleUseProof, `SELECT ${this.proofColumns} FROM ${this.t('identity_single_use_proofs')} WHERE "kind" = 'magic_link' AND "secret_digest" = $1`, [tokenHash]).then((row) => (row && row.kind === 'magic_link' ? row : null));
325
+ consumeProof = async (input) => {
326
+ if (!(input.at > ''))
327
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
328
+ const current = await this.findProof(input.key);
329
+ if (!current || current.state !== 'pending')
330
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
331
+ if (current.userId !== input.expectedUserId)
332
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
333
+ if (current.revision !== input.expectedRevision)
334
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
335
+ if (!(current.expiresAt > input.at))
336
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
337
+ if (input.bindUserId !== null && current.userId !== null && current.userId !== input.bindUserId) {
338
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
339
+ }
340
+ if (input.match.kind !== current.kind)
341
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
342
+ if (input.match.kind === 'webauthn_challenge' && current.kind === 'webauthn_challenge') {
343
+ if (input.match.challenge !== current.challenge || input.match.purpose !== current.purpose || input.match.rpId !== current.rpId) {
344
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
345
+ }
346
+ }
347
+ else if (input.match.kind === 'email_code' && current.kind === 'email_code') {
348
+ if (input.match.email !== current.email)
349
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
350
+ const rowKeyRef = current.codeDigest.algorithm === 'hmac-sha256' ? current.codeDigest.keyRef : null;
351
+ const matchKeyRef = input.match.digest.algorithm === 'hmac-sha256' ? input.match.digest.keyRef : null;
352
+ if (input.match.digest.algorithm !== current.codeDigest.algorithm || matchKeyRef !== rowKeyRef || input.match.digest.value !== current.codeDigest.value) {
353
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
354
+ }
355
+ }
356
+ else if (input.match.kind === 'magic_link' && current.kind === 'magic_link') {
357
+ if (input.match.email !== current.email || input.match.tokenHash !== current.tokenHash) {
358
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
359
+ }
360
+ }
361
+ else {
362
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
363
+ }
364
+ const boundUserId = input.bindUserId ?? current.userId;
365
+ const updated = await this.one(decodeSingleUseProof, `UPDATE ${this.t('identity_single_use_proofs')} SET "state" = 'consumed', "consumed_at" = $4, "user_id" = $5, "revision" = "revision" + 1
366
+ WHERE "kind" = $1 AND "proof_id" = $2 AND "state" = 'pending' AND "revision" = $3 RETURNING ${this.proofColumns}`, [input.key.kind, input.key.proofId, input.expectedRevision, input.at, boundUserId]);
367
+ if (!updated)
368
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
369
+ return updated;
370
+ };
371
+ exchangeCode = async (input) => {
372
+ const consumed = await this.consumeProof({
373
+ key: { kind: 'email_code', proofId: input.codeProofId },
374
+ expectedRevision: input.expectedRevision,
375
+ expectedUserId: null,
376
+ match: { kind: 'email_code', email: input.email, digest: input.digest },
377
+ bindUserId: null,
378
+ at: input.at,
379
+ });
380
+ if (consumed.kind !== 'email_code')
381
+ throw new IdentityCustodyErrorV1('proof_binding_mismatch');
382
+ try {
383
+ await this.session.execute({
384
+ text: `INSERT INTO ${this.t('identity_email_registration_tickets')} ("code_kind","code_proof_id","email","token_hash","user_id","state","revision","created_at","expires_at","consumed_at","revoked_at") VALUES ('email_code',$1,$2,$3,$4,'pending',$5,$6,$7,$8,$9)`,
385
+ values: [input.ticket.codeProofId, input.ticket.email, input.ticket.tokenHash, input.ticket.userId, input.ticket.revision, input.ticket.createdAt, input.ticket.expiresAt, input.ticket.consumedAt, input.ticket.revokedAt],
386
+ });
387
+ }
388
+ catch (error) {
389
+ if (isUniqueViolation(error))
390
+ throw new IdentityCustodyErrorV1('identity_record_conflict');
391
+ throw error;
392
+ }
393
+ const stored = await this.one(decodeEmailTicket, `SELECT * FROM ${this.t('identity_email_registration_tickets')} WHERE "code_proof_id" = $1`, [input.ticket.codeProofId]);
394
+ if (!stored)
395
+ throw new IdentityCustodyErrorV1('identity_material_missing');
396
+ return stored;
397
+ };
398
+ consumeTicket = async (input) => {
399
+ const updated = await this.one(decodeEmailTicket, `UPDATE ${this.t('identity_email_registration_tickets')} SET "state" = 'consumed', "consumed_at" = $5, "user_id" = $4, "revision" = "revision" + 1
400
+ WHERE "token_hash" = $1 AND "email" = $2 AND "state" = 'pending' AND "revision" = $3 AND "expires_at" > $6 RETURNING *`, [input.tokenHash, input.email, input.expectedRevision, input.bindUserId, input.at, input.at]);
401
+ if (!updated)
402
+ throw new IdentityCustodyErrorV1('proof_state_conflict');
403
+ return updated;
404
+ };
405
+ consumeInvitation = async (input) => {
406
+ const updated = await this.one(decodeDigestInvitation, `UPDATE ${this.t('identity_invitation_digests')} SET "status" = 'consumed', "consumed_at" = $6, "consumed_by_user_id" = $5, "revision" = "revision" + 1
407
+ WHERE "token_hash" = $1 AND "email" = $2 AND "status" = 'pending' AND "revision" = $3 AND "expires_at" > $6
408
+ AND ("client_id" IS NULL OR "client_id" = $4) RETURNING *`, [input.tokenHash, input.email, input.expectedRevision, input.clientId, input.userId, input.at]);
409
+ if (!updated)
410
+ throw new InvitationError('consumed');
411
+ return updated;
412
+ };
413
+ baseSessionColumns = '"session_id","user_id","status","mfa_state","created_at","expires_at","revoked_at","refresh_count"';
414
+ readBoundSession = async (where, values) => {
415
+ const binding = await this.one(decodeBoundSession, `SELECT * FROM ${this.t('identity_login_token_bindings')} WHERE ${where}`, values);
416
+ if (!binding)
417
+ return null;
418
+ const base = await this.one(decodeSession, `SELECT ${this.baseSessionColumns} FROM ${this.t('identity_login_sessions')} WHERE "session_id" = $1`, [binding.sessionId]);
419
+ if (!base)
420
+ throw new IdentityCustodyErrorV1('identity_material_missing');
421
+ return { ...binding, userId: base.userId, createdAt: base.createdAt, expiresAt: base.expiresAt, revokedAt: base.revokedAt ?? null };
422
+ };
423
+ insertBoundSession = async (record) => {
424
+ if (record.refreshTokenHash !== null && record.refreshTokenHash === record.sessionTokenHash) {
425
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
426
+ }
427
+ try {
428
+ await this.session.execute({
429
+ text: `INSERT INTO ${this.t('identity_login_sessions')} (${this.baseSessionColumns}) VALUES ($1,$2,'active',$3,$4,$5,NULL,$6)`,
430
+ values: [record.sessionId, record.userId, record.login.mfaVerified ? 'step_up' : 'none', record.createdAt, record.expiresAt, record.rotationVersion],
431
+ });
432
+ await this.session.execute({
433
+ text: `INSERT INTO ${this.t('identity_login_token_bindings')} ("session_id","session_token_hash","refresh_token_hash","mfa_verified","auth_time","session_version","rotation_version","device_name","ip_address","user_agent","last_activity_at") VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
434
+ values: [record.sessionId, record.sessionTokenHash, record.refreshTokenHash, toBool(record.login.mfaVerified), record.login.authTime, record.login.sessionVersion, record.rotationVersion, record.deviceName, record.ipAddress, record.userAgent, record.lastActivityAt],
435
+ });
436
+ }
437
+ catch (error) {
438
+ if (isUniqueViolation(error))
439
+ throw new IdentityCustodyErrorV1('identity_record_conflict');
440
+ throw error;
441
+ }
442
+ };
443
+ findBoundSession = (sessionId) => this.readBoundSession('"session_id" = $1', [sessionId]);
444
+ findBoundSessionByHash = (column, hash) => this.readBoundSession(`"${column}" = $1`, [hash]);
445
+ listBoundSessions = async (userId) => {
446
+ const ids = (await this.session.execute({
447
+ text: `SELECT "session_id" FROM ${this.t('identity_login_sessions')} WHERE "user_id" = $1 ORDER BY "created_at", "session_id"`,
448
+ values: [userId],
449
+ })).rows;
450
+ const out = [];
451
+ for (const row of ids) {
452
+ const found = await this.findBoundSession(String(row['session_id']));
453
+ if (found)
454
+ out.push(found);
455
+ }
456
+ return out;
457
+ };
458
+ rotateBoundSession = async (input) => {
459
+ if (input.nextRefreshTokenHash === input.nextSessionTokenHash) {
460
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
461
+ }
462
+ if (!(input.nextExpiresAt > input.at))
463
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
464
+ if (input.expectedRotationVersion < 0 || !Number.isSafeInteger(input.expectedRotationVersion)) {
465
+ throw new IdentityCustodyErrorV1('identity_material_invalid');
466
+ }
467
+ const current = await this.findBoundSession(input.sessionId);
468
+ if (!current || current.userId !== input.userId)
469
+ throw new IdentityCustodyErrorV1('login_binding_mismatch');
470
+ if (current.refreshTokenHash === null || current.refreshTokenHash !== input.expectedRefreshTokenHash) {
471
+ throw new IdentityCustodyErrorV1('login_refresh_conflict');
472
+ }
473
+ if (current.rotationVersion !== input.expectedRotationVersion)
474
+ throw new IdentityCustodyErrorV1('login_refresh_conflict');
475
+ if (current.revokedAt !== null)
476
+ throw new IdentityCustodyErrorV1('login_binding_mismatch');
477
+ if (!(current.expiresAt > input.at))
478
+ throw new IdentityCustodyErrorV1('login_binding_mismatch');
479
+ if (current.login.mfaVerified !== input.verifiedLogin.mfaVerified || current.login.authTime !== input.verifiedLogin.authTime || current.login.sessionVersion !== input.verifiedLogin.sessionVersion) {
480
+ throw new IdentityCustodyErrorV1('login_binding_mismatch');
481
+ }
482
+ const updated = await this.one(decodeBoundSession, `UPDATE ${this.t('identity_login_token_bindings')} SET "session_token_hash" = $5, "refresh_token_hash" = $6, "rotation_version" = "rotation_version" + 1, "last_activity_at" = $7
483
+ WHERE "session_id" = $1 AND "refresh_token_hash" = $2 AND "rotation_version" = $3
484
+ AND "mfa_verified" = $4 AND "auth_time" = $8 AND "session_version" = $9 RETURNING *`, [input.sessionId, input.expectedRefreshTokenHash, input.expectedRotationVersion, toBool(input.verifiedLogin.mfaVerified), input.nextSessionTokenHash, input.nextRefreshTokenHash, input.at, input.verifiedLogin.authTime, input.verifiedLogin.sessionVersion]);
485
+ if (!updated)
486
+ throw new IdentityCustodyErrorV1('login_refresh_conflict');
487
+ await this.session.execute({
488
+ text: `UPDATE ${this.t('identity_login_sessions')} SET "expires_at" = $2, "refresh_count" = "refresh_count" + 1 WHERE "session_id" = $1 AND "status" = 'active'`,
489
+ values: [input.sessionId, input.nextExpiresAt],
490
+ });
491
+ const reread = await this.findBoundSession(input.sessionId);
492
+ if (!reread)
493
+ throw new IdentityCustodyErrorV1('identity_material_missing');
494
+ return reread;
495
+ };
496
+ revokeBoundSession = async (sessionId, at) => {
497
+ await this.session.execute({
498
+ text: `UPDATE ${this.t('identity_login_sessions')} SET "status" = 'revoked', "revoked_at" = $2 WHERE "session_id" = $1`,
499
+ values: [sessionId, at],
500
+ });
501
+ };
502
+ }
503
+ let custodyTxCounter = 0;
504
+ const nextCustodyTxId = () => {
505
+ custodyTxCounter += 1;
506
+ return `custody-pg-${Date.now().toString(36)}-${custodyTxCounter}`;
507
+ };
508
+ /**
509
+ * Combined custody handle: the transaction-scoped stores plus the deletion
510
+ * journal/outbox over the same session. One object joins every callback.
511
+ */
512
+ export class PostgresCustodyHandle extends PostgresCustodyTx {
513
+ journal;
514
+ constructor(schema, session) {
515
+ super(schema, session);
516
+ this.journal = new PostgresCustodyJournal(schema, session);
517
+ }
518
+ get stores() {
519
+ return this;
520
+ }
521
+ get profile() {
522
+ return 'postgres';
523
+ }
524
+ get raw() {
525
+ return this.session;
526
+ }
527
+ }
528
+ /** Host-owned serializable unit of work over one control schema. */
529
+ export const createPostgresIdentityUnitOfWorkV1 = (input) => {
530
+ const run = async (options, operation) => {
531
+ requireIdentityRunOptions(options);
532
+ const readOnly = options.mode === 'read';
533
+ const deadline = Date.now() + options.deadlineMs;
534
+ let attempt = 0;
535
+ for (;;) {
536
+ attempt += 1;
537
+ try {
538
+ return await input.host.runSerializable({ readOnly, deadlineMs: Math.max(1, deadline - Date.now()) }, async (binding) => {
539
+ if (binding.readOnly !== readOnly)
540
+ throw new IdentityCustodyErrorV1('identity_transaction_unbound');
541
+ const guard = identityTransactionGuard(readOnly, deadline);
542
+ const handle = new PostgresCustodyHandle(input.schema, guard.postgres(binding.session));
543
+ try {
544
+ const result = await operation(rebindIdentityTransactionHost(composeIdentityTransaction({ host: handle, transactionId: binding.transactionId, readOnly, check: guard.check }), binding.hostTransaction));
545
+ guard.check();
546
+ return result;
547
+ }
548
+ finally {
549
+ guard.close();
550
+ }
551
+ });
552
+ }
553
+ catch (error) {
554
+ if (attempt < options.maxAttempts && Date.now() < deadline && (isSerializationFailure(error) || isSocialRaceRetry(error)))
555
+ continue;
556
+ if (isSocialRaceRetry(error))
557
+ throw new IdentityCustodyErrorV1(error.finalCode);
558
+ throw error;
559
+ }
560
+ }
561
+ };
562
+ return {
563
+ profile: 'postgres',
564
+ run,
565
+ };
566
+ };
567
+ export const createPostgresIdentityHostV1 = (options) => ({
568
+ runSerializable: async (runOptions, operation) => {
569
+ await applyPostgresIdentityCoreSchemaIfNeeded(options);
570
+ return options.driver.transaction({ isolation: 'serializable', readOnly: runOptions.readOnly, deadlineMs: runOptions.deadlineMs }, async (rawSession) => {
571
+ const guard = identityTransactionGuard(runOptions.readOnly, Date.now() + runOptions.deadlineMs);
572
+ const session = guard.postgres(rawSession);
573
+ try {
574
+ const result = await operation({ transactionId: nextCustodyTxId(), hostTransaction: new PostgresCustodyHandle(options.schema, session), session, readOnly: runOptions.readOnly });
575
+ guard.check();
576
+ return result;
577
+ }
578
+ finally {
579
+ guard.close();
580
+ }
581
+ });
582
+ },
583
+ });
584
+ const schemaReadyByDriver = new WeakMap();
585
+ /** Idempotent custody DDL; safe to call concurrently. */
586
+ export const applyPostgresIdentityCoreSchemaIfNeeded = async (options) => {
587
+ const { driver, schema, deadlineMs = CUSTODY_TX_DEADLINE_MS } = options;
588
+ let bySchema = schemaReadyByDriver.get(driver);
589
+ if (!bySchema) {
590
+ bySchema = new Map();
591
+ schemaReadyByDriver.set(driver, bySchema);
592
+ }
593
+ let ready = bySchema.get(schema);
594
+ if (!ready) {
595
+ ready = driver
596
+ .transaction({ isolation: 'serializable', readOnly: false, deadlineMs }, async (session) => {
597
+ await session.execute({ text: `CREATE SCHEMA IF NOT EXISTS "${schema}"`, values: [] });
598
+ // One probe instead of 34 round trips when the schema was provisioned
599
+ // atomically beforehand (the DDL below is all IF NOT EXISTS, so a
600
+ // complete table set means the whole batch already committed).
601
+ const present = await session.execute({
602
+ text: 'SELECT count(*)::int AS n FROM information_schema.tables WHERE table_schema = $1 AND table_name = ANY($2)',
603
+ values: [schema, [...IDENTITY_TABLES]],
604
+ });
605
+ if (Number(present.rows[0]?.['n']) !== IDENTITY_TABLES.length) {
606
+ for (const ddl of identitySchemaStatements('postgres', schema)) {
607
+ await session.execute({ text: ddl, values: [] });
608
+ }
609
+ }
610
+ })
611
+ .catch((error) => {
612
+ bySchema.delete(schema);
613
+ throw error;
614
+ });
615
+ bySchema.set(schema, ready);
616
+ }
617
+ return ready;
618
+ };
619
+ /** Standalone per-method custody stores for direct store tests. */
620
+ export const createPostgresCustodyStores = (options) => {
621
+ const runTx = async (readOnly, op) => {
622
+ const host = createPostgresIdentityHostV1(options);
623
+ const unitOfWork = createPostgresIdentityUnitOfWorkV1({ schema: options.schema, host });
624
+ const runOptions = { mode: readOnly ? 'read' : 'write', purpose: 'request', maxAttempts: 3, deadlineMs: options.deadlineMs ?? CUSTODY_TX_DEADLINE_MS };
625
+ return unitOfWork.run(runOptions, (tx) => op(tx.hostTransaction));
626
+ };
627
+ return {
628
+ subjects: {
629
+ register: (account, profile) => runTx(false, (tx) => tx.subjects.register(account, profile)),
630
+ updateEmail: (userId, email, at) => runTx(false, (tx) => tx.subjects.updateEmail(userId, email, at)),
631
+ },
632
+ profiles: {
633
+ find: (userId) => runTx(true, (tx) => tx.profiles.find(userId)),
634
+ put: (record) => runTx(false, (tx) => tx.profiles.put(record)).then(() => undefined),
635
+ },
636
+ credentials: {
637
+ insert: (record) => runTx(false, (tx) => tx.credentials.insert(record)).then(() => undefined),
638
+ findById: (proofId) => runTx(true, (tx) => tx.credentials.findById(proofId)),
639
+ findByCredentialId: (credentialId) => runTx(true, (tx) => tx.credentials.findByCredentialId(credentialId)),
640
+ listForUser: (userId) => runTx(true, (tx) => tx.credentials.listForUser(userId)),
641
+ compareAndSwapCounter: (input) => runTx(false, (tx) => tx.credentials.compareAndSwapCounter(input)),
642
+ rename: (proofId, userId, deviceName) => runTx(false, (tx) => tx.credentials.rename(proofId, userId, deviceName)).then(() => undefined),
643
+ revoke: (proofId, userId, at) => runTx(false, (tx) => tx.credentials.revoke(proofId, userId, at)).then(() => undefined),
644
+ },
645
+ singleUseProofs: {
646
+ insert: (record) => runTx(false, (tx) => tx.singleUseProofs.insert(record)).then(() => undefined),
647
+ find: (key) => runTx(true, (tx) => tx.singleUseProofs.find(key)),
648
+ findChallenge: (challenge, purpose) => runTx(true, (tx) => tx.singleUseProofs.findChallenge(challenge, purpose)),
649
+ findLatestEmailCode: (email, candidates, now) => runTx(true, (tx) => tx.singleUseProofs.findLatestEmailCode(email, candidates, now)),
650
+ findMagicLink: (tokenHash) => runTx(true, (tx) => tx.singleUseProofs.findMagicLink(tokenHash)),
651
+ countEmailCodes: (email, since) => runTx(true, (tx) => tx.singleUseProofs.countEmailCodes(email, since)),
652
+ consume: (input) => runTx(false, (tx) => tx.singleUseProofs.consume(input)),
653
+ revoke: (key, expectedRevision, at) => runTx(false, (tx) => tx.singleUseProofs.revoke(key, expectedRevision, at)).then(() => undefined),
654
+ purgeExpired: (now) => runTx(false, (tx) => tx.singleUseProofs.purgeExpired(now)),
655
+ },
656
+ emailTickets: {
657
+ findByTokenHash: (tokenHash) => runTx(true, (tx) => tx.emailTickets.findByTokenHash(tokenHash)),
658
+ importTicket: (record) => runTx(false, (tx) => tx.emailTickets.importTicket(record)).then(() => undefined),
659
+ exchangeCode: (input) => runTx(false, (tx) => tx.emailTickets.exchangeCode(input)),
660
+ consume: (input) => runTx(false, (tx) => tx.emailTickets.consume(input)),
661
+ revoke: (codeProofId, expectedRevision, at) => runTx(false, (tx) => tx.emailTickets.revoke(codeProofId, expectedRevision, at)).then(() => undefined),
662
+ },
663
+ invitations: {
664
+ insert: (record) => runTx(false, (tx) => tx.invitations.insert(record)).then(() => undefined),
665
+ findById: (invitationId) => runTx(true, (tx) => tx.invitations.findById(invitationId)),
666
+ findByDigest: (tokenHash) => runTx(true, (tx) => tx.invitations.findByDigest(tokenHash)),
667
+ consumeByDigest: (input) => runTx(false, (tx) => tx.invitations.consumeByDigest(input)),
668
+ revoke: (invitationId, expectedRevision, at) => runTx(false, (tx) => tx.invitations.revoke(invitationId, expectedRevision, at)).then(() => undefined),
669
+ },
670
+ sessions: {
671
+ insert: (record) => runTx(false, (tx) => tx.sessions.insert(record)).then(() => undefined),
672
+ findById: (sessionId) => runTx(true, (tx) => tx.sessions.findById(sessionId)),
673
+ findBySessionTokenHash: (hash) => runTx(true, (tx) => tx.sessions.findBySessionTokenHash(hash)),
674
+ findByRefreshTokenHash: (hash) => runTx(true, (tx) => tx.sessions.findByRefreshTokenHash(hash)),
675
+ rotate: (input) => runTx(false, (tx) => tx.sessions.rotate(input)),
676
+ touchActivity: (sessionId, at) => runTx(false, (tx) => tx.sessions.touchActivity(sessionId, at)).then(() => undefined),
677
+ revoke: (sessionId, at) => runTx(false, (tx) => tx.sessions.revoke(sessionId, at)).then(() => undefined),
678
+ revokeAllForUser: (userId, at) => runTx(false, (tx) => tx.sessions.revokeAllForUser(userId, at)),
679
+ listForUser: (userId) => runTx(true, (tx) => tx.sessions.listForUser(userId)),
680
+ },
681
+ social: {
682
+ insert: (record) => runTx(false, (tx) => tx.social.insert(record)).then(() => undefined),
683
+ findById: (proofId) => runTx(true, (tx) => tx.social.findById(proofId)),
684
+ findBySubject: (provider, providerSubject) => runTx(true, (tx) => tx.social.findBySubject(provider, providerSubject)),
685
+ listForUser: (userId) => runTx(true, (tx) => tx.social.listForUser(userId)),
686
+ touchLogin: (proofId, expectedRevision, at) => runTx(false, (tx) => tx.social.touchLogin(proofId, expectedRevision, at)).then(() => undefined),
687
+ unlink: (proofId, userId, expectedRevision, at) => runTx(false, (tx) => tx.social.unlink(proofId, userId, expectedRevision, at)).then(() => undefined),
688
+ },
689
+ };
690
+ };
691
+ /** Applies the custody asset on the caller's active binding; never begins or commits. */
692
+ export const applyPostgresIdentityCustodySchemaV1 = async (input) => {
693
+ const asset = identityCustodySchemaAssetV1('postgres');
694
+ if (asset.assetSha256 !== input.expectedAssetSha256)
695
+ throw new IdentityCustodyErrorV1('identity_contract_unavailable');
696
+ const session = input.binding.session;
697
+ await session.execute({ text: `CREATE SCHEMA IF NOT EXISTS "${input.schema}"`, values: [] });
698
+ for (const ddl of identitySchemaStatements('postgres', input.schema)) {
699
+ await session.execute({ text: ddl, values: [] });
700
+ }
701
+ const existing = await session.execute({
702
+ text: `SELECT * FROM "${input.schema}"."identity_custody_schema_versions" WHERE "migration_id" = 'A2.0b/1'`,
703
+ values: [],
704
+ });
705
+ const row = existing.rows[0];
706
+ if (row) {
707
+ if (row['asset_sha256'] !== asset.assetSha256 || row['contract_version'] !== '1.1.0') {
708
+ throw new IdentityCustodyErrorV1('identity_contract_unavailable');
709
+ }
710
+ return { migrationId: 'A2.0b/1', contractVersion: '1.1.0', profile: 'postgres', assetSha256: asset.assetSha256, appliedAt: String(row['applied_at']) };
711
+ }
712
+ await session.execute({
713
+ text: `INSERT INTO "${input.schema}"."identity_custody_schema_versions" ("migration_id","contract_version","asset_sha256","applied_at") VALUES ('A2.0b/1','1.1.0',$1,$2)`,
714
+ values: [asset.assetSha256, input.appliedAt],
715
+ });
716
+ return { migrationId: 'A2.0b/1', contractVersion: '1.1.0', profile: 'postgres', assetSha256: asset.assetSha256, appliedAt: input.appliedAt };
717
+ };
718
+ export const bindPostgresIdentityTransactionV1 = (input) => rebindIdentityTransactionHost(composeIdentityTransaction({
719
+ host: new PostgresCustodyHandle(input.schema, input.binding.session),
720
+ transactionId: input.binding.transactionId, readOnly: input.binding.readOnly,
721
+ check: (write) => { if (write && input.binding.readOnly)
722
+ throw new IdentityCustodyErrorV1('identity_transaction_unbound'); },
723
+ }), input.binding.hostTransaction);
724
+ /** V1 factory name for the standalone PostgreSQL custody stores. */
725
+ export const createPostgresIdentityCustodyStoresV1 = createPostgresCustodyStores;
726
+ //# sourceMappingURL=custody-postgres.js.map