@fabrika/iam 0.0.0-stage → 0.9.0-dev.26

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 (312) hide show
  1. package/fabrika.config.ts +267 -0
  2. package/migrations/0001_init.sql +316 -0
  3. package/migrations/0002_oauth.sql +38 -0
  4. package/migrations/0003_contract_apps.sql +11 -0
  5. package/migrations/0004_membership.sql +93 -0
  6. package/migrations/0005_workloads.sql +23 -0
  7. package/migrations/0006_membership_transport_keys.sql +16 -0
  8. package/migrations/0007_member_directory.sql +7 -0
  9. package/migrations/0008_durable_audit.sql +28 -0
  10. package/migrations/0009_member_lookups.sql +7 -0
  11. package/migrations/0010_workload_issues.sql +6 -0
  12. package/migrations/0011_app_presentation.sql +15 -0
  13. package/migrations/0012_external_principals.sql +10 -0
  14. package/migrations/0013_app_mail_templates.sql +14 -0
  15. package/migrations/0014_invitation_wording.sql +8 -0
  16. package/migrations/0015_app_schema_revisions.sql +15 -0
  17. package/migrations/0016_principal_grant_revision.sql +9 -0
  18. package/migrations/0017_app_sign_ins.sql +12 -0
  19. package/migrations/0018_app_members.sql +13 -0
  20. package/migrations/0019_app_mail_html.sql +7 -0
  21. package/migrations/0020_public_workloads.sql +34 -0
  22. package/migrations/0021_installation_brand.sql +19 -0
  23. package/migrations/0022_password_policy.sql +12 -0
  24. package/migrations/0023_terminals.sql +155 -0
  25. package/migrations/0024_app_terminals.sql +10 -0
  26. package/migrations/0025_terminal_completion.sql +10 -0
  27. package/migrations/0026_terminal_generation.sql +12 -0
  28. package/migrations/0027_application_exact_actions.sql +28 -0
  29. package/migrations/0028_oauth_client_assertions.sql +10 -0
  30. package/migrations/0029_role_via.sql +6 -0
  31. package/migrations/0030_membership_role_via.sql +12 -0
  32. package/migrations/0031_person_locale.sql +11 -0
  33. package/migrations-postgres/0001_init.sql +331 -0
  34. package/migrations-postgres/0002_oauth.sql +36 -0
  35. package/migrations-postgres/0003_contract_apps.sql +8 -0
  36. package/migrations-postgres/0004_membership.sql +92 -0
  37. package/migrations-postgres/0005_workloads.sql +18 -0
  38. package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
  39. package/migrations-postgres/0007_member_directory.sql +7 -0
  40. package/migrations-postgres/0008_durable_audit.sql +8 -0
  41. package/migrations-postgres/0009_member_lookups.sql +7 -0
  42. package/migrations-postgres/0010_workload_issues.sql +6 -0
  43. package/migrations-postgres/0011_app_presentation.sql +15 -0
  44. package/migrations-postgres/0012_external_principals.sql +10 -0
  45. package/migrations-postgres/0013_app_mail_templates.sql +14 -0
  46. package/migrations-postgres/0014_invitation_wording.sql +8 -0
  47. package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
  48. package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
  49. package/migrations-postgres/0017_app_sign_ins.sql +12 -0
  50. package/migrations-postgres/0018_app_members.sql +13 -0
  51. package/migrations-postgres/0019_app_mail_html.sql +7 -0
  52. package/migrations-postgres/0020_public_workloads.sql +9 -0
  53. package/migrations-postgres/0021_installation_brand.sql +19 -0
  54. package/migrations-postgres/0022_password_policy.sql +12 -0
  55. package/migrations-postgres/0023_terminals.sql +70 -0
  56. package/migrations-postgres/0024_app_terminals.sql +10 -0
  57. package/migrations-postgres/0025_terminal_completion.sql +10 -0
  58. package/migrations-postgres/0026_terminal_generation.sql +12 -0
  59. package/migrations-postgres/0027_application_exact_actions.sql +28 -0
  60. package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
  61. package/migrations-postgres/0029_role_via.sql +4 -0
  62. package/migrations-postgres/0030_membership_role_via.sql +7 -0
  63. package/migrations-postgres/0031_person_locale.sql +11 -0
  64. package/package.json +70 -5
  65. package/src/admin/access.ts +47 -0
  66. package/src/admin/api-keys.ts +280 -0
  67. package/src/admin/app-people.ts +209 -0
  68. package/src/admin/app-schema.ts +308 -0
  69. package/src/admin/audit.ts +81 -0
  70. package/src/admin/brand.ts +54 -0
  71. package/src/admin/connections.ts +48 -0
  72. package/src/admin/context.ts +70 -0
  73. package/src/admin/grant-support.ts +192 -0
  74. package/src/admin/grants.ts +189 -0
  75. package/src/admin/handlers.ts +102 -0
  76. package/src/admin/http.ts +24 -0
  77. package/src/admin/membership-keys.ts +38 -0
  78. package/src/admin/pagination.ts +28 -0
  79. package/src/admin/password-policy.ts +48 -0
  80. package/src/admin/passwords.ts +78 -0
  81. package/src/admin/policies.ts +136 -0
  82. package/src/admin/principals.ts +226 -0
  83. package/src/admin/router.ts +291 -0
  84. package/src/admin/rpc.ts +387 -0
  85. package/src/admin/sessions.ts +115 -0
  86. package/src/admin/share-links.ts +127 -0
  87. package/src/admin/terminals.ts +115 -0
  88. package/src/admin/user-admin.ts +76 -0
  89. package/src/admin/workloads.ts +85 -0
  90. package/src/app-presentation.ts +178 -0
  91. package/src/app.ts +158 -0
  92. package/src/auth/cookies.ts +64 -0
  93. package/src/auth/failure.ts +25 -0
  94. package/src/auth/handoff.ts +136 -0
  95. package/src/auth/http.ts +88 -0
  96. package/src/auth/invitations.ts +220 -0
  97. package/src/auth/known-device.ts +44 -0
  98. package/src/auth/login.ts +162 -0
  99. package/src/auth/oidc-flight.ts +91 -0
  100. package/src/auth/oidc.ts +148 -0
  101. package/src/auth/password.ts +416 -0
  102. package/src/auth/routes.ts +108 -0
  103. package/src/auth/sessions.ts +249 -0
  104. package/src/auth/terminals.ts +284 -0
  105. package/src/auth.ts +193 -0
  106. package/src/binding-identity.ts +25 -0
  107. package/src/bounded-body.ts +35 -0
  108. package/src/catalog/cs.ts +147 -0
  109. package/src/catalog/en.ts +148 -0
  110. package/src/catalog/index.ts +122 -0
  111. package/src/catalog/uk.ts +164 -0
  112. package/src/client-address.ts +39 -0
  113. package/src/common-passwords.ts +37 -0
  114. package/src/contract-rules.ts +80 -0
  115. package/src/cron.ts +54 -0
  116. package/src/db.ts +128 -0
  117. package/src/delegation.ts +100 -0
  118. package/src/device-http.ts +39 -0
  119. package/src/device.ts +269 -0
  120. package/src/email-identity.ts +2 -0
  121. package/src/env.ts +132 -0
  122. package/src/handoff.ts +175 -0
  123. package/src/html.ts +4 -0
  124. package/src/human-admission.ts +40 -0
  125. package/src/identification.ts +185 -0
  126. package/src/index.ts +292 -0
  127. package/src/installation-brand.ts +82 -0
  128. package/src/issue.ts +265 -0
  129. package/src/json.ts +30 -0
  130. package/src/log.ts +26 -0
  131. package/src/membership-http.ts +135 -0
  132. package/src/membership.ts +1210 -0
  133. package/src/messages.ts +44 -0
  134. package/src/narrow-permissions.ts +26 -0
  135. package/src/node/browser-identity.ts +69 -0
  136. package/src/node/migrate.ts +52 -0
  137. package/src/node/prune.ts +34 -0
  138. package/src/node/runtime.ts +221 -0
  139. package/src/node/server.ts +104 -0
  140. package/src/oauth-client-auth.ts +93 -0
  141. package/src/oauth-client.ts +145 -0
  142. package/src/oauth-config.ts +72 -0
  143. package/src/oauth-http.ts +262 -0
  144. package/src/oauth.ts +272 -0
  145. package/src/oidc.ts +260 -0
  146. package/src/origin.ts +29 -0
  147. package/src/password-crypto.ts +148 -0
  148. package/src/password-db.ts +419 -0
  149. package/src/password-minimum.ts +44 -0
  150. package/src/password-pages.ts +397 -0
  151. package/src/password-policy.ts +79 -0
  152. package/src/password-service.ts +67 -0
  153. package/src/person-locale.ts +103 -0
  154. package/src/proxy-proof.ts +36 -0
  155. package/src/relay-mail.ts +64 -0
  156. package/src/repositories/app-schema.ts +550 -0
  157. package/src/repositories/audit.ts +405 -0
  158. package/src/repositories/brand.ts +66 -0
  159. package/src/repositories/credentials.ts +331 -0
  160. package/src/repositories/device.ts +137 -0
  161. package/src/repositories/grants.ts +404 -0
  162. package/src/repositories/handoff.ts +103 -0
  163. package/src/repositories/membership-transport.ts +49 -0
  164. package/src/repositories/membership.ts +875 -0
  165. package/src/repositories/oauth.ts +122 -0
  166. package/src/repositories/password-policy.ts +44 -0
  167. package/src/repositories/principals.ts +358 -0
  168. package/src/repositories/sessions.ts +339 -0
  169. package/src/repositories/sql.ts +23 -0
  170. package/src/repositories/terminals.ts +346 -0
  171. package/src/repositories/workloads.ts +134 -0
  172. package/src/request-id.ts +46 -0
  173. package/src/resolve.ts +396 -0
  174. package/src/retention.ts +34 -0
  175. package/src/roles.ts +54 -0
  176. package/src/rpc-http.ts +333 -0
  177. package/src/rpc-inputs.ts +110 -0
  178. package/src/rpc.ts +440 -0
  179. package/src/secret.ts +45 -0
  180. package/src/service.ts +59 -0
  181. package/src/services.ts +199 -0
  182. package/src/signing.ts +260 -0
  183. package/src/stored-chain.ts +23 -0
  184. package/src/stored-permissions.ts +34 -0
  185. package/src/terminals.ts +15 -0
  186. package/src/tokens.ts +506 -0
  187. package/src/workload-token.ts +130 -0
  188. package/types/fabrika.config.d.ts +11 -0
  189. package/types/src/admin/access.d.ts +19 -0
  190. package/types/src/admin/api-keys.d.ts +26 -0
  191. package/types/src/admin/app-people.d.ts +8 -0
  192. package/types/src/admin/app-schema.d.ts +32 -0
  193. package/types/src/admin/audit.d.ts +10 -0
  194. package/types/src/admin/brand.d.ts +10 -0
  195. package/types/src/admin/connections.d.ts +5 -0
  196. package/types/src/admin/context.d.ts +46 -0
  197. package/types/src/admin/grant-support.d.ts +59 -0
  198. package/types/src/admin/grants.d.ts +8 -0
  199. package/types/src/admin/handlers.d.ts +82 -0
  200. package/types/src/admin/http.d.ts +9 -0
  201. package/types/src/admin/membership-keys.d.ts +8 -0
  202. package/types/src/admin/pagination.d.ts +5 -0
  203. package/types/src/admin/password-policy.d.ts +9 -0
  204. package/types/src/admin/passwords.d.ts +5 -0
  205. package/types/src/admin/policies.d.ts +15 -0
  206. package/types/src/admin/principals.d.ts +15 -0
  207. package/types/src/admin/router.d.ts +75 -0
  208. package/types/src/admin/rpc.d.ts +6 -0
  209. package/types/src/admin/sessions.d.ts +14 -0
  210. package/types/src/admin/share-links.d.ts +21 -0
  211. package/types/src/admin/terminals.d.ts +13 -0
  212. package/types/src/admin/user-admin.d.ts +30 -0
  213. package/types/src/admin/workloads.d.ts +5 -0
  214. package/types/src/app-presentation.d.ts +86 -0
  215. package/types/src/app.d.ts +62 -0
  216. package/types/src/auth/cookies.d.ts +29 -0
  217. package/types/src/auth/failure.d.ts +47 -0
  218. package/types/src/auth/handoff.d.ts +66 -0
  219. package/types/src/auth/http.d.ts +29 -0
  220. package/types/src/auth/invitations.d.ts +18 -0
  221. package/types/src/auth/known-device.d.ts +12 -0
  222. package/types/src/auth/login.d.ts +10 -0
  223. package/types/src/auth/oidc-flight.d.ts +39 -0
  224. package/types/src/auth/oidc.d.ts +7 -0
  225. package/types/src/auth/password.d.ts +7 -0
  226. package/types/src/auth/routes.d.ts +15 -0
  227. package/types/src/auth/sessions.d.ts +60 -0
  228. package/types/src/auth/terminals.d.ts +47 -0
  229. package/types/src/auth.d.ts +70 -0
  230. package/types/src/binding-identity.d.ts +12 -0
  231. package/types/src/bounded-body.d.ts +12 -0
  232. package/types/src/catalog/cs.d.ts +2 -0
  233. package/types/src/catalog/en.d.ts +2 -0
  234. package/types/src/catalog/index.d.ts +112 -0
  235. package/types/src/catalog/uk.d.ts +2 -0
  236. package/types/src/client-address.d.ts +31 -0
  237. package/types/src/common-passwords.d.ts +2 -0
  238. package/types/src/contract-rules.d.ts +25 -0
  239. package/types/src/cron.d.ts +15 -0
  240. package/types/src/db.d.ts +58 -0
  241. package/types/src/delegation.d.ts +38 -0
  242. package/types/src/device-http.d.ts +2 -0
  243. package/types/src/device.d.ts +11 -0
  244. package/types/src/email-identity.d.ts +1 -0
  245. package/types/src/env.d.ts +127 -0
  246. package/types/src/handoff.d.ts +57 -0
  247. package/types/src/html.d.ts +2 -0
  248. package/types/src/human-admission.d.ts +22 -0
  249. package/types/src/identification.d.ts +30 -0
  250. package/types/src/index.d.ts +62 -0
  251. package/types/src/installation-brand.d.ts +22 -0
  252. package/types/src/issue.d.ts +62 -0
  253. package/types/src/json.d.ts +15 -0
  254. package/types/src/log.d.ts +15 -0
  255. package/types/src/membership-http.d.ts +8 -0
  256. package/types/src/membership.d.ts +156 -0
  257. package/types/src/messages.d.ts +20 -0
  258. package/types/src/narrow-permissions.d.ts +7 -0
  259. package/types/src/node/browser-identity.d.ts +1 -0
  260. package/types/src/node/migrate.d.ts +4 -0
  261. package/types/src/node/prune.d.ts +1 -0
  262. package/types/src/node/runtime.d.ts +51 -0
  263. package/types/src/node/server.d.ts +5 -0
  264. package/types/src/oauth-client-auth.d.ts +26 -0
  265. package/types/src/oauth-client.d.ts +17 -0
  266. package/types/src/oauth-config.d.ts +16 -0
  267. package/types/src/oauth-http.d.ts +7 -0
  268. package/types/src/oauth.d.ts +51 -0
  269. package/types/src/oidc.d.ts +81 -0
  270. package/types/src/origin.d.ts +9 -0
  271. package/types/src/password-crypto.d.ts +37 -0
  272. package/types/src/password-db.d.ts +134 -0
  273. package/types/src/password-minimum.d.ts +23 -0
  274. package/types/src/password-pages.d.ts +143 -0
  275. package/types/src/password-policy.d.ts +19 -0
  276. package/types/src/password-service.d.ts +24 -0
  277. package/types/src/person-locale.d.ts +50 -0
  278. package/types/src/proxy-proof.d.ts +21 -0
  279. package/types/src/relay-mail.d.ts +25 -0
  280. package/types/src/repositories/app-schema.d.ts +244 -0
  281. package/types/src/repositories/audit.d.ts +187 -0
  282. package/types/src/repositories/brand.d.ts +41 -0
  283. package/types/src/repositories/credentials.d.ts +148 -0
  284. package/types/src/repositories/device.d.ts +50 -0
  285. package/types/src/repositories/grants.d.ts +177 -0
  286. package/types/src/repositories/handoff.d.ts +52 -0
  287. package/types/src/repositories/membership-transport.d.ts +31 -0
  288. package/types/src/repositories/membership.d.ts +273 -0
  289. package/types/src/repositories/oauth.d.ts +55 -0
  290. package/types/src/repositories/password-policy.d.ts +25 -0
  291. package/types/src/repositories/principals.d.ts +159 -0
  292. package/types/src/repositories/sessions.d.ts +150 -0
  293. package/types/src/repositories/sql.d.ts +13 -0
  294. package/types/src/repositories/terminals.d.ts +144 -0
  295. package/types/src/repositories/workloads.d.ts +61 -0
  296. package/types/src/request-id.d.ts +25 -0
  297. package/types/src/resolve.d.ts +118 -0
  298. package/types/src/retention.d.ts +18 -0
  299. package/types/src/roles.d.ts +34 -0
  300. package/types/src/rpc-http.d.ts +53 -0
  301. package/types/src/rpc-inputs.d.ts +707 -0
  302. package/types/src/rpc.d.ts +4 -0
  303. package/types/src/secret.d.ts +21 -0
  304. package/types/src/service.d.ts +19 -0
  305. package/types/src/services.d.ts +72 -0
  306. package/types/src/signing.d.ts +72 -0
  307. package/types/src/stored-chain.d.ts +6 -0
  308. package/types/src/stored-permissions.d.ts +12 -0
  309. package/types/src/terminals.d.ts +7 -0
  310. package/types/src/tokens.d.ts +113 -0
  311. package/types/src/workload-token.d.ts +7 -0
  312. package/README.md +0 -3
@@ -0,0 +1,875 @@
1
+ import type { PrincipalAffiliation, Scope } from '@fabrika/auth-core'
2
+ import { type SqlDatabase, type SqlQueryResult, type SqlStatement, uuidv7 } from '@fabrika/platform'
3
+ import type { StoredPasswordHash } from '../password-crypto'
4
+ import { type AuditEventInput, auditEventStatement, AuditWriter, type SqlChange, type SqlDialect } from './audit'
5
+ import { eligibleGrantBinds, eligibleGrantSql, grantRemovalStatement, type GrantRow } from './grants'
6
+ import type { PrincipalRow } from './principals'
7
+ import { unixNow } from './sql'
8
+
9
+ /** A single-use delegation grant (`delegation_grants`). Only its hash is stored. */
10
+ export interface DelegationGrantRow {
11
+ id: string
12
+ grant_hash: string
13
+ app: string
14
+ principal_id: string
15
+ endpoint: string
16
+ request_id: string
17
+ expires_at: number
18
+ consumed_at: number | null
19
+ created_at: number
20
+ }
21
+
22
+ /** An invitation to a membership role (`membership_invitations`). `email` is the normalized mailbox. */
23
+ export interface InvitationRow {
24
+ id: string
25
+ token_hash: string
26
+ app: string
27
+ scope_type: string
28
+ scope_value: string
29
+ role_key: string
30
+ email: string
31
+ invited_by: string
32
+ expires_at: number
33
+ accepted_at: number | null
34
+ accepted_by: string | null
35
+ acceptance_id: string | null
36
+ revoked_at: number | null
37
+ created_at: number
38
+ /** The invited person's company as the inviting application names it (plain text), or NULL. */
39
+ company_label: string | null
40
+ /** The inviter's personal message (plain text), or NULL. */
41
+ message: string | null
42
+ /** The invited person's language as the inviting application named it, or NULL: the application's then. */
43
+ locale: string | null
44
+ }
45
+
46
+ /** One membership-role grant in a value, with the principal it belongs to and its last sign-in to the app. */
47
+ export interface MemberGrantRow {
48
+ principal_id: string
49
+ role_key: string
50
+ label: string
51
+ email: string | null
52
+ disabled_at: number | null
53
+ affiliation: PrincipalAffiliation
54
+ signed_in_at: number | null
55
+ }
56
+
57
+ /** One role grant at an application, in a value or global, with its principal and its last sign-in there. */
58
+ export interface AppMemberGrantRow extends MemberGrantRow {
59
+ scope_type: string | null
60
+ scope_value: string | null
61
+ }
62
+
63
+ /**
64
+ * The grants that count as holding a role of the application: an active grant of a role row of the app, a membership
65
+ * role only in a value of its own dimension, and an external principal's only of a role declared external, as
66
+ * `computePermissions` counts them.
67
+ */
68
+ const APP_MEMBER_GRANT = `g.app = ? AND (g.expires_at IS NULL OR g.expires_at > ?)
69
+ AND (r.member_scope IS NULL OR r.member_scope = g.scope_type)
70
+ AND (p.affiliation = 'internal' OR r.external = 1)`
71
+
72
+ /**
73
+ * The rows behind the membership operations. Membership itself is ordinary role grants scoped to a value,
74
+ * so a group assignment (backlog 91) can sit next to them later; this repository adds the values IAM
75
+ * created, the single-use delegation grants and the invitations.
76
+ */
77
+ /**
78
+ * The conflict clause of every membership-role grant write. An ACTIVE grant of the role in the value is
79
+ * kept as it is, which makes a repeated assignment answer the same result; an EXPIRED one is renewed in
80
+ * the same statement, so it never reads as held while it grants nothing. A renewal takes the new grant's expiry, which
81
+ * the use case clamped to the authority that gave it (S8).
82
+ */
83
+ const RENEW_EXPIRED_MEMBERSHIP = `ON CONFLICT (principal_id, role_key, scope_type, scope_value, COALESCE(app, '*'))
84
+ WHERE role_key IS NOT NULL AND scope_value IS NOT NULL
85
+ DO UPDATE SET expires_at = excluded.expires_at, granted_by = excluded.granted_by, created_at = excluded.created_at
86
+ WHERE grants.expires_at IS NOT NULL AND grants.expires_at <= ?`
87
+
88
+ /**
89
+ * How an acceptance ended: written; refused because the inviter holds no assigning role there now, or because the
90
+ * accepting principal may not hold the role (ADR-0051); or no longer open.
91
+ */
92
+ /**
93
+ * The grants that make their holder an assigner in the value bound next (type, value): a role grant in exactly that
94
+ * value, or a global grant of an application-wide role, one with no `member_scope` (ADR-0022 rule 6).
95
+ */
96
+ const ASSIGNING_GRANT = `((grants.scope_type = ? AND grants.scope_value = ?)
97
+ OR (grants.scope_type IS NULL AND grants.scope_value IS NULL AND EXISTS (
98
+ SELECT 1 FROM roles WHERE roles.app = grants.app AND roles.role_key = grants.role_key AND roles.member_scope IS NULL)))`
99
+
100
+ export type InvitationAcceptance = 'accepted' | 'not_allowed' | 'not_eligible' | 'not_open'
101
+
102
+ /**
103
+ * How an acceptance that creates its principal ended: accepted with the new principal; refused as `acceptInvitation`
104
+ * refuses; or `account_exists`, because another writer gave the mailbox a principal first, which then signs in and
105
+ * accepts as any existing principal does.
106
+ */
107
+ export type NewPrincipalAcceptance =
108
+ | { readonly outcome: 'accepted'; readonly principal: PrincipalRow }
109
+ | { readonly outcome: Exclude<InvitationAcceptance, 'accepted'> | 'account_exists' }
110
+
111
+ /**
112
+ * What authorized an acceptance, as the use case checked it: the roles that make the inviter an assigner of the
113
+ * invitation's role, the revision of the app's schema and policies (`AppSchemaRepository.getSchemaRevision`) and the
114
+ * inviter's grant revision (`principals.grant_revision`), both read BEFORE that check. The acceptance writes only while
115
+ * both are unchanged, so the declarations and the grants the check read are the ones in force at the write.
116
+ */
117
+ export interface InviterCheck {
118
+ readonly assigners: readonly string[]
119
+ readonly revision: number
120
+ readonly grantRevision: number
121
+ /** The expiry of the grant the acceptance writes: the earliest expiry among the inviter's grants behind it (S8). */
122
+ readonly expiresAt: number | null
123
+ }
124
+
125
+ /** The records of an acceptance that creates its principal, each written exactly when its change was. */
126
+ export interface NewPrincipalEvents {
127
+ readonly principal: AuditEventInput
128
+ readonly acceptance: AuditEventInput
129
+ readonly password: AuditEventInput
130
+ }
131
+
132
+ export interface MembershipRepositoryOptions {
133
+ /**
134
+ * The dialect of `db`. On Postgres an acceptance locks the inviter's assigning grant while it commits (`FOR SHARE`),
135
+ * so a removal of that grant waits for it; SQLite has no row locks, and D1 runs a batch alone, which is atomic
136
+ * already. It also picks how a change writes its record (`AuditWriter`).
137
+ */
138
+ readonly dialect?: SqlDialect
139
+ }
140
+
141
+ export class MembershipRepository {
142
+ /** `FOR SHARE` on Postgres: an acceptance holds the inviter's assigning grant and the role row to its commit. */
143
+ readonly #shareLock: string
144
+ /** `eligibleGrantSql` of the dialect: on Postgres it holds the role row for the transaction. */
145
+ readonly #eligible: string
146
+ protected readonly writer: AuditWriter
147
+
148
+ constructor(
149
+ protected readonly db: SqlDatabase,
150
+ options: MembershipRepositoryOptions = {},
151
+ ) {
152
+ const dialect = options.dialect ?? 'sqlite'
153
+ this.#shareLock = dialect === 'postgres' ? 'FOR SHARE' : ''
154
+ this.#eligible = eligibleGrantSql(dialect)
155
+ this.writer = new AuditWriter(db, dialect)
156
+ }
157
+
158
+ async issueDelegationGrant(input: {
159
+ grantHash: string
160
+ app: string
161
+ principalId: string
162
+ endpoint: string
163
+ requestId: string
164
+ expiresAt: number
165
+ }): Promise<void> {
166
+ await this.db
167
+ .prepare(`INSERT INTO delegation_grants (id, grant_hash, app, principal_id, endpoint, request_id, expires_at, created_at)
168
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
169
+ .bind(uuidv7(), input.grantHash, input.app, input.principalId, input.endpoint, input.requestId, input.expiresAt, unixNow())
170
+ .run()
171
+ }
172
+
173
+ /**
174
+ * Spend a delegation grant, at most once. The UPDATE is the guard, as for `auth_codes`: a second
175
+ * attempt changes no rows. The caller compares the binding AFTER this, so a mismatched attempt spends it too.
176
+ */
177
+ async consumeDelegationGrant(grantHash: string, now: number): Promise<DelegationGrantRow | null> {
178
+ const marked = await this.db
179
+ .prepare('UPDATE delegation_grants SET consumed_at = ? WHERE grant_hash = ? AND consumed_at IS NULL AND expires_at > ?')
180
+ .bind(now, grantHash, now)
181
+ .run()
182
+ if (marked.meta.changes === 0) {
183
+ return null
184
+ }
185
+ return this.db.prepare('SELECT * FROM delegation_grants WHERE grant_hash = ?').bind(grantHash).first<DelegationGrantRow>()
186
+ }
187
+
188
+ /**
189
+ * Record a value IAM generated, grant its creator the creator role, and write `audit`, in one transaction. Both writes
190
+ * carry the eligibility condition (ADR-0051), so a creator who may not hold the role writes nothing: answers false.
191
+ */
192
+ async createScope(
193
+ input: { app: string; scope: Scope; createdBy: string; roleKey: string; expiresAt?: number | null },
194
+ audit?: AuditEventInput,
195
+ ): Promise<boolean> {
196
+ const now = unixNow()
197
+ const eligible = eligibleGrantBinds({ principalId: input.createdBy, app: input.app, roleKey: input.roleKey })
198
+ const created = this.writer.changed([
199
+ {
200
+ sql: `INSERT INTO membership_scopes (app, scope_type, scope_value, created_by, created_at)
201
+ SELECT ?, ?, ?, ?, ? WHERE ${this.#eligible} RETURNING scope_value`,
202
+ binds: [input.app, input.scope.type, input.scope.value, input.createdBy, now, ...eligible],
203
+ },
204
+ {
205
+ sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
206
+ SELECT ?, ?, ?, ?, NULL, ?, ?, ?, ?, ? WHERE ${this.#eligible} RETURNING id`,
207
+ binds: [
208
+ uuidv7(),
209
+ input.createdBy,
210
+ input.app,
211
+ input.roleKey,
212
+ input.scope.type,
213
+ input.scope.value,
214
+ input.createdBy,
215
+ input.expiresAt ?? null,
216
+ now,
217
+ ...eligible,
218
+ ],
219
+ },
220
+ ], audit)
221
+ return created.rows(await this.db.batch(created.statements)).length > 0
222
+ }
223
+
224
+ /** The active role grants a principal holds in exactly `scope` — the roles it holds "there". */
225
+ async listRoleGrantsAt(app: string, principalId: string, scope: Scope): Promise<GrantRow[]> {
226
+ const { results } = await this.db
227
+ .prepare(`SELECT * FROM grants
228
+ WHERE app = ? AND principal_id = ? AND role_key IS NOT NULL AND scope_type = ? AND scope_value = ?
229
+ AND (expires_at IS NULL OR expires_at > ?)
230
+ ORDER BY role_key`)
231
+ .bind(app, principalId, scope.type, scope.value, unixNow())
232
+ .all<GrantRow>()
233
+ return results
234
+ }
235
+
236
+ /** The active role grants that make a principal an assigner in `scope` (`ASSIGNING_GRANT`). */
237
+ async listAssigningGrants(app: string, principalId: string, scope: Scope): Promise<GrantRow[]> {
238
+ const { results } = await this.db
239
+ .prepare(`SELECT * FROM grants
240
+ WHERE app = ? AND principal_id = ? AND role_key IS NOT NULL AND ${ASSIGNING_GRANT}
241
+ AND (expires_at IS NULL OR expires_at > ?)
242
+ ORDER BY role_key`)
243
+ .bind(app, principalId, scope.type, scope.value, unixNow())
244
+ .all<GrantRow>()
245
+ return results
246
+ }
247
+
248
+ /** Every active grant of a membership role of `scope.type` in `scope`, with its principal. */
249
+ async listMemberGrants(app: string, scope: Scope): Promise<MemberGrantRow[]> {
250
+ const { results } = await this.db
251
+ .prepare(`SELECT g.principal_id, g.role_key, p.label, p.email, p.disabled_at, p.affiliation, si.signed_in_at
252
+ FROM grants g
253
+ JOIN principals p ON p.id = g.principal_id
254
+ JOIN roles r ON r.app = g.app AND r.role_key = g.role_key
255
+ LEFT JOIN app_sign_ins si ON si.app = g.app AND si.principal_id = g.principal_id
256
+ WHERE g.app = ? AND g.scope_type = ? AND g.scope_value = ? AND r.member_scope = ?
257
+ AND (g.expires_at IS NULL OR g.expires_at > ?)
258
+ ORDER BY g.principal_id, g.role_key`)
259
+ .bind(app, scope.type, scope.value, scope.type, unixNow())
260
+ .all<MemberGrantRow>()
261
+ return results
262
+ }
263
+
264
+ /** A page of the principals holding a role of `app` (`APP_MEMBER_GRANT`), by id after `after`, at most `limit`. */
265
+ async listAppMemberIds(app: string, after: string | null, limit: number): Promise<string[]> {
266
+ const page = after === null ? '' : 'AND g.principal_id > ?'
267
+ const { results } = await this.db
268
+ .prepare(`SELECT DISTINCT g.principal_id
269
+ FROM grants g
270
+ JOIN principals p ON p.id = g.principal_id
271
+ JOIN roles r ON r.app = g.app AND r.role_key = g.role_key
272
+ WHERE ${APP_MEMBER_GRANT} ${page}
273
+ ORDER BY g.principal_id
274
+ LIMIT ?`)
275
+ .bind(app, unixNow(), ...(after === null ? [] : [after]), limit)
276
+ .all<{ principal_id: string }>()
277
+ return results.map((row) => row.principal_id)
278
+ }
279
+
280
+ /** The grants of `principalIds` that make them people of `app` (`APP_MEMBER_GRANT`), with each principal. */
281
+ async listAppMemberGrants(app: string, principalIds: readonly string[]): Promise<AppMemberGrantRow[]> {
282
+ if (principalIds.length === 0) return []
283
+ const { results } = await this.db
284
+ .prepare(`SELECT g.principal_id, g.role_key, g.scope_type, g.scope_value, p.label, p.email, p.disabled_at, p.affiliation, si.signed_in_at
285
+ FROM grants g
286
+ JOIN principals p ON p.id = g.principal_id
287
+ JOIN roles r ON r.app = g.app AND r.role_key = g.role_key
288
+ LEFT JOIN app_sign_ins si ON si.app = g.app AND si.principal_id = g.principal_id
289
+ WHERE ${APP_MEMBER_GRANT} AND g.principal_id IN (${principalIds.map(() => '?').join(', ')})
290
+ ORDER BY g.principal_id, g.role_key`)
291
+ .bind(app, unixNow(), ...principalIds)
292
+ .all<AppMemberGrantRow>()
293
+ return results
294
+ }
295
+
296
+ /** Every active grant of a membership role of `scope.type` in `scope` held by `principalId`, with the principal. */
297
+ async listMemberGrantsOf(app: string, scope: Scope, principalId: string): Promise<MemberGrantRow[]> {
298
+ const { results } = await this.db
299
+ .prepare(`SELECT g.principal_id, g.role_key, p.label, p.email, p.disabled_at, p.affiliation, si.signed_in_at
300
+ FROM grants g
301
+ JOIN principals p ON p.id = g.principal_id
302
+ JOIN roles r ON r.app = g.app AND r.role_key = g.role_key
303
+ LEFT JOIN app_sign_ins si ON si.app = g.app AND si.principal_id = g.principal_id
304
+ WHERE g.app = ? AND g.scope_type = ? AND g.scope_value = ? AND r.member_scope = ? AND g.principal_id = ?
305
+ AND (g.expires_at IS NULL OR g.expires_at > ?)
306
+ ORDER BY g.role_key`)
307
+ .bind(app, scope.type, scope.value, scope.type, principalId, unixNow())
308
+ .all<MemberGrantRow>()
309
+ return results
310
+ }
311
+
312
+ /**
313
+ * Grant a membership role in `scope`. Returns the row when this call granted or renewed it, null when it was held or
314
+ * the principal may not hold it (ADR-0051: the insert carries the condition); `audit` is written exactly then.
315
+ */
316
+ async grantMembershipRole(
317
+ input: { app: string; principalId: string; roleKey: string; scope: Scope; grantedBy: string; expiresAt?: number | null },
318
+ audit?: AuditEventInput,
319
+ ): Promise<GrantRow | null> {
320
+ const now = unixNow()
321
+ const grant: SqlChange = {
322
+ sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
323
+ SELECT ?, ?, ?, ?, NULL, ?, ?, ?, ?, ? WHERE ${this.#eligible} ${RENEW_EXPIRED_MEMBERSHIP} RETURNING *`,
324
+ binds: [
325
+ uuidv7(),
326
+ input.principalId,
327
+ input.app,
328
+ input.roleKey,
329
+ input.scope.type,
330
+ input.scope.value,
331
+ input.grantedBy,
332
+ input.expiresAt ?? null,
333
+ now,
334
+ ...eligibleGrantBinds(input),
335
+ now,
336
+ ],
337
+ }
338
+ const [granted] = await this.writer.run<GrantRow>([grant], audit)
339
+ return granted ?? null
340
+ }
341
+
342
+ /** Remove one role grant of a principal in `scope`, after its grant revision (`grantRemovalStatement`). Returns whether a row went. */
343
+ async deleteRoleGrant(app: string, principalId: string, roleKey: string, scope: Scope): Promise<boolean> {
344
+ const [, deleted] = await this.db.batch<{ id: string }>([
345
+ grantRemovalStatement(this.db, { principalId }),
346
+ this.db
347
+ .prepare('DELETE FROM grants WHERE app = ? AND principal_id = ? AND role_key = ? AND scope_type = ? AND scope_value = ? RETURNING id')
348
+ .bind(app, principalId, roleKey, scope.type, scope.value),
349
+ ])
350
+ return (deleted?.results.length ?? 0) > 0
351
+ }
352
+
353
+ /**
354
+ * Remove a principal's creator-role grant in `scope` only while another principal still holds the role
355
+ * there. The value's `membership_scopes` row is the lock: created on demand, because an administrator
356
+ * may have granted the role without `createScope`, then taken with a row-locking UPDATE — the one lock
357
+ * statement SQLite and Postgres share; D1 runs a batch serially anyway. Two revokes of the last two
358
+ * holders therefore run one after the other, and the second sees the first's delete. The principal's
359
+ * grant revision moves first (`grantRemovalStatement`), so its row is locked before the value's.
360
+ */
361
+ async deleteCreatorGrantUnlessLast(app: string, principalId: string, roleKey: string, scope: Scope): Promise<boolean> {
362
+ const remove = this.deleteCreatorChange(app, principalId, roleKey, scope, unixNow())
363
+ const [, , , deleted] = await this.db.batch<{ role_key: string }>([
364
+ grantRemovalStatement(this.db, { principalId }),
365
+ ...this.scopeLockStatements(app, scope),
366
+ this.db.prepare(remove.sql).bind(...remove.binds),
367
+ ])
368
+ return (deleted?.results.length ?? 0) > 0
369
+ }
370
+
371
+ /**
372
+ * Remove a member's roles in `scope`, in one transaction under the value's lock (`deleteCreatorGrantUnlessLast`),
373
+ * writing one `audit` row per role this call removed, decided by each DELETE itself. The creator role goes only
374
+ * while another principal holds it, and while the member still holds it no other role goes either, so a refused
375
+ * creator leaves every role in place. Answers the roles removed.
376
+ */
377
+ async revokeMemberRoles(
378
+ input: { app: string; principalId: string; scope: Scope; roles: readonly string[]; creatorRole: string | null },
379
+ audit: (roleKey: string) => AuditEventInput,
380
+ ): Promise<string[]> {
381
+ const { app, principalId, scope } = input
382
+ const now = unixNow()
383
+ const creator = input.creatorRole !== null && input.roles.includes(input.creatorRole) ? input.creatorRole : null
384
+ const groups = [
385
+ ...(creator === null ? [] : [this.writer.changed([this.deleteCreatorChange(app, principalId, creator, scope, now)], audit(creator))]),
386
+ ...input.roles.filter((roleKey) => roleKey !== creator).map((roleKey) => {
387
+ // While the member still holds an active creator grant here, no other role of it goes.
388
+ const creatorHeld = creator === null ? '' : `AND NOT EXISTS (SELECT 1 FROM grants
389
+ WHERE app = ? AND principal_id = ? AND role_key = ? AND scope_type = ? AND scope_value = ?
390
+ AND (expires_at IS NULL OR expires_at > ?))`
391
+ const remove: SqlChange = {
392
+ sql: `DELETE FROM grants WHERE app = ? AND principal_id = ? AND role_key = ? AND scope_type = ? AND scope_value = ?
393
+ ${creatorHeld} RETURNING role_key`,
394
+ binds: [
395
+ app,
396
+ principalId,
397
+ roleKey,
398
+ scope.type,
399
+ scope.value,
400
+ ...(creator === null ? [] : [app, principalId, creator, scope.type, scope.value, now]),
401
+ ],
402
+ }
403
+ return this.writer.changed([remove], audit(roleKey))
404
+ }),
405
+ ]
406
+ const lock = [grantRemovalStatement(this.db, { principalId }), ...this.scopeLockStatements(app, scope)]
407
+ const results = await this.db.batch<{ role_key: string }>([...lock, ...groups.flatMap((group) => group.statements)])
408
+ let offset = lock.length
409
+ const removed: string[] = []
410
+ for (const group of groups) {
411
+ removed.push(...group.rows(results, offset).map((row) => row.role_key))
412
+ offset += group.statements.length
413
+ }
414
+ return removed
415
+ }
416
+
417
+ /** Create the value's `membership_scopes` row on demand and lock it; see `deleteCreatorGrantUnlessLast`. */
418
+ private scopeLockStatements(app: string, scope: Scope): SqlStatement[] {
419
+ return [
420
+ this.db
421
+ .prepare(`INSERT INTO membership_scopes (app, scope_type, scope_value, created_by, created_at) VALUES (?, ?, ?, NULL, ?)
422
+ ON CONFLICT (app, scope_type, scope_value) DO NOTHING`)
423
+ .bind(app, scope.type, scope.value, unixNow()),
424
+ this.db
425
+ .prepare('UPDATE membership_scopes SET created_at = created_at WHERE app = ? AND scope_type = ? AND scope_value = ?')
426
+ .bind(app, scope.type, scope.value),
427
+ ]
428
+ }
429
+
430
+ /** The DELETE of a principal's creator grant in `scope`, only while another principal holds the role there. */
431
+ private deleteCreatorChange(app: string, principalId: string, roleKey: string, scope: Scope, now: number): SqlChange {
432
+ return {
433
+ sql: `DELETE FROM grants
434
+ WHERE app = ? AND principal_id = ? AND role_key = ? AND scope_type = ? AND scope_value = ?
435
+ AND EXISTS (
436
+ SELECT 1 FROM grants other
437
+ WHERE other.app = ? AND other.role_key = ? AND other.scope_type = ? AND other.scope_value = ?
438
+ AND other.principal_id <> ? AND (other.expires_at IS NULL OR other.expires_at > ?))
439
+ RETURNING role_key`,
440
+ binds: [app, principalId, roleKey, scope.type, scope.value, app, roleKey, scope.type, scope.value, principalId, now],
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Open an invitation, or answer the open one for the same value, role and mailbox. An expired open
446
+ * invitation is closed first, so it never blocks a new one. `audit` is written exactly when this call opened one.
447
+ */
448
+ async openInvitation(input: {
449
+ tokenHash: string
450
+ app: string
451
+ scope: Scope
452
+ roleKey: string
453
+ email: string
454
+ invitedBy: string
455
+ expiresAt: number
456
+ companyLabel?: string | null
457
+ message?: string | null
458
+ locale?: string | null
459
+ }, audit?: (invitationId: string) => AuditEventInput): Promise<{ invitation: InvitationRow; created: boolean }> {
460
+ const now = unixNow()
461
+ const id = uuidv7()
462
+ const key = [input.app, input.scope.type, input.scope.value, input.roleKey, input.email]
463
+ const opened = this.writer.changed([{
464
+ sql: `INSERT INTO membership_invitations
465
+ (id, token_hash, app, scope_type, scope_value, role_key, email, invited_by, expires_at, created_at, company_label, message, locale)
466
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
467
+ ON CONFLICT (app, scope_type, scope_value, role_key, email) WHERE accepted_at IS NULL AND revoked_at IS NULL DO NOTHING
468
+ RETURNING *`,
469
+ binds: [
470
+ id,
471
+ input.tokenHash,
472
+ ...key,
473
+ input.invitedBy,
474
+ input.expiresAt,
475
+ now,
476
+ input.companyLabel ?? null,
477
+ input.message ?? null,
478
+ input.locale ?? null,
479
+ ],
480
+ }], audit?.(id))
481
+ const results = await this.db.batch<InvitationRow>([
482
+ this.db
483
+ .prepare(`UPDATE membership_invitations SET revoked_at = ?
484
+ WHERE app = ? AND scope_type = ? AND scope_value = ? AND role_key = ? AND email = ?
485
+ AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at <= ?`)
486
+ .bind(now, ...key, now),
487
+ ...opened.statements,
488
+ ])
489
+ const created = opened.rows(results, 1)[0] ?? null
490
+ if (created !== null) {
491
+ return { invitation: created, created: true }
492
+ }
493
+ const open = await this.db
494
+ .prepare(`SELECT * FROM membership_invitations
495
+ WHERE app = ? AND scope_type = ? AND scope_value = ? AND role_key = ? AND email = ? AND accepted_at IS NULL AND revoked_at IS NULL`)
496
+ .bind(...key)
497
+ .first<InvitationRow>()
498
+ if (open === null) {
499
+ throw new Error('an open invitation conflicted and then vanished')
500
+ }
501
+ return { invitation: open, created: false }
502
+ }
503
+
504
+ /**
505
+ * Give an open invitation a new link and a new lifetime (a resend): the old token's hash is replaced, so its link
506
+ * stops working. A label, message or locale the call names replaces the stored one; NULL keeps it. Answers the
507
+ * invitation when it was still open, and `audit` is written exactly then.
508
+ */
509
+ async rotateInvitation(
510
+ input: { id: string; tokenHash: string; expiresAt: number; companyLabel: string | null; message: string | null; locale: string | null },
511
+ audit?: AuditEventInput,
512
+ ): Promise<InvitationRow | null> {
513
+ const now = unixNow()
514
+ const rotate: SqlChange = {
515
+ sql: `UPDATE membership_invitations
516
+ SET token_hash = ?, expires_at = ?, company_label = COALESCE(?, company_label), message = COALESCE(?, message),
517
+ locale = COALESCE(?, locale)
518
+ WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
519
+ RETURNING *`,
520
+ binds: [input.tokenHash, input.expiresAt, input.companyLabel, input.message, input.locale, input.id, now],
521
+ }
522
+ const [rotated] = await this.writer.run<InvitationRow>([rotate], audit)
523
+ return rotated ?? null
524
+ }
525
+
526
+ async getInvitationByHash(tokenHash: string): Promise<InvitationRow | null> {
527
+ return this.db.prepare('SELECT * FROM membership_invitations WHERE token_hash = ?').bind(tokenHash).first<InvitationRow>()
528
+ }
529
+
530
+ async getInvitationById(id: string): Promise<InvitationRow | null> {
531
+ return this.db.prepare('SELECT * FROM membership_invitations WHERE id = ?').bind(id).first<InvitationRow>()
532
+ }
533
+
534
+ /** Remove an invitation whose email could not be delivered, so a retry opens a fresh one; `audit` records the removal. */
535
+ async deleteInvitation(id: string, audit?: AuditEventInput): Promise<void> {
536
+ const remove = this.db.prepare('DELETE FROM membership_invitations WHERE id = ?').bind(id)
537
+ await this.db.batch(audit === undefined ? [remove] : [remove, auditEventStatement(this.db, audit)])
538
+ }
539
+
540
+ /** Close an open invitation. Answers whether it was still open; `audit` is written exactly then. */
541
+ async revokeInvitation(id: string, audit?: AuditEventInput): Promise<boolean> {
542
+ const revoke: SqlChange = {
543
+ sql: 'UPDATE membership_invitations SET revoked_at = ? WHERE id = ? AND accepted_at IS NULL AND revoked_at IS NULL RETURNING id',
544
+ binds: [unixNow(), id],
545
+ }
546
+ return (await this.writer.run([revoke], audit)).length > 0
547
+ }
548
+
549
+ /**
550
+ * Accept an invitation for `principalId` and write its grant, in one transaction. The guarded UPDATE
551
+ * stamps a fresh acceptance id on the invitation only when it is still open under this token AND the authority the
552
+ * use case checked still holds (`checkedAuthority`): the inviter enabled, the app's schema revision unchanged, and
553
+ * one of the assigners held in the value or, an application-wide role, globally (`ASSIGNING_GRANT`). The re-check
554
+ * is part of the statement that consumes the invitation, so a removal or disable of the inviter, or a reconcile,
555
+ * cannot land between a check and the write. The grant is written
556
+ * only for the attempt holding that id — never on the strength of a timestamp another attempt can share.
557
+ * An expired grant of the role is renewed; an active one is left as it is. A refused acceptance leaves the
558
+ * invitation open. `audit` is written only for the attempt holding the acceptance id, in the same batch.
559
+ */
560
+ async acceptInvitation(
561
+ invitation: InvitationRow,
562
+ principalId: string,
563
+ inviter: InviterCheck,
564
+ audit?: AuditEventInput,
565
+ ): Promise<InvitationAcceptance> {
566
+ if (inviter.assigners.length === 0) {
567
+ return 'not_allowed'
568
+ }
569
+ const now = unixNow()
570
+ const acceptanceId = uuidv7()
571
+ const authority = this.checkedAuthority(invitation, inviter, now)
572
+ const accept = this.writer.changed([{
573
+ sql: `UPDATE membership_invitations SET accepted_at = ?, accepted_by = ?, acceptance_id = ?
574
+ WHERE id = ? AND token_hash = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
575
+ AND ${authority.sql}
576
+ AND ${this.#eligible}
577
+ RETURNING id`,
578
+ binds: [
579
+ now,
580
+ principalId,
581
+ acceptanceId,
582
+ invitation.id,
583
+ invitation.token_hash,
584
+ now,
585
+ ...authority.binds,
586
+ ...eligibleGrantBinds({ principalId, app: invitation.app, roleKey: invitation.role_key }),
587
+ ],
588
+ }], audit)
589
+ const statements = [
590
+ ...authority.locks,
591
+ ...accept.statements,
592
+ this.db
593
+ .prepare(`INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
594
+ SELECT ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?
595
+ WHERE EXISTS (SELECT 1 FROM membership_invitations WHERE id = ? AND acceptance_id = ?) AND ${this.#eligible}
596
+ ${RENEW_EXPIRED_MEMBERSHIP}`)
597
+ .bind(
598
+ uuidv7(),
599
+ principalId,
600
+ invitation.app,
601
+ invitation.role_key,
602
+ invitation.scope_type,
603
+ invitation.scope_value,
604
+ invitation.invited_by,
605
+ inviter.expiresAt,
606
+ now,
607
+ invitation.id,
608
+ acceptanceId,
609
+ ...eligibleGrantBinds({ principalId, app: invitation.app, roleKey: invitation.role_key }),
610
+ now,
611
+ ),
612
+ // The acceptance holds the grant it promised or does not happen: this NOT NULL violation rolls the batch back,
613
+ // invitation and record included, when the attempt holding the acceptance id has no active grant of the role.
614
+ this.db
615
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL
616
+ WHERE EXISTS (SELECT 1 FROM membership_invitations WHERE id = ? AND acceptance_id = ?)
617
+ AND NOT EXISTS (
618
+ SELECT 1 FROM grants
619
+ WHERE principal_id = ? AND app = ? AND role_key = ? AND scope_type = ? AND scope_value = ?
620
+ AND (expires_at IS NULL OR expires_at > ?))`)
621
+ .bind(
622
+ `${invitation.app}#acceptance-without-grant`,
623
+ invitation.id,
624
+ acceptanceId,
625
+ principalId,
626
+ invitation.app,
627
+ invitation.role_key,
628
+ invitation.scope_type,
629
+ invitation.scope_value,
630
+ now,
631
+ ),
632
+ ]
633
+ let accepted: boolean
634
+ try {
635
+ accepted = accept.rows(await this.db.batch<{ id: string }>(statements), authority.locks.length).length > 0
636
+ } catch (cause) {
637
+ if (await this.ineligible(invitation, principalId)) return 'not_eligible'
638
+ throw cause
639
+ }
640
+ if (accepted) {
641
+ return 'accepted'
642
+ }
643
+ const current = await this.getInvitationById(invitation.id)
644
+ const open = current !== null && current.accepted_at === null && current.revoked_at === null && current.expires_at > now
645
+ if (!open) return 'not_open'
646
+ return (await this.ineligible(invitation, principalId)) ? 'not_eligible' : 'not_allowed'
647
+ }
648
+
649
+ /**
650
+ * Accept an invitation to a role declared external for a mailbox no principal holds, creating its principal, in ONE
651
+ * transaction: an `external` user labelled with the invited address, active, with its mailbox claimed; the
652
+ * acceptance and its grant as `acceptInvitation` writes them; an enabled password account holding `password`; and the
653
+ * three records. After the inviter's locks (`checkedAuthority`), the new principal's row is the first of its rows
654
+ * written, as every writer of a principal's rows starts at it (`principalLockStatements`); nobody else sees it before
655
+ * the commit.
656
+ *
657
+ * The principal is inserted only while the invitation is open under this token, the checked authority holds
658
+ * (`checkedAuthority`: the inviter enabled, the schema revision unchanged, its assigning grant `FOR SHARE`) and the
659
+ * role is still external (`FOR SHARE`), so a refusal writes nothing. The acceptance repeats the authority and
660
+ * eligibility conditions, and a guard rolls the whole batch back if a change in between (the invitation cancelled or
661
+ * rotated) left the principal without its grant. A mailbox another writer claimed first fails the principal's unique
662
+ * mailbox, which rolls the batch back: `account_exists`.
663
+ */
664
+ async acceptAsNewPrincipal(
665
+ input: { readonly invitation: InvitationRow; readonly inviter: InviterCheck; readonly password: StoredPasswordHash },
666
+ events: (principalId: string) => NewPrincipalEvents,
667
+ ): Promise<NewPrincipalAcceptance> {
668
+ const { invitation, password } = input
669
+ if (input.inviter.assigners.length === 0) {
670
+ return { outcome: 'not_allowed' }
671
+ }
672
+ const now = unixNow()
673
+ const principalId = uuidv7()
674
+ const acceptanceId = uuidv7()
675
+ const recorded = events(principalId)
676
+ const authority = this.checkedAuthority(invitation, input.inviter, now)
677
+ const inviter = authority.sql
678
+ const inviterBinds = authority.binds
679
+ const eligible = eligibleGrantBinds({ principalId, app: invitation.app, roleKey: invitation.role_key })
680
+ const accepted = `EXISTS (SELECT 1 FROM membership_invitations WHERE id = ? AND acceptance_id = ?)`
681
+ const create = this.writer.changed([{
682
+ sql: `INSERT INTO principals (id, type, external_id, email, label, activated_at, created_at, affiliation, locale)
683
+ SELECT ?, 'user', NULL, ?, ?, ?, ?, 'external', ?
684
+ WHERE EXISTS (
685
+ SELECT 1 FROM membership_invitations
686
+ WHERE id = ? AND token_hash = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?)
687
+ AND ${inviter}
688
+ AND EXISTS (SELECT 1 FROM roles WHERE app = ? AND role_key = ? AND external = 1 ${this.#shareLock})
689
+ RETURNING id`,
690
+ binds: [
691
+ principalId,
692
+ invitation.email,
693
+ invitation.email,
694
+ now,
695
+ now,
696
+ invitation.locale,
697
+ invitation.id,
698
+ invitation.token_hash,
699
+ now,
700
+ ...inviterBinds,
701
+ invitation.app,
702
+ invitation.role_key,
703
+ ],
704
+ }], recorded.principal)
705
+ const claim = this.db
706
+ .prepare('INSERT INTO principal_email_claims (normalized_email, principal_id) SELECT email, id FROM principals WHERE id = ?')
707
+ .bind(principalId)
708
+ const accept = this.writer.changed([{
709
+ sql: `UPDATE membership_invitations SET accepted_at = ?, accepted_by = ?, acceptance_id = ?
710
+ WHERE id = ? AND token_hash = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
711
+ AND EXISTS (SELECT 1 FROM principals WHERE id = ?)
712
+ AND ${inviter}
713
+ AND ${this.#eligible}
714
+ RETURNING id`,
715
+ binds: [now, principalId, acceptanceId, invitation.id, invitation.token_hash, now, principalId, ...inviterBinds, ...eligible],
716
+ }], recorded.acceptance)
717
+ const grant = this.db
718
+ .prepare(`INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
719
+ SELECT ?, ?, ?, ?, NULL, ?, ?, ?, ?, ? WHERE ${accepted} AND ${this.#eligible}`)
720
+ .bind(
721
+ uuidv7(),
722
+ principalId,
723
+ invitation.app,
724
+ invitation.role_key,
725
+ invitation.scope_type,
726
+ invitation.scope_value,
727
+ invitation.invited_by,
728
+ input.inviter.expiresAt,
729
+ now,
730
+ invitation.id,
731
+ acceptanceId,
732
+ ...eligible,
733
+ )
734
+ const account = this.db
735
+ .prepare(`INSERT INTO password_accounts (principal_id, state, created_at, updated_at) SELECT ?, 'enabled', ?, ? WHERE ${accepted}`)
736
+ .bind(principalId, now, now, invitation.id, acceptanceId)
737
+ const credential = this.writer.changed([{
738
+ sql: `INSERT INTO password_credentials (principal_id, algorithm, parameters, salt, password_hash, created_at, updated_at)
739
+ SELECT ?, ?, ?, ?, ?, ?, ? WHERE ${accepted}
740
+ RETURNING principal_id`,
741
+ binds: [principalId, password.algorithm, password.parameters, password.salt, password.passwordHash, now, now, invitation.id, acceptanceId],
742
+ }], recorded.password)
743
+ // No principal without the grant it was created for: this NOT NULL violation rolls the batch back, principal included.
744
+ const guard = this.db
745
+ .prepare(`INSERT INTO contract_apps (app, created_at) SELECT ?, NULL
746
+ WHERE EXISTS (SELECT 1 FROM principals WHERE id = ?)
747
+ AND NOT EXISTS (
748
+ SELECT 1 FROM grants
749
+ WHERE principal_id = ? AND app = ? AND role_key = ? AND scope_type = ? AND scope_value = ?)`)
750
+ .bind(
751
+ `${invitation.app}#principal-without-grant`,
752
+ principalId,
753
+ principalId,
754
+ invitation.app,
755
+ invitation.role_key,
756
+ invitation.scope_type,
757
+ invitation.scope_value,
758
+ )
759
+ const statements = [...authority.locks, ...create.statements, claim, ...accept.statements, grant, account, ...credential.statements, guard]
760
+ let results: SqlQueryResult<{ id: string }>[]
761
+ try {
762
+ results = await this.db.batch<{ id: string }>(statements)
763
+ } catch (cause) {
764
+ if (await this.mailboxHeld(invitation.email)) return { outcome: 'account_exists' }
765
+ const refused = await this.newPrincipalRefusal(invitation)
766
+ if (refused !== null) return { outcome: refused }
767
+ throw cause
768
+ }
769
+ if (accept.rows(results, authority.locks.length + create.statements.length + 1).length === 0) {
770
+ if (await this.mailboxHeld(invitation.email)) return { outcome: 'account_exists' }
771
+ return { outcome: (await this.newPrincipalRefusal(invitation)) ?? 'not_allowed' }
772
+ }
773
+ const principal = await this.db.prepare('SELECT * FROM principals WHERE id = ?').bind(principalId).first<PrincipalRow>()
774
+ if (principal === null) {
775
+ throw new Error('an accepted invitation created no principal')
776
+ }
777
+ return { outcome: 'accepted', principal }
778
+ }
779
+
780
+ /** Whether a user principal holds `mailbox`, a normalized address. */
781
+ private async mailboxHeld(mailbox: string): Promise<boolean> {
782
+ return (await this.db.prepare(`SELECT id FROM principals WHERE type = 'user' AND email = ?`).bind(mailbox).first()) !== null
783
+ }
784
+
785
+ /** Why an acceptance that would create its principal wrote nothing: the invitation closed, or its role is no longer external. */
786
+ private async newPrincipalRefusal(invitation: InvitationRow): Promise<'not_open' | 'not_eligible' | null> {
787
+ const current = await this.getInvitationById(invitation.id)
788
+ const open = current !== null && current.token_hash === invitation.token_hash && current.accepted_at === null
789
+ && current.revoked_at === null && current.expires_at > unixNow()
790
+ if (!open) return 'not_open'
791
+ const external = await this.db
792
+ .prepare('SELECT 1 AS external FROM roles WHERE app = ? AND role_key = ? AND external = 1')
793
+ .bind(invitation.app, invitation.role_key)
794
+ .first()
795
+ return external === null ? 'not_eligible' : null
796
+ }
797
+
798
+ /**
799
+ * What an acceptance's writes require of the authority `inviter` checked: the inviter is still enabled and its grant
800
+ * revision unchanged (no grant of it was removed, the one that supplied an action of the role included), the app's
801
+ * schema revision is still the one read before the check, and the inviter still holds one of the assigners in the
802
+ * value, or an application-wide one globally (`ASSIGNING_GRANT`).
803
+ *
804
+ * On Postgres `locks` come first in the batch, in the principal-first order: the inviter's principal row `FOR SHARE`
805
+ * (a disable or a grant removal waits for the acceptance, or the acceptance reads the committed change), then the revision row
806
+ * `FOR SHARE` (a reconcile's increment, its first statement, waits, or the acceptance reads the new revision), and
807
+ * only then do the writes' conditions lock the assigning grant and the role row. SQLite and D1 run one writer at a
808
+ * time and need none.
809
+ */
810
+ private checkedAuthority(
811
+ invitation: InvitationRow,
812
+ inviter: InviterCheck,
813
+ now: number,
814
+ ): { readonly locks: SqlStatement[]; readonly sql: string; readonly binds: (string | number)[] } {
815
+ const locks = this.#shareLock === ''
816
+ ? []
817
+ : [
818
+ this.db.prepare(`SELECT id FROM principals WHERE id = ? ${this.#shareLock}`).bind(invitation.invited_by),
819
+ this.db.prepare(`SELECT revision FROM app_schema_revisions WHERE app = ? ${this.#shareLock}`).bind(invitation.app),
820
+ ]
821
+ const sql = `EXISTS (SELECT 1 FROM principals WHERE id = ? AND disabled_at IS NULL AND grant_revision = ?)
822
+ AND COALESCE((SELECT revision FROM app_schema_revisions WHERE app = ?), 0) = ?
823
+ AND EXISTS (
824
+ SELECT 1 FROM grants
825
+ WHERE app = ? AND principal_id = ? AND ${ASSIGNING_GRANT} AND role_key IN (${inviter.assigners.map(() => '?').join(', ')})
826
+ AND (expires_at IS NULL OR expires_at > ?)
827
+ ${this.#shareLock})`
828
+ const binds = [
829
+ invitation.invited_by,
830
+ inviter.grantRevision,
831
+ invitation.app,
832
+ inviter.revision,
833
+ invitation.app,
834
+ invitation.invited_by,
835
+ invitation.scope_type,
836
+ invitation.scope_value,
837
+ ...inviter.assigners,
838
+ now,
839
+ ]
840
+ return { locks, sql, binds }
841
+ }
842
+
843
+ /** Whether `principalId` may not hold the invitation's role now (ADR-0051). */
844
+ private async ineligible(invitation: InvitationRow, principalId: string): Promise<boolean> {
845
+ const eligible = await this.db
846
+ .prepare(`SELECT 1 AS eligible WHERE ${eligibleGrantSql('sqlite')}`)
847
+ .bind(...eligibleGrantBinds({ principalId, app: invitation.app, roleKey: invitation.role_key }))
848
+ .first()
849
+ return eligible === null
850
+ }
851
+
852
+ /** Open, unexpired invitations to `scope`. */
853
+ async listOpenInvitations(app: string, scope: Scope): Promise<InvitationRow[]> {
854
+ const { results } = await this.db
855
+ .prepare(`SELECT * FROM membership_invitations
856
+ WHERE app = ? AND scope_type = ? AND scope_value = ? AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > ?
857
+ ORDER BY id`)
858
+ .bind(app, scope.type, scope.value, unixNow())
859
+ .all<InvitationRow>()
860
+ return results
861
+ }
862
+
863
+ /**
864
+ * Prune spent and expired delegation grants, and invitations whose expiry is older than
865
+ * `invitationCutoff` whatever their state (the audit log keeps the history). Returns rows removed.
866
+ */
867
+ async prune(now: number, invitationCutoff: number): Promise<number> {
868
+ const grants = await this.db
869
+ .prepare('DELETE FROM delegation_grants WHERE expires_at <= ? OR consumed_at IS NOT NULL')
870
+ .bind(now)
871
+ .run()
872
+ const invitations = await this.db.prepare('DELETE FROM membership_invitations WHERE expires_at < ?').bind(invitationCutoff).run()
873
+ return grants.meta.changes + invitations.meta.changes
874
+ }
875
+ }