@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,404 @@
1
+ import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
2
+ import { type AuditEventInput, AuditWriter, type SqlChange, type SqlDialect } from './audit'
3
+ import { unixNow } from './sql'
4
+
5
+ /** A grant written for a workload principal: its authority is its declared actions, never a grant. */
6
+ export class WorkloadGrantError extends Error {
7
+ override readonly name = 'WorkloadGrantError'
8
+ constructor() {
9
+ super('a workload principal holds no grant')
10
+ }
11
+ }
12
+
13
+ /** A grant an external principal may not hold: its authority is only roles its application declares external. */
14
+ export class ExternalGrantError extends Error {
15
+ override readonly name = 'ExternalGrantError'
16
+ constructor() {
17
+ super('an external principal holds only a role its application declares external')
18
+ }
19
+ }
20
+
21
+ /**
22
+ * The condition every grant write carries (ADR-0051): the principal is internal, or the grant names a role of its app
23
+ * declared external. Binds the principal id, the app and the role key; a null app or role key never matches a role, so
24
+ * an inline, cross-app or built-in grant is refused for an external principal.
25
+ *
26
+ * On Postgres the role row is read `FOR SHARE`, and held to the end of the write's transaction. A reconcile deletes and
27
+ * rewrites every role row of the app, so it waits for a grant write already holding the row, and its batch guard then
28
+ * sees the committed grant; a grant write that comes second waits for the reconcile, and the lock's re-check of the
29
+ * latest row version (the old row is gone) makes it write nothing. SQLite and D1 run one writer at a time.
30
+ */
31
+ export function eligibleGrantSql(dialect: SqlDialect): string {
32
+ const lock = dialect === 'postgres' ? ' FOR SHARE' : ''
33
+ return `(NOT EXISTS (SELECT 1 FROM principals ep WHERE ep.id = ? AND ep.affiliation = 'external')
34
+ OR EXISTS (SELECT 1 FROM roles er WHERE er.app = ? AND er.role_key = ? AND er.external = 1${lock}))`
35
+ }
36
+
37
+ /**
38
+ * The first statement of every transaction that removes a grant of a principal: it moves the principal's grant revision
39
+ * on and, on Postgres, takes the principal row first, as every writer of a principal's rows starts. An acceptance
40
+ * writes only while its inviter's revision is the one read before its check of the inviter's live permissions
41
+ * (`InviterCheck`), so a removal of any of its grants between the check and the write is seen.
42
+ */
43
+ export function grantRemovalStatement(db: SqlDatabase, target: { principalId: string } | { grantId: string }): SqlStatement {
44
+ return 'principalId' in target
45
+ ? db.prepare('UPDATE principals SET grant_revision = grant_revision + 1 WHERE id = ?').bind(target.principalId)
46
+ : db.prepare('UPDATE principals SET grant_revision = grant_revision + 1 WHERE id = (SELECT principal_id FROM grants WHERE id = ?)')
47
+ .bind(target.grantId)
48
+ }
49
+
50
+ export function eligibleGrantBinds(input: { principalId: string; app?: string | null; roleKey?: string | null }): (string | null)[] {
51
+ return [input.principalId, input.app ?? null, input.roleKey ?? null]
52
+ }
53
+
54
+ /**
55
+ * What authorized a delegated grant change (ADR-0022 rule 6), read BEFORE its check: the administrator's grant revision
56
+ * (`principals.grant_revision`) and the app's schema revision (`AppSchemaRepository.getSchemaRevision`). The change
57
+ * writes only while the administrator is enabled and both are unchanged, so the grants and declarations the check read
58
+ * are the ones in force at the write.
59
+ */
60
+ export interface DelegatedAuthority {
61
+ readonly administratorId: string
62
+ readonly app: string
63
+ readonly grantRevision: number
64
+ readonly schemaRevision: number
65
+ }
66
+
67
+ export interface GrantRow {
68
+ id: string
69
+ principal_id: string
70
+ /** Registered app id this grant applies to; NULL = all apps (cross-app). */
71
+ app: string | null
72
+ /** Named role/policy key; XOR `permissions`. Exactly one is non-null. */
73
+ role_key: string | null
74
+ /** Inline action-pattern set (JSON array); XOR `role_key`. Exactly one is non-null. */
75
+ permissions: string | null
76
+ /** Scope dimension; NULL = global (both scope columns rise/fall together). */
77
+ scope_type: string | null
78
+ /** Opaque, app-owned scope value; NULL = global. */
79
+ scope_value: string | null
80
+ granted_by: string | null
81
+ expires_at: number | null
82
+ created_at: number
83
+ }
84
+
85
+ export interface CreateGrantInput {
86
+ principalId: string
87
+ app?: string | null
88
+ roleKey?: string | null
89
+ permissions?: string[] | null
90
+ scopeType?: string | null
91
+ scopeValue?: string | null
92
+ grantedBy?: string | null
93
+ expiresAt?: number | null
94
+ }
95
+
96
+ export class GrantRepository {
97
+ constructor(
98
+ protected readonly db: SqlDatabase,
99
+ protected readonly writer: AuditWriter = new AuditWriter(db, 'sqlite'),
100
+ ) {}
101
+
102
+ /** Active (non-expired) grants for a principal, ALL apps (admin/effective view). */
103
+ async getActiveGrants(principalId: string): Promise<GrantRow[]> {
104
+ const { results } = await this.db
105
+ .prepare(`SELECT * FROM grants
106
+ WHERE principal_id = ? AND (expires_at IS NULL OR expires_at > ?)`)
107
+ .bind(principalId, unixNow())
108
+ .all<GrantRow>()
109
+ return results
110
+ }
111
+
112
+ /**
113
+ * Active grants that apply to the calling `app` — the authz path. A grant counts when its `app`
114
+ * equals the verified calling app, and a cross-app (NULL) grant counts only when `includeCrossApp`
115
+ * says so: `resolvePermissionsAt` decides that, and it is true for platform audiences only.
116
+ */
117
+ async getActiveGrantsForApp(principalId: string, app: string, options: { includeCrossApp: boolean }): Promise<GrantRow[]> {
118
+ const appFilter = options.includeCrossApp ? '(app = ? OR app IS NULL)' : 'app = ?'
119
+ // A workload principal resolves no grant on any path: its authority is its declared actions (ADR-0022).
120
+ const { results } = await this.db
121
+ .prepare(`SELECT * FROM grants
122
+ WHERE principal_id = ?
123
+ AND ${appFilter}
124
+ AND (expires_at IS NULL OR expires_at > ?)
125
+ AND NOT EXISTS (SELECT 1 FROM workload_principals w WHERE w.principal_id = grants.principal_id)`)
126
+ .bind(principalId, app, unixNow())
127
+ .all<GrantRow>()
128
+ return results
129
+ }
130
+
131
+ /** Grants of `roleKey` at `app` held by an external principal. */
132
+ async listExternalHoldersOfRole(app: string, roleKey: string): Promise<GrantRow[]> {
133
+ const { results } = await this.db
134
+ .prepare(`SELECT g.* FROM grants g JOIN principals p ON p.id = g.principal_id
135
+ WHERE g.app = ? AND g.role_key = ? AND p.affiliation = 'external'
136
+ ORDER BY g.id`)
137
+ .bind(app, roleKey)
138
+ .all<GrantRow>()
139
+ return results
140
+ }
141
+
142
+ /** Grants of `roleKey` at `app` that are not in a value of `scopeType` — global ones included. */
143
+ async listRoleGrantsOutsideScope(app: string, roleKey: string, scopeType: string): Promise<GrantRow[]> {
144
+ const { results } = await this.db
145
+ .prepare(`SELECT * FROM grants
146
+ WHERE app = ? AND role_key = ? AND (scope_type IS NULL OR scope_type <> ?)
147
+ ORDER BY id`)
148
+ .bind(app, roleKey, scopeType)
149
+ .all<GrantRow>()
150
+ return results
151
+ }
152
+
153
+ /** All grants for a principal (admin view, incl. expired). */
154
+ async listGrants(principalId: string): Promise<GrantRow[]> {
155
+ const { results } = await this.db
156
+ .prepare('SELECT * FROM grants WHERE principal_id = ? ORDER BY created_at DESC, id DESC')
157
+ .bind(principalId)
158
+ .all<GrantRow>()
159
+ return results
160
+ }
161
+
162
+ /**
163
+ * All grants for a PAGE of principals, in one statement — the api-keys list used to run one query
164
+ * per row over an unbounded roster (SEC-22). The page is bounded, so the `IN` list is too.
165
+ */
166
+ async listGrantsFor(principalIds: readonly string[]): Promise<GrantRow[]> {
167
+ if (principalIds.length === 0) {
168
+ return []
169
+ }
170
+ const placeholders = principalIds.map(() => '?').join(', ')
171
+ const { results } = await this.db
172
+ .prepare(`SELECT * FROM grants WHERE principal_id IN (${placeholders}) ORDER BY created_at DESC, id DESC`)
173
+ .bind(...principalIds)
174
+ .all<GrantRow>()
175
+ return results
176
+ }
177
+
178
+ async getGrantById(id: string): Promise<GrantRow | null> {
179
+ return this.db.prepare('SELECT * FROM grants WHERE id = ?').bind(id).first<GrantRow>()
180
+ }
181
+
182
+ /**
183
+ * Create a grant. EITHER `roleKey` (named role/policy) OR `permissions` (an inline
184
+ * action-pattern set, JSON-encoded here) — the caller MUST supply exactly one; the
185
+ * DB CHECK rejects both/neither. `scopeType`/`scopeValue` are both-or-neither (both
186
+ * null = global). The handler validates which is set; this layer just persists it.
187
+ * `audit` is the change's record, written in the same batch. Throws `ExternalGrantError`, writing
188
+ * nothing, for a grant the principal may not hold (ADR-0051).
189
+ */
190
+ async createGrant(input: CreateGrantInput, audit?: (grantId: string) => AuditEventInput): Promise<GrantRow> {
191
+ await this.refuseWorkload(input.principalId)
192
+ const id = uuidv7()
193
+ const [created] = await this.writer.run<GrantRow>([this.grantChange(id, input, '')], audit?.(id))
194
+ if (created === undefined) {
195
+ // The insert carries the eligibility condition, so the only way it writes nothing is an ineligible grant.
196
+ throw new ExternalGrantError()
197
+ }
198
+ return created
199
+ }
200
+
201
+ /** Whether `principalId` may hold this grant: it is internal, or the role is one its app declares external. */
202
+ async isEligibleGrant(input: { principalId: string; app?: string | null; roleKey?: string | null }): Promise<boolean> {
203
+ return (await this.db.prepare(`SELECT 1 AS eligible WHERE ${eligibleGrantSql('sqlite')}`).bind(...eligibleGrantBinds(input)).first()) !== null
204
+ }
205
+
206
+ /** Whether `principalId` is a job's, a webhook's or a connector's principal, which holds no grant. */
207
+ async isWorkloadPrincipal(principalId: string): Promise<boolean> {
208
+ return (await this.db.prepare('SELECT principal_id FROM workload_principals WHERE principal_id = ?').bind(principalId).first()) !== null
209
+ }
210
+
211
+ /** A principal is a workload from the batch that creates it, so this check cannot race a later change. */
212
+ private async refuseWorkload(principalId: string): Promise<void> {
213
+ if (await this.isWorkloadPrincipal(principalId)) {
214
+ throw new WorkloadGrantError()
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Create a ROLE grant, or answer null when the principal already holds it. The conflict target is
220
+ * the one unique index this grant falls under (`idx_grants_uq_scoped` / `idx_grants_uq_global`), so
221
+ * the statement itself decides on both engines and any other failure still throws. A grant the
222
+ * principal may not hold writes nothing and throws `ExternalGrantError` (ADR-0051).
223
+ */
224
+ async createRoleGrantUnlessHeld(
225
+ input: CreateGrantInput & { roleKey: string; permissions?: null },
226
+ audit?: (grantId: string) => AuditEventInput,
227
+ ): Promise<GrantRow | null> {
228
+ await this.refuseWorkload(input.principalId)
229
+ const target = input.scopeValue == null
230
+ ? `(principal_id, role_key, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NULL`
231
+ : `(principal_id, role_key, scope_type, scope_value, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NOT NULL`
232
+ const id = uuidv7()
233
+ const [created] = await this.writer.run<GrantRow>([this.grantChange(id, input, `ON CONFLICT ${target} DO NOTHING`)], audit?.(id))
234
+ if (created === undefined && !(await this.isEligibleGrant(input))) {
235
+ throw new ExternalGrantError()
236
+ }
237
+ return created ?? null
238
+ }
239
+
240
+ /**
241
+ * `createRoleGrantUnlessHeld` of a global role under a delegated `authority`, renewing an expired one in place with the
242
+ * new expiry: null when the principal holds it unexpired or the authority changed since its check
243
+ * (`delegatedAuthorityHolds` tells them apart). Throws `ExternalGrantError` for a grant the principal may not hold.
244
+ */
245
+ async createDelegatedRoleGrant(
246
+ input: { principalId: string; roleKey: string; grantedBy: string; expiresAt?: number | null },
247
+ authority: DelegatedAuthority,
248
+ audit: (grantId: string) => AuditEventInput,
249
+ ): Promise<GrantRow | null> {
250
+ await this.refuseWorkload(input.principalId)
251
+ const guard = this.delegatedGuard(authority, 0)
252
+ const now = unixNow()
253
+ // A renewal keeps the expired row's id, so its record names the row it changed.
254
+ const expired = await this.db
255
+ .prepare(`SELECT id FROM grants WHERE principal_id = ? AND role_key = ? AND app = ? AND scope_value IS NULL
256
+ AND expires_at IS NOT NULL AND expires_at <= ?`)
257
+ .bind(input.principalId, input.roleKey, authority.app, now)
258
+ .first<{ id: string }>()
259
+ const id = expired?.id ?? uuidv7()
260
+ const grant = { ...input, app: authority.app }
261
+ const conflict = `ON CONFLICT (principal_id, role_key, COALESCE(app, '*')) WHERE role_key IS NOT NULL AND scope_value IS NULL
262
+ DO UPDATE SET expires_at = excluded.expires_at, granted_by = excluded.granted_by, created_at = excluded.created_at
263
+ WHERE grants.expires_at IS NOT NULL AND grants.expires_at <= ?`
264
+ const insert = this.grantChange(id, grant, conflict, guard)
265
+ const change = this.writer.changed([{ sql: insert.sql, binds: [...insert.binds, now] }], audit(id))
266
+ const locks = [...this.administratorLock(authority), ...this.revisionLock(authority)]
267
+ const [created] = change.rows<GrantRow>(await this.db.batch([...locks, ...change.statements]), locks.length)
268
+ if (created === undefined && !(await this.isEligibleGrant(grant))) {
269
+ throw new ExternalGrantError()
270
+ }
271
+ return created ?? null
272
+ }
273
+
274
+ /**
275
+ * Delete a grant under a delegated `authority`, after its principal's revision (`grantRemovalStatement`); false when
276
+ * it is gone or the authority changed since its check. A removal of the administrator's own grant moves the revision
277
+ * the guard reads, so the guard expects it one higher.
278
+ */
279
+ async deleteDelegatedGrant(grant: Pick<GrantRow, 'id' | 'principal_id'>, authority: DelegatedAuthority, audit: AuditEventInput): Promise<boolean> {
280
+ const own = grant.principal_id === authority.administratorId
281
+ const guard = this.delegatedGuard(authority, own ? 1 : 0)
282
+ const removal = this.writer.changed(
283
+ [{ sql: `DELETE FROM grants WHERE id = ? AND ${guard.sql} RETURNING id`, binds: [grant.id, ...guard.binds] }],
284
+ audit,
285
+ )
286
+ const locks = [
287
+ ...(own ? [] : this.administratorLock(authority)),
288
+ grantRemovalStatement(this.db, { principalId: grant.principal_id }),
289
+ ...this.revisionLock(authority),
290
+ ]
291
+ return removal.rows(await this.db.batch([...locks, ...removal.statements]), locks.length).length > 0
292
+ }
293
+
294
+ /** Whether `authority` still holds: the administrator enabled and both revisions the ones its check read. */
295
+ async delegatedAuthorityHolds(authority: DelegatedAuthority): Promise<boolean> {
296
+ const guard = this.delegatedGuard(authority, 0)
297
+ return (await this.db.prepare(`SELECT 1 AS holds WHERE ${guard.sql}`).bind(...guard.binds).first()) !== null
298
+ }
299
+
300
+ /**
301
+ * On Postgres a delegated change takes the principal rows first, as every writer of a principal's rows starts: the
302
+ * administrator's `FOR SHARE` (a disable or a grant removal waits, or the change reads the committed one), and a
303
+ * removed grant's principal by its revision's increment, which takes the administrator's own row when the grant is
304
+ * theirs. Then the app's revision row `FOR SHARE`: a reconcile's increment, its first statement, waits, or the change
305
+ * reads the new revision. SQLite and D1 run one writer at a time and need no lock.
306
+ */
307
+ private administratorLock(authority: DelegatedAuthority): SqlStatement[] {
308
+ return this.writer.dialect === 'postgres'
309
+ ? [this.db.prepare('SELECT id FROM principals WHERE id = ? FOR SHARE').bind(authority.administratorId)]
310
+ : []
311
+ }
312
+
313
+ private revisionLock(authority: DelegatedAuthority): SqlStatement[] {
314
+ return this.writer.dialect === 'postgres'
315
+ ? [this.db.prepare('SELECT revision FROM app_schema_revisions WHERE app = ? FOR SHARE').bind(authority.app)]
316
+ : []
317
+ }
318
+
319
+ private delegatedGuard(authority: DelegatedAuthority, ownRemoval: 0 | 1): { sql: string; binds: (string | number)[] } {
320
+ return {
321
+ sql: `EXISTS (SELECT 1 FROM principals WHERE id = ? AND disabled_at IS NULL AND grant_revision = ?)
322
+ AND COALESCE((SELECT revision FROM app_schema_revisions WHERE app = ?), 0) = ?`,
323
+ binds: [authority.administratorId, authority.grantRevision + ownRemoval, authority.app, authority.schemaRevision],
324
+ }
325
+ }
326
+
327
+ /** The INSERT of one grant with a caller-generated id, for a batch that also writes its principal and record. */
328
+ grantStatement(id: string, input: CreateGrantInput, onConflict: string = ''): SqlStatement {
329
+ const insert = this.grantChange(id, input, onConflict)
330
+ return this.db.prepare(insert.sql).bind(...insert.binds)
331
+ }
332
+
333
+ private grantChange(id: string, input: CreateGrantInput, onConflict: string, guard?: { sql: string; binds: (string | number)[] }): SqlChange {
334
+ return {
335
+ sql: `INSERT INTO grants (id, principal_id, app, role_key, permissions, scope_type, scope_value, granted_by, expires_at, created_at)
336
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE ${eligibleGrantSql(this.writer.dialect)}${
337
+ guard === undefined ? '' : ` AND ${guard.sql}`
338
+ } ${onConflict} RETURNING *`,
339
+ binds: [
340
+ id,
341
+ input.principalId,
342
+ input.app ?? null,
343
+ input.roleKey ?? null,
344
+ input.permissions == null ? null : JSON.stringify(input.permissions),
345
+ input.scopeType ?? null,
346
+ input.scopeValue ?? null,
347
+ input.grantedBy ?? null,
348
+ input.expiresAt ?? null,
349
+ unixNow(),
350
+ ...eligibleGrantBinds(input),
351
+ ...(guard?.binds ?? []),
352
+ ],
353
+ }
354
+ }
355
+
356
+ /** Keep the audit's before-value true if another administrator edited this grant after it was read. */
357
+ async updateGrant(grant: GrantRow, input: CreateGrantInput, audit: AuditEventInput): Promise<GrantRow | null> {
358
+ await this.refuseWorkload(grant.principal_id)
359
+ const update = this.writer.changed([{
360
+ sql: `UPDATE grants SET role_key = ?, permissions = ?, scope_type = ?, scope_value = ?, expires_at = ?
361
+ WHERE id = ? AND role_key IS NOT DISTINCT FROM ? AND permissions IS NOT DISTINCT FROM ?
362
+ AND scope_type IS NOT DISTINCT FROM ? AND scope_value IS NOT DISTINCT FROM ? AND expires_at IS NOT DISTINCT FROM ?
363
+ AND ${eligibleGrantSql(this.writer.dialect)} RETURNING *`,
364
+ binds: [
365
+ input.roleKey ?? null,
366
+ input.permissions === null || input.permissions === undefined ? null : JSON.stringify(input.permissions),
367
+ input.scopeType ?? null,
368
+ input.scopeValue ?? null,
369
+ input.expiresAt ?? null,
370
+ grant.id,
371
+ grant.role_key,
372
+ grant.permissions,
373
+ grant.scope_type,
374
+ grant.scope_value,
375
+ grant.expires_at,
376
+ ...eligibleGrantBinds(input),
377
+ ],
378
+ }], audit)
379
+ // Editing can remove authority too. Invalidate pending delegation checks before changing the grant.
380
+ const results = await this.db.batch<GrantRow>([grantRemovalStatement(this.db, { principalId: grant.principal_id }), ...update.statements])
381
+ return update.rows(results, 1)[0] ?? null
382
+ }
383
+
384
+ /** Delete a grant, after its principal's revision. */
385
+ async deleteGrant(id: string, audit?: AuditEventInput): Promise<boolean> {
386
+ const removal = this.writer.changed([{ sql: 'DELETE FROM grants WHERE id = ? RETURNING id', binds: [id] }], audit)
387
+ const results = await this.db.batch([grantRemovalStatement(this.db, { grantId: id }), ...removal.statements])
388
+ return removal.rows(results, 1).length > 0
389
+ }
390
+
391
+ /** Delete all grants for a principal (revocation), after its revision (`grantRemovalStatement`). */
392
+ async deleteGrantsForPrincipal(principalId: string): Promise<void> {
393
+ const removal = this.db.prepare('DELETE FROM grants WHERE principal_id = ?').bind(principalId)
394
+ await this.db.batch([grantRemovalStatement(this.db, { principalId }), removal])
395
+ }
396
+
397
+ /**
398
+ * Every grant of a principal, as a change an audited revocation groups with others. It moves no grant revision, so
399
+ * the group must disable the principal in the same transaction, which an acceptance sees as surely (`InviterCheck`).
400
+ */
401
+ deleteGrantsForPrincipalChange(principalId: string): SqlChange {
402
+ return { sql: 'DELETE FROM grants WHERE principal_id = ? RETURNING id', binds: [principalId] }
403
+ }
404
+ }
@@ -0,0 +1,103 @@
1
+ import { type SqlDatabase, type SqlStatement, uuidv7 } from '@fabrika/platform'
2
+ import { type AuditEventInput, auditEventStatement } from './audit'
3
+ import { unixNow } from './sql'
4
+
5
+ /** A single-use cross-host handoff code (`auth_codes`). Only its hash is stored. */
6
+ export interface AuthCodeRow {
7
+ id: string
8
+ code_hash: string
9
+ app: string
10
+ parent_session_id: string
11
+ return_url: string
12
+ expires_at: number
13
+ consumed_at: number | null
14
+ created_at: number
15
+ }
16
+
17
+ export class HandoffRepository {
18
+ constructor(protected readonly db: SqlDatabase) {}
19
+
20
+ /** Origins IAM will send a browser back to for this app. Empty = the app can receive no handoff. */
21
+ async listReturnOrigins(app: string): Promise<string[]> {
22
+ const { results } = await this.db
23
+ .prepare('SELECT origin FROM app_return_origins WHERE app = ? ORDER BY origin')
24
+ .bind(app)
25
+ .all<{ origin: string }>()
26
+ return results.map((row) => row.origin)
27
+ }
28
+
29
+ /**
30
+ * Replace an app's registered return origins. Declarative on purpose: the caller states the whole
31
+ * set, so removing an origin is the same operation as adding one and a stale entry cannot survive
32
+ * a reconcile. Values are stored exactly as given — `normalizeOrigin` is the one place that decides
33
+ * what canonical means, and it runs before this.
34
+ *
35
+ * ONE batch, like `reconcileAppSchema`: a failure between the DELETE and the INSERTs would leave
36
+ * the app with no registered origin, which is a hard refusal on every cross-host sign-in.
37
+ */
38
+ async setReturnOrigins(app: string, origins: readonly string[], audit?: AuditEventInput): Promise<void> {
39
+ const now = unixNow()
40
+ const statements: SqlStatement[] = [this.db.prepare('DELETE FROM app_return_origins WHERE app = ?').bind(app)]
41
+ for (const origin of origins) {
42
+ statements.push(
43
+ this.db.prepare('INSERT INTO app_return_origins (app, origin, created_at) VALUES (?, ?, ?)').bind(app, origin, now),
44
+ )
45
+ }
46
+ if (audit !== undefined) {
47
+ statements.push(auditEventStatement(this.db, audit))
48
+ }
49
+ await this.db.batch(statements)
50
+ }
51
+
52
+ /** Issue a single-use code. Only the hash is stored; the plaintext lives in one redirect. */
53
+ async issueCode(input: {
54
+ codeHash: string
55
+ app: string
56
+ parentSessionId: string
57
+ returnUrl: string
58
+ expiresAt: number
59
+ }): Promise<string> {
60
+ const id = uuidv7()
61
+ await this.db
62
+ .prepare(`INSERT INTO auth_codes (id, code_hash, app, parent_session_id, return_url, expires_at, created_at)
63
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)
64
+ .bind(id, input.codeHash, input.app, input.parentSessionId, input.returnUrl, input.expiresAt, unixNow())
65
+ .run()
66
+ return id
67
+ }
68
+
69
+ /**
70
+ * Consume a code, atomically and at most once.
71
+ *
72
+ * The UPDATE is the guard, not the SELECT: a second redemption of the same code changes no rows
73
+ * and gets null, with no window in which two callers both believe they won. The row is read only
74
+ * after it has been marked, so what comes back is what this caller consumed.
75
+ *
76
+ * Returns null for unknown, expired and already-consumed alike — the caller maps those to distinct
77
+ * reasons by looking the code up separately, because none of them is worth a second write here.
78
+ */
79
+ async consumeCode(codeHash: string, now: number): Promise<AuthCodeRow | null> {
80
+ const marked = await this.db
81
+ .prepare('UPDATE auth_codes SET consumed_at = ? WHERE code_hash = ? AND consumed_at IS NULL AND expires_at > ?')
82
+ .bind(now, codeHash, now)
83
+ .run()
84
+ if ((marked.meta.changes ?? 0) === 0) {
85
+ return null
86
+ }
87
+ return this.db.prepare('SELECT * FROM auth_codes WHERE code_hash = ?').bind(codeHash).first<AuthCodeRow>()
88
+ }
89
+
90
+ /** Whether a code exists at all — only to tell `expired_code` from `invalid_code` after a miss. */
91
+ async findCode(codeHash: string): Promise<AuthCodeRow | null> {
92
+ return this.db.prepare('SELECT * FROM auth_codes WHERE code_hash = ?').bind(codeHash).first<AuthCodeRow>()
93
+ }
94
+
95
+ /** Prune spent and expired codes (cron). Returns the number removed. */
96
+ async pruneCodes(olderThanSeconds: number): Promise<number> {
97
+ const result = await this.db
98
+ .prepare('DELETE FROM auth_codes WHERE expires_at < ? OR consumed_at IS NOT NULL')
99
+ .bind(olderThanSeconds)
100
+ .run()
101
+ return result.meta.changes ?? 0
102
+ }
103
+ }
@@ -0,0 +1,49 @@
1
+ import { type SqlDatabase, uuidv7 } from '@fabrika/platform'
2
+ import { type AuditEventInput, auditEventStatement } from './audit'
3
+
4
+ /** One live membership transport key (the `membership_transport_keys` table); only its hash is stored. */
5
+ export interface MembershipTransportKeyRow {
6
+ id: string
7
+ app: string
8
+ key_hash: string
9
+ expires_at: number
10
+ created_at: number
11
+ }
12
+
13
+ /**
14
+ * The keys an application environment authenticates IAM's membership transport with (`src/membership-http.ts`). A key
15
+ * names the one IAM application id it acts for and nothing else: it is no principal and holds no grant.
16
+ */
17
+ export class MembershipTransportKeyRepository {
18
+ constructor(protected readonly db: SqlDatabase) {}
19
+
20
+ /**
21
+ * Record a new key of `app` and delete every other key of it except `keep`, in one batch: the key the caller recorded
22
+ * as active stays valid until the caller replaces it, and a key issued earlier and never recorded is gone.
23
+ */
24
+ async issue(
25
+ input: { app: string; keyHash: string; expiresAt: number; keep: string | null; now: number },
26
+ audit?: (keyId: string) => AuditEventInput,
27
+ ): Promise<string> {
28
+ const id = uuidv7()
29
+ await this.db.batch([
30
+ this.db
31
+ .prepare('DELETE FROM membership_transport_keys WHERE app = ? AND id <> ?')
32
+ .bind(input.app, input.keep ?? ''),
33
+ this.db
34
+ .prepare('INSERT INTO membership_transport_keys (id, app, key_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?)')
35
+ .bind(id, input.app, input.keyHash, input.expiresAt, input.now),
36
+ ...(audit === undefined ? [] : [auditEventStatement(this.db, audit(id))]),
37
+ ])
38
+ return id
39
+ }
40
+
41
+ /** The application id a live key acts for, or null for an unknown or expired key. */
42
+ async appOfKey(keyHash: string, now: number): Promise<string | null> {
43
+ const row = await this.db
44
+ .prepare('SELECT app FROM membership_transport_keys WHERE key_hash = ? AND expires_at > ?')
45
+ .bind(keyHash, now)
46
+ .first<{ app: string }>()
47
+ return row?.app ?? null
48
+ }
49
+ }