@fabrika/iam 0.0.1 → 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 +69 -8
  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
package/src/resolve.ts ADDED
@@ -0,0 +1,396 @@
1
+ import {
2
+ isReservedScopeType,
3
+ matchAction,
4
+ type PermissionEntry,
5
+ type PermissionSource,
6
+ type PrincipalAffiliation,
7
+ RELATION_SCOPE_TYPE,
8
+ relationInsideScope,
9
+ type RoleDef,
10
+ type RoleSource,
11
+ type Scope,
12
+ uniquePermissions,
13
+ } from '@fabrika/auth-core'
14
+ import type { AuditEventInput, GrantRow, IamRepositories, PrincipalRow, RoleRow } from './db'
15
+ import { normalizeEmailIdentity } from './email-identity'
16
+ import { logWarn } from './log'
17
+ import { makeRoleSource } from './roles'
18
+ import type { Config } from './services'
19
+ import { parseStoredPermissions, parseStoredVia } from './stored-permissions'
20
+
21
+ // ── Pure resolution (no I/O) — testable with in-memory rows ───────────────────
22
+
23
+ /**
24
+ * The explicit grants already fetched as rows, plus the bootstrap decision.
25
+ * `computePermissions` is pure over this, so the union/dedup logic is
26
+ * unit-testable without D1.
27
+ */
28
+ export interface ResolutionInputs {
29
+ /** The calling app — passed to `RoleSource.getRole`; null = cross-app. */
30
+ app: string | null
31
+ /** Active, non-expired explicit grants for this principal. */
32
+ grants: GrantRow[]
33
+ /** True when the user's email is in IAM_BOOTSTRAP_ADMINS (false for services). */
34
+ isBootstrapAdmin: boolean
35
+ /**
36
+ * An `external` principal's grant counts only when it names a role of `app` declared external (ADR-0051): no inline,
37
+ * cross-app or built-in grant, and no bootstrap `admin`.
38
+ */
39
+ affiliation: PrincipalAffiliation
40
+ /**
41
+ * A contract application holds exact actions of its approved catalog: a pattern (a stored `*` or `prefix.*`, the
42
+ * built-in `admin` included) contributes nothing there, so nothing tracks the catalog beyond its approved revision.
43
+ */
44
+ exactActions?: boolean
45
+ }
46
+
47
+ /**
48
+ * Reconstruct the flat scope coordinate from a row's `scope_type`/`scope_value`. Both
49
+ * are NULL together (= global, `scope: null`) by the migration's both-or-neither
50
+ * CHECK; a half-set pair can't exist, but we guard on `scope_type` to stay total.
51
+ */
52
+ function rowScope(scopeType: string | null, scopeValue: string | null): Scope | null {
53
+ return scopeType === null || scopeValue === null ? null : { type: scopeType, value: scopeValue }
54
+ }
55
+
56
+ /**
57
+ * A principal's resolved permissions and how long they hold. `supports` keeps, per identical action-and-scope entry,
58
+ * the latest expiry among the grants behind it (`null` = no deadline), so a credential can be capped by the authority
59
+ * it carries (`authorityDeadline`).
60
+ */
61
+ export interface ResolvedAuthority {
62
+ permissions: PermissionEntry[]
63
+ supports: readonly HeldEntry[]
64
+ }
65
+
66
+ /** One `(action, scope)` a principal holds and until when; `null` is no deadline. */
67
+ export interface HeldEntry {
68
+ action: string
69
+ scope: Scope | null
70
+ until: number | null
71
+ }
72
+
73
+ /** The `~relin` scope of `relation` inside `scope`, or null when a name holds the `:` the entry's value cannot carry. */
74
+ function insideScope(relation: string, scope: Scope): Scope | null {
75
+ if (relation.includes(':') || scope.type.includes(':')) {
76
+ return null
77
+ }
78
+ return relationInsideScope({ relation, dimension: scope.type, node: scope.value })
79
+ }
80
+
81
+ /**
82
+ * Union the permission sources, expanding role keys into permission patterns via the
83
+ * (app-aware) role source and adding inline grant patterns directly, then dedupe.
84
+ * Wildcards (`*`, `prefix.*`) stay as patterns in the entries — they are NOT
85
+ * pre-expanded; `permits()` in core matches them. A grant whose role key no longer
86
+ * resolves contributes zero permissions (fail-closed).
87
+ *
88
+ * Resolution is PURE: `roles` is built up front from the app's loaded DB rows, so no
89
+ * I/O happens here. Dedup key is `action|scope|source` — the same permission from two
90
+ * sources is kept separately so the admin UI can explain *why* a permission is held;
91
+ * `can()` / `scopedTo()` ignore `source` anyway.
92
+ */
93
+ export function computePermissions(inputs: ResolutionInputs, roles: RoleSource): PermissionEntry[] {
94
+ return computeAuthority(inputs, roles).permissions
95
+ }
96
+
97
+ /** `computePermissions`, plus each entry's latest supporting expiry. */
98
+ export function computeAuthority(inputs: ResolutionInputs, roles: RoleSource): ResolvedAuthority {
99
+ const entries: PermissionEntry[] = []
100
+ const supports = new Map<string, HeldEntry>()
101
+
102
+ const add = (action: string, scope: Scope | null, source: PermissionSource, until: number | null): void => {
103
+ if (inputs.exactActions === true && action.includes('*')) {
104
+ return
105
+ }
106
+ const scopeKey = scope === null ? '' : `${scope.type}:${scope.value}`
107
+ const held = supports.get(`${action} ${scopeKey}`)
108
+ if (held === undefined) {
109
+ supports.set(`${action} ${scopeKey}`, { action, scope, until })
110
+ } else if (held.until !== null) {
111
+ held.until = until === null ? null : Math.max(held.until, until)
112
+ }
113
+ entries.push({ action, scope, source })
114
+ }
115
+
116
+ const external = inputs.affiliation === 'external'
117
+ const expandRole = (roleKey: string, scope: Scope | null, source: PermissionSource, until: number | null): void => {
118
+ const role = roles.getRole(inputs.app, roleKey)
119
+ if (!role) {
120
+ // Dangling role key — resolves to zero permissions (fail-closed).
121
+ return
122
+ }
123
+ if (external && role.external !== true) {
124
+ // An external principal's grant of a role not declared external (a grant older than a narrowing).
125
+ return
126
+ }
127
+ if (role.member !== undefined && scope?.type !== role.member.scope) {
128
+ // A membership role outside a value of its own dimension (a grant older than the declaration).
129
+ return
130
+ }
131
+ for (const permission of role.permissions) {
132
+ add(permission, scope, source, until)
133
+ }
134
+ // A global grant holds a relation anywhere (`~rel`); a grant at a node holds it only inside that node (`~relin`),
135
+ // never `~rel`, which would hold it at nodes outside the grant. An external principal holds no relation (ADR-0051).
136
+ if (external || role.external === true) {
137
+ return
138
+ }
139
+ for (const [relation, actions] of Object.entries(role.via ?? {})) {
140
+ const held = scope === null ? { type: RELATION_SCOPE_TYPE, value: relation } : insideScope(relation, scope)
141
+ for (const action of held === null ? [] : actions) {
142
+ add(action, held, source, until)
143
+ }
144
+ }
145
+ }
146
+
147
+ // 1. Explicit grants — EITHER a named role OR an inline action-pattern set.
148
+ for (const grant of inputs.grants) {
149
+ const scope = rowScope(grant.scope_type, grant.scope_value)
150
+ if (external && (grant.app === null || grant.role_key === null)) {
151
+ continue
152
+ }
153
+ if (scope !== null && isReservedScopeType(scope.type)) {
154
+ // A row stored before `~` was reserved: IAM alone derives a `~` entry, so the row grants nothing.
155
+ continue
156
+ }
157
+ if (grant.role_key !== null) {
158
+ expandRole(grant.role_key, scope, 'grant', grant.expires_at)
159
+ } else if (grant.permissions !== null) {
160
+ for (const pattern of parseStoredPermissions(grant.permissions)) {
161
+ add(pattern, scope, 'grant', grant.expires_at)
162
+ }
163
+ }
164
+ }
165
+
166
+ // 2. Bootstrap admins (users only) — the built-in global `admin` role, source
167
+ // 'bootstrap'. `admin` is a cross-app built-in, so it resolves even at app=null.
168
+ if (inputs.isBootstrapAdmin && !external) {
169
+ expandRole('admin', null, 'bootstrap', null)
170
+ }
171
+
172
+ return { permissions: uniquePermissions(entries), supports: [...supports.values()] }
173
+ }
174
+
175
+ /**
176
+ * The earliest time at which some entry of `carried` loses all its support in `authority`, or `null` when none ever
177
+ * does. An entry is supported by every held entry that covers it under `permits` semantics (a global entry covers a
178
+ * scoped one, a pattern the actions it matches); an entry nothing supports gives the deadline `now`, which no caller
179
+ * meets because it carries only what `authority` holds.
180
+ */
181
+ export function authorityDeadline(authority: Pick<ResolvedAuthority, 'supports'>, carried: readonly PermissionEntry[], now: number): number | null {
182
+ let deadline: number | null = null
183
+ for (const entry of carried) {
184
+ let latest: number | null | undefined
185
+ for (const held of authority.supports) {
186
+ const scopeOk = held.scope === null || (entry.scope !== null && held.scope.type === entry.scope.type && held.scope.value === entry.scope.value)
187
+ if (!scopeOk || !matchAction(held.action, entry.action)) {
188
+ continue
189
+ }
190
+ if (held.until === null || latest === null) {
191
+ latest = null
192
+ } else {
193
+ latest = latest === undefined ? held.until : Math.max(latest, held.until)
194
+ }
195
+ }
196
+ const until = latest === undefined ? now : latest
197
+ if (until !== null && (deadline === null || until < deadline)) {
198
+ deadline = until
199
+ }
200
+ }
201
+ return deadline
202
+ }
203
+
204
+ // ── Principal resolution (the 3-step claim-then-lazy flow) ────────────────────
205
+
206
+ export type ResolveUserResult =
207
+ | { ok: true; principal: PrincipalRow }
208
+ | { ok: false; reason: 'disabled' | 'unknown_principal' | 'external_principal' }
209
+
210
+ /**
211
+ * The narrow principal capability that user resolution needs. Keeping the contract local makes the
212
+ * 3-step flow unit-testable with an in-memory store. `PrincipalRepository` satisfies it structurally.
213
+ */
214
+ export interface UserPrincipalStore {
215
+ getUserByExternalId(sub: string): Promise<PrincipalRow | null>
216
+ getUserByEmail(email: string): Promise<PrincipalRow | null>
217
+ refreshUserLabel(id: string, email: string, audit?: AuditEventInput): Promise<void>
218
+ claimInvitedUser(id: string, sub: string, label: string, audit?: AuditEventInput): Promise<PrincipalRow | null>
219
+ createUser(sub: string, email: string, audit?: (principalId: string) => AuditEventInput): Promise<PrincipalRow>
220
+ }
221
+
222
+ /** The record of a change a login made to its own principal: by the principal, about it, with no email in it. */
223
+ function loginEvent(requestId: string, principalId: string, action: string): AuditEventInput {
224
+ return { requestId, principalId, principalLabel: principalId, app: 'propustka', action, resourceType: 'principal', resourceId: principalId }
225
+ }
226
+
227
+ /**
228
+ * Resolve (or claim/create) a user principal from a verified identity-login JWT.
229
+ * Ordered: (1) by `sub`; (2) claim an invited row matched on the IdP-verified
230
+ * `email`; (3) lazy-create. Matching uses ONLY the verified token email — never a
231
+ * self-asserted value. A disabled match returns `disabled` (403). An email that
232
+ * already belongs to a *different* claimed sub is a conflict → `unknown_principal`
233
+ * (fail-closed; the unique-email index forbids a second user, so we never insert).
234
+ *
235
+ * The mailbox, not the spelling, is what matches: the store normalizes on both sides, so an invite
236
+ * for `Bob@Example.com` is claimed by an IdP that says `bob@example.com` instead of lazy-creating a
237
+ * second principal and stranding every grant on the first.
238
+ *
239
+ * Every write records itself in its own transaction, under the login's `requestId`: a creation, a claim, and a refresh
240
+ * of the mailbox the IdP now reports.
241
+ */
242
+ export async function resolveUserPrincipal(db: UserPrincipalStore, sub: string, email: string, requestId: string): Promise<ResolveUserResult> {
243
+ const mailbox = normalizeEmailIdentity(email)
244
+ // 1. By sub — a returning user. Refresh mailbox/label if the token's email changed.
245
+ const bySub = await db.getUserByExternalId(sub)
246
+ if (bySub) {
247
+ if (bySub.affiliation === 'external') {
248
+ return { ok: false, reason: 'external_principal' }
249
+ }
250
+ if (bySub.disabled_at !== null) {
251
+ return { ok: false, reason: 'disabled' }
252
+ }
253
+ if (bySub.email !== mailbox || bySub.label !== email) {
254
+ try {
255
+ await db.refreshUserLabel(bySub.id, email, loginEvent(requestId, bySub.id, 'iam.principal.refresh'))
256
+ } catch (err) {
257
+ // Non-fatal: the new token email may collide with another principal's
258
+ // unique-email row. This user is already a known principal by sub, so a
259
+ // cosmetic label refresh must never lock them out — keep serving the
260
+ // existing identity (its current email/label) and skip the refresh.
261
+ logWarn(`refreshUserLabel skipped for principal ${bySub.id} (its new mailbox collides with another principal)`, err)
262
+ return { ok: true, principal: bySub }
263
+ }
264
+ }
265
+ return { ok: true, principal: { ...bySub, email: mailbox, label: email } }
266
+ }
267
+
268
+ // 2. Match the verified email.
269
+ const byEmail = await db.getUserByEmail(email)
270
+ if (byEmail) {
271
+ if (byEmail.affiliation === 'external') {
272
+ // An external person authenticates by password only; an IdP presenting the address claims nothing (ADR-0051).
273
+ return { ok: false, reason: 'external_principal' }
274
+ }
275
+ if (byEmail.external_id === null) {
276
+ // An invited row — claim it.
277
+ if (byEmail.disabled_at !== null) {
278
+ // An invited-but-disabled principal — treat as not allowed.
279
+ return { ok: false, reason: 'disabled' }
280
+ }
281
+ const claimed = await db.claimInvitedUser(byEmail.id, sub, email, loginEvent(requestId, byEmail.id, 'iam.principal.claim'))
282
+ if (claimed) {
283
+ return { ok: true, principal: claimed }
284
+ }
285
+ // Lost the claim race — re-read by sub (the winner bound the same sub).
286
+ const reread = await db.getUserByExternalId(sub)
287
+ if (reread) {
288
+ if (reread.disabled_at !== null) {
289
+ return { ok: false, reason: 'disabled' }
290
+ }
291
+ return { ok: true, principal: reread }
292
+ }
293
+ }
294
+ // The email belongs to a row already claimed by a DIFFERENT sub (step 1 didn't
295
+ // match this sub). The unique-email index forbids a second user — fail closed.
296
+ // Narrow window per spec (email reassigned before first login); mitigate with
297
+ // invite expiry later (out of scope v1).
298
+ return { ok: false, reason: 'unknown_principal' }
299
+ }
300
+
301
+ // 3. Lazy-create, zero grants — unprivileged until granted or matched.
302
+ try {
303
+ const created = await db.createUser(sub, email, (principalId) => loginEvent(requestId, principalId, 'iam.principal.create'))
304
+ return { ok: true, principal: created }
305
+ } catch (err) {
306
+ // Lazy-create race: two concurrent first logins for the same brand-new sub both
307
+ // miss steps 1 & 2, then both INSERT. The second hits the partial unique index
308
+ // (idx_principals_uq_external / idx_principals_uq_email) and D1 throws. Recover
309
+ // exactly like the step-2 claim race: re-read by sub and serve the winner
310
+ // (honoring its disabled_at). If the re-read still finds nothing, fail closed.
311
+ const reread = await db.getUserByExternalId(sub)
312
+ if (reread) {
313
+ if (reread.disabled_at !== null) {
314
+ return { ok: false, reason: 'disabled' }
315
+ }
316
+ return { ok: true, principal: reread }
317
+ }
318
+ logWarn(`createUser failed and no row found on re-read for sub '${sub}'`, err)
319
+ return { ok: false, reason: 'unknown_principal' }
320
+ }
321
+ }
322
+
323
+ // ── Full resolution wiring (grants ∪ bootstrap) ───────────────────────────────
324
+
325
+ /**
326
+ * Load the calling app's DB roles into a `RoleSource` (built-ins layered over them).
327
+ * `app === null` (cross-app, e.g. the provisioning key / a NULL-app token) has no
328
+ * per-app rows to load — only the built-in `admin` applies. Roles are fetched HERE,
329
+ * up front, so `computePermissions` stays pure: its parsed permission arrays are
330
+ * cached in the returned `RoleSource`'s map and never re-read from D1.
331
+ *
332
+ * A cross-app grant's INLINE patterns are unaffected by this: they are carried through
333
+ * `computePermissions` verbatim and matched by `permits()` at request time, never pre-expanded
334
+ * against a catalog. That is why a cross-app grant covers an app registered after the grant was
335
+ * written, and why the admin surface validates such a grant against the UNION of every registered
336
+ * catalog as a typo check rather than as a boundary (see `parseRoleOrInline`).
337
+ */
338
+ async function loadRoleSource(repositories: IamRepositories, app: string | null): Promise<RoleSource> {
339
+ const appRoles: Record<string, RoleDef> = {}
340
+ if (app !== null) {
341
+ for (const row of await repositories.appSchema.listRoles(app)) {
342
+ appRoles[row.role_key] = toRoleDef(row)
343
+ }
344
+ }
345
+ return makeRoleSource(appRoles)
346
+ }
347
+
348
+ /** A `roles` row → core `RoleDef`. `permissions` parses from its JSON-array column. */
349
+ function toRoleDef(row: RoleRow): RoleDef {
350
+ return {
351
+ name: row.name,
352
+ ...(row.description !== null ? { description: row.description } : {}),
353
+ permissions: parseStoredPermissions(row.permissions),
354
+ ...(row.member_scope !== null ? { member: { scope: row.member_scope } } : {}),
355
+ ...(row.external === 1 ? { external: true } : {}),
356
+ ...(row.via === null ? {} : { via: parseStoredVia(row.via) }),
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Whether cross-app grants and the bootstrap `admin` reach a token for `app` (ADR-0022 rule 6). Only a
362
+ * platform audience gets them: every application receives its token in cleartext, and a token minted for
363
+ * one application must not carry authority over another, or another environment of itself.
364
+ */
365
+ export function reachesCrossAppAuthority(config: Pick<Config, 'platformAudiences'>, app: string): boolean {
366
+ return config.platformAudiences.has(app)
367
+ }
368
+
369
+ /**
370
+ * A principal's permissions AT ONE APP — the question every mint front, the admin views and the
371
+ * delegation checks ask. A platform audience sees the principal's cross-app grants and, for a bootstrap
372
+ * admin, the global `admin`; an application sees only the grants of its own app id. The app's roles are
373
+ * loaded once and passed to the pure `computePermissions`.
374
+ */
375
+ export async function resolvePermissionsAt(
376
+ services: { readonly repositories: IamRepositories; readonly config: Pick<Config, 'bootstrapAdmins' | 'platformAudiences'> },
377
+ principal: PrincipalRow,
378
+ app: string,
379
+ ): Promise<PermissionEntry[]> {
380
+ return (await resolveAuthorityAt(services, principal, app)).permissions
381
+ }
382
+
383
+ /** `resolvePermissionsAt`, with each entry's latest supporting expiry, for a mint front that caps its credential. */
384
+ export async function resolveAuthorityAt(
385
+ services: { readonly repositories: IamRepositories; readonly config: Pick<Config, 'bootstrapAdmins' | 'platformAudiences'> },
386
+ principal: PrincipalRow,
387
+ app: string,
388
+ ): Promise<ResolvedAuthority> {
389
+ const crossApp = reachesCrossAppAuthority(services.config, app)
390
+ const grants = await services.repositories.grants.getActiveGrantsForApp(principal.id, app, { includeCrossApp: crossApp })
391
+ const isBootstrapAdmin = crossApp && principal.type === 'user' && principal.affiliation === 'internal' && principal.email !== null
392
+ && services.config.bootstrapAdmins.has(normalizeEmailIdentity(principal.email))
393
+ const roles = await loadRoleSource(services.repositories, app)
394
+ const exactActions = await services.repositories.appSchema.isContractApp(app)
395
+ return computeAuthority({ app, grants, isBootstrapAdmin, affiliation: principal.affiliation, exactActions }, roles)
396
+ }
@@ -0,0 +1,34 @@
1
+ /** How long IAM keeps its logs, in days: `auth_log` always expires, `audit_events` only when the operator says so. */
2
+ export interface Retention {
3
+ readonly authLogDays: number
4
+ /** Null keeps every audit row: an audit trail that expires is not one unless the operator chose it. */
5
+ readonly auditDays: number | null
6
+ }
7
+
8
+ export const DEFAULT_AUTH_LOG_RETENTION_DAYS = 30
9
+
10
+ const DAYS = /^[1-9][0-9]{0,4}$/
11
+
12
+ /**
13
+ * Parse the two retention settings. Unset or empty means the default; anything but a whole number of days from 1 to
14
+ * 99999 is refused, so a typo fails the boot instead of pruning at a value nobody chose.
15
+ */
16
+ export function parseRetention(
17
+ raw: { authLogDays: string | undefined; auditDays: string | undefined },
18
+ names: { authLogDays: string; auditDays: string } = { authLogDays: 'AUTH_LOG_RETENTION_DAYS', auditDays: 'AUDIT_RETENTION_DAYS' },
19
+ ): Retention {
20
+ return {
21
+ authLogDays: parseDays(names.authLogDays, raw.authLogDays) ?? DEFAULT_AUTH_LOG_RETENTION_DAYS,
22
+ auditDays: parseDays(names.auditDays, raw.auditDays),
23
+ }
24
+ }
25
+
26
+ function parseDays(name: string, raw: string | undefined): number | null {
27
+ if (raw === undefined || raw.trim() === '') {
28
+ return null
29
+ }
30
+ if (!DAYS.test(raw.trim())) {
31
+ throw new Error(`${name} must be a whole number of days from 1 to 99999`)
32
+ }
33
+ return Number.parseInt(raw.trim(), 10)
34
+ }
package/src/roles.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { RoleDef, RoleSource } from '@fabrika/auth-core'
2
+
3
+ /**
4
+ * Roles now live in the DB, per app (the `roles` table) — each app declares its own
5
+ * vocabulary and reconciles it in. The ONE exception is a built-in, cross-app role
6
+ * kept in code: `admin = ['*']`. It must resolve for ANY app (including app=null, the
7
+ * cross-app / bootstrap path), so it can't sit in a per-app DB table. Everything else
8
+ * is loaded from `roles` for the calling app and layered under the built-ins.
9
+ *
10
+ * `grants.role_key` is plain TEXT (no FK — a grant may set app=NULL while a roles row
11
+ * always has a concrete app). Validate the key at write time against the built-ins OR
12
+ * the app's `roles` rows; a key that resolves to nothing at read time confers zero
13
+ * permissions (fail-closed) and shows as dangling.
14
+ *
15
+ * Its keys are `BUILTIN_ROLE_KEYS` (`@fabrika/auth-core`), which the schema parser reserves; a test pins the two.
16
+ */
17
+ export const BUILTIN_ROLES: Record<string, RoleDef> = {
18
+ admin: { name: 'Admin', permissions: ['*'] },
19
+ }
20
+
21
+ /**
22
+ * Build a request-scoped `RoleSource` over the built-ins layered on top of an app's
23
+ * DB roles, already loaded into `appRoles` (role_key -> def). Resolution stays PURE:
24
+ * the caller fetches the rows up front and hands them in, so `computePermissions`
25
+ * does no I/O. `getRole`/`listRoles` ignore the `app` arg for matching (the map is
26
+ * already the calling app's roles); it is part of the `RoleSource` contract so a
27
+ * future multi-app source could honor it.
28
+ *
29
+ * Lookup order in `getRole`: built-ins first (so `admin` resolves for every app,
30
+ * incl. app=null), then the app's DB roles. `listRoles` unions both, built-ins last
31
+ * so an app cannot shadow the cross-app `admin`.
32
+ */
33
+ export function makeRoleSource(appRoles: Record<string, RoleDef>): RoleSource {
34
+ return {
35
+ getRole(_app: string | null, key: string): RoleDef | undefined {
36
+ if (Object.hasOwn(BUILTIN_ROLES, key)) {
37
+ return BUILTIN_ROLES[key]
38
+ }
39
+ // Object.hasOwn guards against prototype keys ('constructor', etc.).
40
+ return Object.hasOwn(appRoles, key) ? appRoles[key] : undefined
41
+ },
42
+ listRoles(_app: string | null): Record<string, RoleDef> {
43
+ return { ...appRoles, ...BUILTIN_ROLES }
44
+ },
45
+ }
46
+ }
47
+
48
+ /**
49
+ * True iff `key` is a known role for `appRoles` — a built-in (e.g. `admin`) OR a row
50
+ * in the app's loaded `roles`. The grant/mapping validation gate (app-aware).
51
+ */
52
+ export function isKnownRole(key: string, appRoles: Record<string, RoleDef>): boolean {
53
+ return Object.hasOwn(BUILTIN_ROLES, key) || Object.hasOwn(appRoles, key)
54
+ }