@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,267 @@
1
+ // IAM's deploy surface. This file owns its environment contract and Cloudflare resource graph.
2
+ // fabrika loads the default `defineApp` config; the local Oblaka entry imports the same builder.
3
+ //
4
+ // Non-secret deploy vars come from fabrika's per-app environment registry. Native-auth secrets are
5
+ // validated before remote materialization but never enter Worker `vars`, where Oblaka would serialize
6
+ // them as plaintext. The Custom Domain route comes from `ctx.domain` (`FABRIKA_IAM_HOSTNAME` in the
7
+ // standalone Oblaka adapter).
8
+
9
+ import { type EmailTransportConfig, readEmailTransportConfig } from '@fabrika/email'
10
+ import { isHttpOrigin } from '@fabrika/email/platform'
11
+ import { builtinEmailProviders } from '@fabrika/email/providers'
12
+ import { D1Database, defineApp, platformNames, type ResourceContext, Worker } from '@fabrika/provider-cloudflare'
13
+
14
+ // Keep the legacy Oblaka namespace so the first fabrika deploy continues the existing cf-state.
15
+ const IAM_APP_ID = 'propustka'
16
+
17
+ const KNOWN_ENVS = new Set(['local', 'stage', 'prod'])
18
+
19
+ type EnvironmentSource = Readonly<Record<string, string | undefined>>
20
+
21
+ interface RemoteConfig {
22
+ domain: string
23
+ humanEmailDomains: string
24
+ /** Absent when the deploy var is unset — IAM then defaults to the console's own app id. */
25
+ adminAudiences?: string
26
+ oidcEnabled: boolean
27
+ passwordEnabled: boolean
28
+ oidcIssuer: string
29
+ oidcClientId: string
30
+ email: EmailTransportConfig
31
+ /** Control's public origin, which IAM's mail goes through when set; absent keeps IAM on its own provider. */
32
+ controlUrl?: string
33
+ }
34
+
35
+ interface AuthenticationConfig {
36
+ oidcEnabled: boolean
37
+ passwordEnabled: boolean
38
+ }
39
+
40
+ const requiredDomain = (domain: string | undefined): string => {
41
+ if (domain === undefined || domain === '') {
42
+ throw new Error('Missing FABRIKA_IAM_HOSTNAME')
43
+ }
44
+ return domain
45
+ }
46
+
47
+ const booleanValue = (source: EnvironmentSource, name: string, fallback: boolean): boolean => {
48
+ const raw = source[name]
49
+ if (raw === undefined || raw === '') return fallback
50
+ if (raw === 'true') return true
51
+ if (raw === 'false') return false
52
+ throw new Error(`${name} must be true or false`)
53
+ }
54
+
55
+ const authenticationConfig = (source: EnvironmentSource): AuthenticationConfig => {
56
+ const config = {
57
+ oidcEnabled: booleanValue(source, 'FABRIKA_IAM_OIDC_ENABLED', true),
58
+ passwordEnabled: booleanValue(source, 'FABRIKA_IAM_PASSWORD_ENABLED', false),
59
+ }
60
+ if (!config.oidcEnabled && !config.passwordEnabled) {
61
+ throw new Error('At least one IAM authentication method must be enabled')
62
+ }
63
+ return config
64
+ }
65
+
66
+ /** Refuses an unknown provider and lists every missing or invalid `FABRIKA_EMAIL_*` variable, never a value. */
67
+ const emailConfig = (source: EnvironmentSource): EmailTransportConfig => readEmailTransportConfig(source, builtinEmailProviders)
68
+
69
+ /** The transport as plaintext Worker vars: the sender split into address and name, and the provider's non-secret variables. */
70
+ const emailVars = (email: EmailTransportConfig, source: EnvironmentSource): Record<string, string> => {
71
+ if (email.kind === 'none') return { FABRIKA_EMAIL_PROVIDER: 'none' }
72
+ const vars: Record<string, string> = { FABRIKA_EMAIL_PROVIDER: email.provider, FABRIKA_EMAIL_FROM: email.from.address }
73
+ if (email.from.name !== undefined) vars['FABRIKA_EMAIL_FROM_NAME'] = email.from.name
74
+ for (const variable of email.variables) {
75
+ const value = source[variable.name]
76
+ if (!variable.secret && value !== undefined && value !== '') vars[variable.name] = value
77
+ }
78
+ return vars
79
+ }
80
+
81
+ const emailVariableNames = (email: EmailTransportConfig, secret: boolean): string[] =>
82
+ email.kind === 'none' ? [] : email.variables.filter((variable) => variable.secret === secret).map((variable) => variable.name)
83
+
84
+ /**
85
+ * `FABRIKA_CONTROL_URL` as an https origin, or undefined when unset. IAM's Worker reaches Control across the internet
86
+ * with a key that sends mail past the relay's gate, so never in cleartext. The relay knows IAM by a key derived from the
87
+ * provisioning key, so the origin without that key would leave the relay unused.
88
+ */
89
+ const controlUrl = (source: EnvironmentSource): string | undefined => {
90
+ const raw = source['FABRIKA_CONTROL_URL']
91
+ if (raw === undefined || raw === '') return undefined
92
+ if (!isHttpOrigin(raw) || !raw.startsWith('https://')) {
93
+ throw new Error('FABRIKA_CONTROL_URL must be an https origin, with no path and no trailing slash')
94
+ }
95
+ if (!source['FABRIKA_IAM_PROVISIONING_KEY']?.trim()) {
96
+ throw new Error('FABRIKA_CONTROL_URL needs FABRIKA_IAM_PROVISIONING_KEY, which the mail relay authenticates IAM by')
97
+ }
98
+ return raw
99
+ }
100
+
101
+ const remoteConfig = (env: string, domain: string | undefined, source: EnvironmentSource): RemoteConfig => {
102
+ const authentication = authenticationConfig(source)
103
+ const email = emailConfig(source)
104
+ const control = controlUrl(source)
105
+ const humanEmailDomains = source['FABRIKA_IAM_HUMAN_EMAIL_DOMAINS']
106
+ const oidcIssuer = source['FABRIKA_IAM_OIDC_ISSUER']
107
+ const oidcClientId = source['FABRIKA_IAM_OIDC_CLIENT_ID']
108
+ const signingKeys = source['FABRIKA_IAM_SIGNING_KEYS']
109
+ const adminAudiences = source['FABRIKA_IAM_ADMIN_AUDIENCES']
110
+ const missing: string[] = []
111
+ if (authentication.oidcEnabled) {
112
+ if (!humanEmailDomains) missing.push('FABRIKA_IAM_HUMAN_EMAIL_DOMAINS')
113
+ if (!oidcIssuer) missing.push('FABRIKA_IAM_OIDC_ISSUER')
114
+ if (!oidcClientId) missing.push('FABRIKA_IAM_OIDC_CLIENT_ID')
115
+ if (!source['OIDC_CLIENT_SECRET']) missing.push('OIDC_CLIENT_SECRET')
116
+ }
117
+ if (!signingKeys) missing.push('FABRIKA_IAM_SIGNING_KEYS')
118
+ if (domain === undefined || domain === '') {
119
+ missing.push('FABRIKA_IAM_HOSTNAME')
120
+ }
121
+ if (missing.length > 0) {
122
+ throw new Error(`Missing ${missing.join(', ')} for env=${env}. Configure them before materializing IAM resources.`)
123
+ }
124
+
125
+ return {
126
+ domain: requiredDomain(domain),
127
+ humanEmailDomains: humanEmailDomains ?? '[]',
128
+ ...(adminAudiences === undefined ? {} : { adminAudiences }),
129
+ oidcEnabled: authentication.oidcEnabled,
130
+ passwordEnabled: authentication.passwordEnabled,
131
+ oidcIssuer: oidcIssuer ?? '',
132
+ oidcClientId: oidcClientId ?? '',
133
+ email,
134
+ ...(control === undefined ? {} : { controlUrl: control }),
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Build IAM's Worker vars. Remote secrets are validated above but excluded here because
140
+ * Oblaka serializes this object into the plaintext `vars` section of `wrangler.jsonc`.
141
+ */
142
+ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): Record<string, string> => {
143
+ if (config === 'local') {
144
+ return {
145
+ HUMAN_EMAIL_DOMAINS: '[]',
146
+ HUMAN_EMAILS: '[]',
147
+ IAM_BOOTSTRAP_ADMINS: '[]',
148
+ OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
149
+ ISSUER: 'http://localhost:18191',
150
+ // Password-only locally. OIDC is now FATAL when half-configured (one rule on both engines),
151
+ // and a `wrangler dev` has no client id or secret to give it.
152
+ OIDC_ENABLED: 'false',
153
+ PASSWORD_ENABLED: 'true',
154
+ OIDC_ISSUER: '',
155
+ OIDC_CLIENT_ID: '',
156
+ OIDC_SCOPES: '',
157
+ OIDC_REQUIRE_VERIFIED_EMAIL: 'true',
158
+ FABRIKA_EMAIL_PROVIDER: 'none',
159
+ }
160
+ }
161
+
162
+ return {
163
+ HUMAN_EMAIL_DOMAINS: config.humanEmailDomains,
164
+ OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
165
+ // Only when named: an empty ADMIN_AUDIENCES means "no JWT may administer", so a `?? ''`
166
+ // default would lock the console out of every install instead of falling back to its app id.
167
+ ...(config.adminAudiences === undefined ? {} : { ADMIN_AUDIENCES: config.adminAudiences }),
168
+ ...retentionVars(source),
169
+ HUMAN_EMAILS: source['FABRIKA_IAM_HUMAN_EMAILS'] ?? '[]',
170
+ IAM_BOOTSTRAP_ADMINS: source['FABRIKA_IAM_BOOTSTRAP_ADMINS'] ?? '[]',
171
+ ISSUER: `https://${config.domain}`,
172
+ OIDC_ENABLED: String(config.oidcEnabled),
173
+ PASSWORD_ENABLED: String(config.passwordEnabled),
174
+ OIDC_ISSUER: config.oidcIssuer,
175
+ OIDC_CLIENT_ID: config.oidcClientId,
176
+ OIDC_SCOPES: source['FABRIKA_IAM_OIDC_SCOPES'] ?? '',
177
+ OIDC_REQUIRE_VERIFIED_EMAIL: source['FABRIKA_IAM_OIDC_REQUIRE_VERIFIED_EMAIL'] ?? 'true',
178
+ ...emailVars(config.email, source),
179
+ ...(config.controlUrl === undefined ? {} : { FABRIKA_CONTROL_URL: config.controlUrl }),
180
+ }
181
+ }
182
+
183
+ /** The operator's retention settings, only where set: unset keeps IAM's defaults (30 days, audit kept). */
184
+ const retentionVars = (source: EnvironmentSource): Record<string, string> => {
185
+ const authLog = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
186
+ const audit = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
187
+ return {
188
+ ...(authLog === undefined || authLog === '' ? {} : { AUTH_LOG_RETENTION_DAYS: authLog }),
189
+ ...(audit === undefined || audit === '' ? {} : { AUDIT_RETENTION_DAYS: audit }),
190
+ }
191
+ }
192
+
193
+ export const iamPipelineVars = (source: EnvironmentSource): string[] => {
194
+ const authentication = authenticationConfig(source)
195
+ const email = emailConfig(source)
196
+ return [
197
+ 'FABRIKA_IAM_ADMIN_AUDIENCES',
198
+ 'FABRIKA_IAM_OAUTH_CONFIG',
199
+ 'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS',
200
+ 'FABRIKA_IAM_AUDIT_RETENTION_DAYS',
201
+ 'FABRIKA_IAM_OIDC_ENABLED',
202
+ 'FABRIKA_IAM_PASSWORD_ENABLED',
203
+ 'FABRIKA_EMAIL_PROVIDER',
204
+ 'FABRIKA_CONTROL_URL',
205
+ ...(authentication.oidcEnabled
206
+ ? ['FABRIKA_IAM_HUMAN_EMAIL_DOMAINS', 'FABRIKA_IAM_OIDC_ISSUER', 'FABRIKA_IAM_OIDC_CLIENT_ID']
207
+ : []),
208
+ ...(email.kind === 'provider' ? ['FABRIKA_EMAIL_FROM', 'FABRIKA_EMAIL_FROM_NAME', ...emailVariableNames(email, false)] : []),
209
+ ]
210
+ }
211
+
212
+ export const iamPipelineSecrets = (source: EnvironmentSource): string[] => {
213
+ const authentication = authenticationConfig(source)
214
+ const email = emailConfig(source)
215
+ return [
216
+ 'FABRIKA_IAM_SIGNING_KEYS',
217
+ 'FABRIKA_IAM_PROVISIONING_KEY',
218
+ ...(authentication.oidcEnabled ? ['OIDC_CLIENT_SECRET'] : []),
219
+ ...emailVariableNames(email, true),
220
+ ]
221
+ }
222
+
223
+ /**
224
+ * Build IAM's only Cloudflare resource graph. Both fabrika and the standalone Oblaka adapter
225
+ * call this function.
226
+ */
227
+ export const buildIamWorker = (ctx: ResourceContext, source: EnvironmentSource = process.env): Worker => {
228
+ const { env } = ctx
229
+ if (!KNOWN_ENVS.has(env)) {
230
+ throw new Error(`Unknown environment ${env}`)
231
+ }
232
+
233
+ const runtimeConfig: RemoteConfig | 'local' = env === 'local' ? 'local' : remoteConfig(env, ctx.domain, source)
234
+ const domain = runtimeConfig === 'local' ? undefined : runtimeConfig.domain
235
+ const names = platformNames(source)
236
+
237
+ return new Worker({
238
+ dir: '.',
239
+ name: names.iamWorker,
240
+ main: './src/index.ts',
241
+ compatibility_flags: ['nodejs_compat_v2'],
242
+ compatibility_date: '2025-10-01',
243
+ // This is the public auth surface. Control reaches admin APIs over a service binding.
244
+ routes: domain === undefined ? [] : [{ pattern: domain, custom_domain: true }],
245
+ observability: { enabled: true },
246
+ // Daily prune of auth_log; see scheduled() in src/index.ts.
247
+ triggers: { crons: ['0 3 * * *'] },
248
+ bindings: {
249
+ DB: new D1Database({ name: names.iamDatabase, migrationsDir: './migrations', locationHint: 'weur' }),
250
+ },
251
+ vars: {
252
+ ENVIRONMENT: env,
253
+ ...buildVars(runtimeConfig, source),
254
+ },
255
+ })
256
+ }
257
+
258
+ export default defineApp({
259
+ id: IAM_APP_ID,
260
+ resources: buildIamWorker,
261
+ pipeline: {
262
+ workerDir: '.',
263
+ // Values stay in fabrika's vault and are provisioned out-of-band from Worker plaintext vars.
264
+ secrets: iamPipelineSecrets(process.env),
265
+ vars: iamPipelineVars(process.env),
266
+ },
267
+ })
@@ -0,0 +1,316 @@
1
+ -- IAM schema — SQLite/D1 dialect. `../migrations-postgres/0001_init.sql` states the same schema for
2
+ -- Postgres; add every later change to both sets.
3
+ --
4
+ -- Two concerns with opposite characteristics live here:
5
+ -- * policies — mutable current state, read on every request.
6
+ -- * audit — append-only history, written often, read rarely.
7
+ -- They are distinct table groups (logical separation, one D1) with different
8
+ -- retention: prune `auth_log` after weeks, keep `audit_events` long.
9
+ --
10
+ -- All self-owned string ids are UUIDv7 (time-sortable), generated in-Worker —
11
+ -- the TEXT id columns are never filled by SQL. `auth_log` is the one exception:
12
+ -- it uses a plain INTEGER rowid (densest table, cheapest insert, never FK'd) —
13
+ -- and deliberately NOT AUTOINCREMENT (the more expensive variant, no benefit here).
14
+ --
15
+ -- Timestamps (`created_at`, unix seconds) are NOT NULL with NO default: the writer
16
+ -- always binds them. `unixepoch()` does not exist in Postgres, so a DDL default would
17
+ -- pin this schema to SQLite; binding caller-side is the repo convention anyway (see
18
+ -- the root CLAUDE.md and @fabrika/platform's `sql.ts`).
19
+
20
+ -- ── Policies ────────────────────────────────────────────────────────────────
21
+
22
+ CREATE TABLE principals (
23
+ id TEXT PRIMARY KEY, -- UUIDv7, ours; STABLE — grants & audit reference this, never external_id
24
+ type TEXT NOT NULL CHECK (type IN ('user','service')),
25
+ external_id TEXT, -- IdP `sub` (user) / client_id (service). NULL = user INVITED, not yet claimed
26
+ email TEXT, -- users: the NORMALIZED mailbox, invite-match key + label source; NULL for services
27
+ label TEXT NOT NULL, -- email / token name, human-readable
28
+ disabled_at INTEGER, -- soft-disable, NULL = active
29
+ created_at INTEGER NOT NULL, -- unix seconds, bound by the writer (no DDL default — see header)
30
+ activated_at INTEGER -- set once a user claims (OIDC) or enrolls a password; services at creation
31
+ );
32
+
33
+ -- Status is derived: invited (external_id IS NULL) → claimed/active → disabled (disabled_at set).
34
+ -- external_id is NULL for invited-not-yet-claimed users, so a plain UNIQUE(type, external_id)
35
+ -- would treat those NULLs as distinct. Partial unique indexes (same pattern as grants):
36
+ CREATE UNIQUE INDEX idx_principals_uq_external ON principals(type, external_id)
37
+ WHERE external_id IS NOT NULL;
38
+ -- At most one user principal per email (the invite target, then the claimed identity):
39
+ CREATE UNIQUE INDEX idx_principals_uq_email ON principals(email)
40
+ WHERE type = 'user' AND email IS NOT NULL;
41
+
42
+ -- The seeded PROVISIONING identity. `resolveCaller` (src/auth.ts) resolves a bearer matching the
43
+ -- FABRIKA_IAM_PROVISIONING_KEY secret to a synthetic global admin with this id; the row exists so the
44
+ -- audit that key drives resolves its principal_id FK. A migration cannot bind a parameter, so
45
+ -- `created_at` is a fixed literal.
46
+ INSERT INTO principals (id, type, external_id, email, label, disabled_at, created_at, activated_at)
47
+ VALUES ('provisioning-admin', 'service', NULL, NULL, 'provisioning', NULL, 1782561600, 1782561600);
48
+
49
+ -- Reserves a normalized mailbox for exactly one user principal.
50
+ CREATE TABLE principal_email_claims (
51
+ normalized_email TEXT PRIMARY KEY,
52
+ principal_id TEXT NOT NULL UNIQUE REFERENCES principals(id) ON DELETE CASCADE
53
+ );
54
+
55
+ -- ── App-declared vocabulary (reconciled from each app's code) ───────────────
56
+
57
+ -- The scope DIMENSIONS an app understands. Opaque to authz (scope matching is string equality); this
58
+ -- exists so the admin UI offers a real dropdown per app.
59
+ CREATE TABLE app_scopes (
60
+ app TEXT NOT NULL,
61
+ scope_type TEXT NOT NULL, -- 'organization' | 'team' | 'project' | …
62
+ label TEXT, -- human label for the admin UI
63
+ PRIMARY KEY (app, scope_type)
64
+ );
65
+
66
+ -- The ACTION CATALOG per app — every concrete action the app authorizes against.
67
+ CREATE TABLE app_actions (
68
+ app TEXT NOT NULL,
69
+ action TEXT NOT NULL, -- concrete action, e.g. 'project.read'
70
+ description TEXT,
71
+ PRIMARY KEY (app, action)
72
+ );
73
+
74
+ -- Named permission BUNDLES. JSON validity is NOT a DB constraint: `json_valid()` is SQLite-only and
75
+ -- `IS JSON` is Postgres-only, so the only writer JSON-encodes and every reader goes through
76
+ -- `parseJsonOrNull` (src/json.ts).
77
+ CREATE TABLE roles (
78
+ app TEXT NOT NULL,
79
+ role_key TEXT NOT NULL,
80
+ name TEXT NOT NULL,
81
+ description TEXT,
82
+ permissions TEXT NOT NULL, -- JSON array of action patterns
83
+ origin TEXT NOT NULL CHECK (origin IN ('app', 'custom')), -- 'app'=reconciled from code, 'custom'=admin-made
84
+ created_at INTEGER NOT NULL,
85
+ PRIMARY KEY (app, role_key)
86
+ );
87
+
88
+ -- Return origins an app registered for the cross-host session handoff (ADR-0021).
89
+ CREATE TABLE app_return_origins (
90
+ app TEXT NOT NULL,
91
+ origin TEXT NOT NULL, -- canonical scheme://host[:port], lower-cased, no trailing slash
92
+ created_at INTEGER NOT NULL,
93
+ PRIMARY KEY (app, origin)
94
+ );
95
+
96
+ -- ── grants ──────────────────────────────────────────────────────────────────
97
+ --
98
+ -- Scope is the generic, flat (scope_type, scope_value) pair. A grant is EITHER role-based OR inline,
99
+ -- never both, never neither. role_key is deliberately NOT FK'd to roles(app, role_key): a grant may
100
+ -- set app=NULL (cross-app) while a role row always has a concrete app.
101
+ CREATE TABLE grants (
102
+ id TEXT PRIMARY KEY, -- UUIDv7
103
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
104
+ app TEXT, -- NULL = all apps (cross-app, e.g. super-admin)
105
+ role_key TEXT, -- named role/policy; XOR permissions
106
+ permissions TEXT, -- inline action set (JSON array); XOR role_key. No json_valid CHECK — see roles above.
107
+ scope_type TEXT, -- NULL = global (all scopes)
108
+ scope_value TEXT, -- opaque, app-owned; NULL = global
109
+ granted_by TEXT REFERENCES principals(id),
110
+ expires_at INTEGER, -- NULL = permanent
111
+ created_at INTEGER NOT NULL,
112
+ CHECK ((role_key IS NULL) <> (permissions IS NULL)), -- exactly one of role_key / inline permissions
113
+ CHECK ((scope_type IS NULL) = (scope_value IS NULL)) -- scope is both-or-neither
114
+ );
115
+
116
+ -- `ON CONFLICT` infers its target from the index predicate + expression list, so these must stay
117
+ -- character-for-character equal to the Postgres set. They constrain ONLY role-based grants. NULL app
118
+ -- folds to '*' because raw NULLs compare as distinct in a unique index.
119
+ CREATE UNIQUE INDEX idx_grants_uq_scoped ON grants(principal_id, role_key, scope_type, scope_value, COALESCE(app, '*'))
120
+ WHERE role_key IS NOT NULL AND scope_value IS NOT NULL;
121
+ CREATE UNIQUE INDEX idx_grants_uq_global ON grants(principal_id, role_key, COALESCE(app, '*'))
122
+ WHERE role_key IS NOT NULL AND scope_value IS NULL;
123
+ CREATE INDEX idx_grants_principal ON grants(principal_id);
124
+
125
+ -- ── Credentials (unified opaque API keys / share links) ─────────────────────
126
+ --
127
+ -- An opaque `px_` secret (only its SHA-256 hash kept) resolved into a short signed access token.
128
+ -- principal_id set → the credential carries that principal's LIVE permissions; principal_id NULL → an
129
+ -- anonymous credential whose FROZEN inline grants, bound to `app`, are the whole permission set.
130
+ CREATE TABLE credentials (
131
+ id TEXT PRIMARY KEY, -- UUIDv7, ours
132
+ token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the opaque `px_` secret; never plaintext
133
+ label TEXT, -- human-readable, e.g. 'opice CI — ingest'
134
+ principal_id TEXT REFERENCES principals(id) ON DELETE CASCADE, -- NULL = anonymous (frozen inline grants)
135
+ issued_by TEXT REFERENCES principals(id), -- resolved server-side at issue, never self-asserted
136
+ expires_at INTEGER, -- absolute expiry (unix seconds); NULL = no expiry
137
+ revoked_at INTEGER, -- explicit revoke; NULL = active
138
+ created_at INTEGER NOT NULL, -- unix seconds, bound by the writer
139
+ app TEXT -- the app it was issued for; an anonymous credential without one never resolves
140
+ );
141
+
142
+ CREATE INDEX idx_credentials_principal ON credentials(principal_id);
143
+ CREATE INDEX idx_credentials_expires ON credentials(expires_at);
144
+ CREATE INDEX idx_credentials_app ON credentials(app);
145
+
146
+ -- What an inline-grant credential confers: 1..N (action, scope) entries, matched by permits().
147
+ CREATE TABLE credential_grants (
148
+ credential_id TEXT NOT NULL REFERENCES credentials(id) ON DELETE CASCADE,
149
+ action TEXT NOT NULL,
150
+ scope_type TEXT,
151
+ scope_value TEXT,
152
+ CHECK ((scope_type IS NULL) = (scope_value IS NULL))
153
+ );
154
+
155
+ CREATE INDEX idx_credential_grants_credential ON credential_grants(credential_id);
156
+
157
+ -- ── Audit ───────────────────────────────────────────────────────────────────
158
+
159
+ CREATE TABLE audit_events (
160
+ id TEXT PRIMARY KEY, -- UUIDv7 = time-sortable
161
+ request_id TEXT NOT NULL, -- correlates with auth log
162
+ principal_id TEXT REFERENCES principals(id) ON DELETE SET NULL,
163
+ principal_label TEXT NOT NULL, -- SNAPSHOT, survives principal deletion
164
+ credential_id TEXT, -- set when acting under a credential; principal_id is NULL then
165
+ app TEXT NOT NULL, -- self-asserted caller id (audit() carries no token)
166
+ action TEXT NOT NULL, -- 'project.settings.update'
167
+ resource_type TEXT NOT NULL, -- 'project'
168
+ resource_id TEXT,
169
+ -- diff/metadata hold JSON text. There is no JSON-validity predicate in the SQLite ∩ Postgres
170
+ -- common subset (`json_valid()` is SQLite-only, `IS JSON` is Postgres-only), so validity is
171
+ -- NOT a DB constraint: the only writer JSON-encodes, and the admin read path parses
172
+ -- defensively (`parseJsonOrNull`, src/json.ts) so a hand-written row can't 500 the API.
173
+ diff TEXT, -- {"field":["old","new"]}
174
+ metadata TEXT,
175
+ created_at INTEGER NOT NULL
176
+ );
177
+
178
+ CREATE INDEX idx_audit_resource ON audit_events(resource_type, resource_id, created_at);
179
+ CREATE INDEX idx_audit_principal ON audit_events(principal_id, created_at);
180
+ CREATE INDEX idx_audit_request ON audit_events(request_id);
181
+
182
+ CREATE TABLE auth_log (
183
+ -- SQLite's rowid alias; the Postgres set spells it `BIGINT GENERATED BY DEFAULT AS IDENTITY`
184
+ -- (writeAuthLog omits `id`).
185
+ id INTEGER PRIMARY KEY,
186
+ request_id TEXT NOT NULL,
187
+ app TEXT NOT NULL,
188
+ kind TEXT NOT NULL CHECK (kind IN ('authenticate')),
189
+ principal_id TEXT REFERENCES principals(id) ON DELETE SET NULL,
190
+ credential_id TEXT,
191
+ decision TEXT NOT NULL CHECK (decision IN ('allow','deny')),
192
+ reason TEXT,
193
+ created_at INTEGER NOT NULL
194
+ );
195
+
196
+ CREATE INDEX idx_auth_log_principal ON auth_log(principal_id, created_at);
197
+ CREATE INDEX idx_auth_log_request ON auth_log(request_id);
198
+
199
+ -- ── Sessions ────────────────────────────────────────────────────────────────
200
+ --
201
+ -- The long-lived opaque credential a browser carries; only the SHA-256 hash of the cookie value is
202
+ -- stored. `app` NULL marks an IAM session (held on IAM's own host); non-NULL marks a child session the
203
+ -- proxy holds on ONE app's host. Revoking the parent revokes every child derived from it.
204
+ CREATE TABLE sessions (
205
+ id TEXT PRIMARY KEY,
206
+ token_hash TEXT NOT NULL UNIQUE,
207
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
208
+ idp_sub TEXT,
209
+ email TEXT,
210
+ authentication_method TEXT NOT NULL CHECK (authentication_method IN ('oidc', 'password', 'local_dev')),
211
+ created_at INTEGER NOT NULL,
212
+ expires_at INTEGER NOT NULL,
213
+ revoked_at INTEGER,
214
+ app TEXT,
215
+ parent_session_id TEXT REFERENCES sessions(id) ON DELETE CASCADE,
216
+ CHECK (
217
+ (authentication_method IN ('oidc', 'local_dev') AND idp_sub IS NOT NULL)
218
+ OR (authentication_method = 'password' AND idp_sub IS NULL)
219
+ )
220
+ );
221
+
222
+ CREATE INDEX idx_sessions_principal ON sessions(principal_id);
223
+ CREATE INDEX idx_sessions_expires ON sessions(expires_at);
224
+ CREATE INDEX idx_sessions_principal_method ON sessions(principal_id, authentication_method);
225
+ CREATE INDEX idx_sessions_parent ON sessions(parent_session_id);
226
+
227
+ -- One-time codes that hand a parent session over to an app host.
228
+ CREATE TABLE auth_codes (
229
+ id TEXT PRIMARY KEY, -- UUIDv7, minted caller-side
230
+ code_hash TEXT NOT NULL UNIQUE, -- SHA-256; the plaintext lives in one redirect
231
+ app TEXT NOT NULL,
232
+ parent_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
233
+ return_url TEXT NOT NULL, -- carried server-side so redemption cannot be pointed elsewhere
234
+ expires_at INTEGER NOT NULL,
235
+ consumed_at INTEGER,
236
+ created_at INTEGER NOT NULL
237
+ );
238
+
239
+ CREATE INDEX idx_auth_codes_expires ON auth_codes(expires_at);
240
+
241
+ -- ── Password authentication ─────────────────────────────────────────────────
242
+ --
243
+ -- Passwords, one-time action tokens, and login throttles are separate concerns. Only derived
244
+ -- password material and token/login-key hashes live in the database.
245
+
246
+ CREATE TABLE password_accounts (
247
+ principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
248
+ state TEXT NOT NULL CHECK (state IN ('disabled', 'pending', 'enabled')),
249
+ created_at INTEGER NOT NULL,
250
+ updated_at INTEGER NOT NULL
251
+ );
252
+
253
+ CREATE TABLE password_credentials (
254
+ principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
255
+ algorithm TEXT NOT NULL,
256
+ parameters TEXT NOT NULL,
257
+ salt TEXT NOT NULL,
258
+ password_hash TEXT NOT NULL,
259
+ created_at INTEGER NOT NULL,
260
+ updated_at INTEGER NOT NULL
261
+ );
262
+
263
+ CREATE TABLE password_action_tokens (
264
+ id TEXT PRIMARY KEY,
265
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
266
+ purpose TEXT NOT NULL CHECK (purpose IN ('enrollment', 'reset')),
267
+ token_hash TEXT NOT NULL UNIQUE,
268
+ issued_by TEXT REFERENCES principals(id) ON DELETE SET NULL,
269
+ expires_at INTEGER NOT NULL,
270
+ consumed_at INTEGER,
271
+ consumption_id TEXT UNIQUE,
272
+ created_at INTEGER NOT NULL
273
+ );
274
+
275
+ CREATE INDEX idx_password_action_tokens_principal ON password_action_tokens(principal_id, purpose);
276
+ CREATE INDEX idx_password_action_tokens_expires ON password_action_tokens(expires_at);
277
+ CREATE UNIQUE INDEX uq_password_action_tokens_active
278
+ ON password_action_tokens(principal_id, purpose) WHERE consumed_at IS NULL;
279
+
280
+ CREATE TABLE password_login_throttles (
281
+ login_key_hash TEXT PRIMARY KEY,
282
+ window_started_at INTEGER NOT NULL,
283
+ attempt_count INTEGER NOT NULL CHECK (attempt_count > 0),
284
+ blocked_until INTEGER,
285
+ updated_at INTEGER NOT NULL
286
+ );
287
+
288
+ CREATE INDEX idx_password_login_throttles_updated ON password_login_throttles(updated_at);
289
+
290
+ -- ── Device authorization (builder pairing) ──────────────────────────────────
291
+
292
+ CREATE TABLE device_authorizations (
293
+ id TEXT PRIMARY KEY,
294
+ app TEXT NOT NULL,
295
+ label TEXT NOT NULL,
296
+ permissions TEXT NOT NULL,
297
+ key_lifetime_seconds INTEGER NOT NULL CHECK (key_lifetime_seconds > 0 AND key_lifetime_seconds <= 2592000),
298
+ redemption_challenge TEXT NOT NULL,
299
+ approval_challenge TEXT NOT NULL,
300
+ expires_at INTEGER NOT NULL,
301
+ next_poll_at INTEGER NOT NULL,
302
+ status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'issued', 'denied', 'cancelled', 'authority_lost')),
303
+ approver_id TEXT,
304
+ consent_id TEXT UNIQUE,
305
+ scope_type TEXT,
306
+ scope_value TEXT,
307
+ key_expires_at INTEGER,
308
+ claim_id TEXT UNIQUE,
309
+ credential_id TEXT,
310
+ principal_id TEXT,
311
+ issued_at INTEGER,
312
+ created_at INTEGER NOT NULL
313
+ );
314
+
315
+ CREATE INDEX idx_device_authorizations_issuer ON device_authorizations (approver_id, app, id);
316
+ CREATE INDEX idx_device_authorizations_expiry ON device_authorizations (expires_at);
@@ -0,0 +1,38 @@
1
+ -- OAuth 2.1 authorization server for MCP clients (ADR-0049). Only hashes of codes and refresh
2
+ -- tokens are stored. A grant is one consent, bounded by the IAM session it was given under: it
3
+ -- cascades with that session's row, and every redemption re-checks the session is still live.
4
+ -- A grant is also the refresh-token family — one code per grant, so reuse revokes the grant.
5
+ CREATE TABLE oauth_grants (
6
+ id TEXT PRIMARY KEY,
7
+ principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
8
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
9
+ client_id TEXT NOT NULL,
10
+ app TEXT NOT NULL,
11
+ resource TEXT NOT NULL,
12
+ scopes TEXT NOT NULL,
13
+ created_at INTEGER NOT NULL,
14
+ expires_at INTEGER NOT NULL,
15
+ revoked_at INTEGER
16
+ );
17
+ CREATE INDEX idx_oauth_grants_session ON oauth_grants(session_id);
18
+ CREATE INDEX idx_oauth_grants_principal ON oauth_grants(principal_id);
19
+
20
+ CREATE TABLE oauth_codes (
21
+ token_hash TEXT PRIMARY KEY,
22
+ grant_id TEXT NOT NULL REFERENCES oauth_grants(id) ON DELETE CASCADE,
23
+ redirect_uri TEXT NOT NULL,
24
+ challenge TEXT NOT NULL,
25
+ expires_at INTEGER NOT NULL,
26
+ used_at INTEGER
27
+ );
28
+ CREATE INDEX idx_oauth_codes_grant ON oauth_codes(grant_id);
29
+ CREATE INDEX idx_oauth_codes_expires ON oauth_codes(expires_at);
30
+
31
+ CREATE TABLE oauth_refresh_tokens (
32
+ token_hash TEXT PRIMARY KEY,
33
+ grant_id TEXT NOT NULL REFERENCES oauth_grants(id) ON DELETE CASCADE,
34
+ expires_at INTEGER NOT NULL,
35
+ used_at INTEGER
36
+ );
37
+ CREATE INDEX idx_oauth_refresh_tokens_grant ON oauth_refresh_tokens(grant_id);
38
+ CREATE INDEX idx_oauth_refresh_tokens_expires ON oauth_refresh_tokens(expires_at);
@@ -0,0 +1,11 @@
1
+ -- Contract applications (ADR-0022 rule 6). A row marks an app whose schema was compiled from a
2
+ -- contract; IAM then refuses every wildcard action written for it. `putAppSchema` writes it in the
3
+ -- same batch as the vocabulary, so the flag and the roles it constrains never disagree.
4
+ CREATE TABLE contract_apps (
5
+ app TEXT PRIMARY KEY,
6
+ created_at INTEGER NOT NULL
7
+ );
8
+
9
+ -- A membership role is granted only in a value of this scope dimension, never globally. NULL for
10
+ -- every other role, which is every row written before this file.
11
+ ALTER TABLE roles ADD COLUMN member_scope TEXT;