@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
@@ -0,0 +1,416 @@
1
+ import { AUTH_HANDOFF_CHALLENGE_PARAM, AUTH_HANDOFF_STATE_PARAM } from '@fabrika/auth-core'
2
+ import { z } from 'zod'
3
+ import { actionLandingOrigin, type AppPresentation, installationPresentation, landingUrl, presentationFor } from '../app-presentation'
4
+ import { type AuditEventInput } from '../db'
5
+ import { normalizeEmailIdentity } from '../email-identity'
6
+
7
+ import { type RequestContext } from '../env'
8
+ import { type PasswordActionPurpose } from '../password-db'
9
+ import { passwordMinLength } from '../password-minimum'
10
+ import { authFailurePage, forgotPasswordPage, invalidActionPage, loginPage, setPasswordPage } from '../password-pages'
11
+ import { PASSWORD_MAX_CODE_POINTS, validatePassword } from '../password-policy'
12
+ import { deliverPasswordAction, issuePasswordAction } from '../password-service'
13
+ import { hashToken } from '../secret'
14
+ import { type Config, type Services } from '../services'
15
+ import type { AuthFailure } from './failure'
16
+ import { handoffOf, handoffRedirectOr, loginDestinationFields, readHandoff } from './handoff'
17
+ import { methodNotAllowed, readForm, sameOrigin, stringValue } from './http'
18
+ import { knownDeviceCookie, readKnownDevice } from './known-device'
19
+ import type { AuthEnv } from './oidc-flight'
20
+ import { issueSession, type LoginRefusal, refuseLogin } from './sessions'
21
+
22
+ const LOGIN_WINDOW_SECONDS = 15 * 60
23
+
24
+ const LOGIN_BLOCK_SECONDS = 15 * 60
25
+
26
+ const ACCOUNT_MAX_ATTEMPTS = 5
27
+
28
+ const GLOBAL_MAX_ATTEMPTS = 1_000
29
+
30
+ /** Attempts a known-device cookie may spend between successes before it stops exempting its login from the other buckets. */
31
+ const DEVICE_MAX_ATTEMPTS = 10
32
+
33
+ const RECOVERY_ACCOUNT_MAX_ATTEMPTS = 3
34
+
35
+ const RECOVERY_GLOBAL_MAX_ATTEMPTS = 100
36
+
37
+ /**
38
+ * The per-client buckets (WU-C, backlog 21 + 49). They sit between the account bucket and the
39
+ * deployment-wide one on purpose: the point is to stop ONE client exhausting the deployment-wide
40
+ * bucket and denying everyone, not to be a second account lockout. Generous enough that a shared
41
+ * office address logging in normally never reaches them; a client that does is not logging in.
42
+ */
43
+ const LOGIN_CLIENT_MAX_ATTEMPTS = 100
44
+
45
+ const RECOVERY_CLIENT_MAX_ATTEMPTS = 30
46
+
47
+ const emailSchema = z.string().transform(normalizeEmailIdentity).pipe(z.string().min(1).max(254).includes('@'))
48
+ const loginFormSchema = z.object({ email: emailSchema, password: z.string().transform((value) => value.normalize('NFC')) })
49
+ const passwordActionFormSchema = z.object({ token: z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/), password: z.string() })
50
+
51
+ /**
52
+ * The per-client bucket, and the reason it is shaped differently from the other two.
53
+ *
54
+ * The account and deployment-wide buckets READ first and record a failure afterwards, which is a
55
+ * check-then-act: a concurrent burst all reads "not blocked" and all proceeds. That is tolerable for a
56
+ * bucket whose key an attacker cannot pick freely; it is not tolerable for the one bucket whose whole
57
+ * job is to bound a burst. So this one is a single statement — `recordLoginFailure` is one
58
+ * `INSERT … ON CONFLICT DO UPDATE … RETURNING`, and the admission decision is read from ITS OWN
59
+ * returned row. Every concurrent request therefore observes its own increment and no request can be
60
+ * admitted on a count another has not yet written.
61
+ *
62
+ * It counts every ATTEMPT, not every failure, for the same reason: a decision made before the work
63
+ * cannot know the outcome. A successful login never clears it either — clearing on success would let
64
+ * an attacker who holds one valid credential reset the bucket between bursts.
65
+ *
66
+ * `null` (this composition cannot see the client) records nothing and blocks nothing.
67
+ */
68
+ async function clientBlocked(
69
+ services: Services,
70
+ purpose: 'password-login' | 'password-recovery',
71
+ clientAddress: string | null,
72
+ maxAttempts: number,
73
+ ): Promise<boolean> {
74
+ if (clientAddress === null) return false
75
+ // Hashed like every other key here: the throttle table must never hold a client address in the clear.
76
+ return attemptBlocked(services, await hashToken(`${purpose}:client:${clientAddress}`), maxAttempts)
77
+ }
78
+
79
+ /**
80
+ * Record one attempt and decide admission from the row that statement returns, so a concurrent burst cannot pass the
81
+ * limit (see `clientBlocked`). The attempt that reaches `maxAttempts` is the first one refused.
82
+ */
83
+ async function attemptBlocked(services: Services, loginKeyHash: string, maxAttempts: number): Promise<boolean> {
84
+ const row = await services.repositories.passwords.recordLoginFailure({
85
+ loginKeyHash,
86
+ windowSeconds: LOGIN_WINDOW_SECONDS,
87
+ maxAttempts,
88
+ blockSeconds: LOGIN_BLOCK_SECONDS,
89
+ })
90
+ return (row.blocked_until ?? 0) > Math.floor(Date.now() / 1000)
91
+ }
92
+
93
+ export async function handlePasswordLogin(
94
+ request: Request,
95
+ services: Services,
96
+ env: AuthEnv,
97
+ ctx: RequestContext,
98
+ clientAddress: string | null,
99
+ requestId: string,
100
+ ): Promise<Response> {
101
+ if (!services.config.authentication.password.enabled) {
102
+ return authFailurePage(await installationPresentation(services, { request }), { kind: 'password_disabled' }, 404)
103
+ }
104
+ // Before the form is read no application is known, so these refusals speak the reader's language.
105
+ const refused = (reason: LoginRefusal, failure: AuthFailure, status: number) =>
106
+ refuseLogin(
107
+ services,
108
+ request,
109
+ { requestId, principalId: null, reason },
110
+ async () => authFailurePage(await installationPresentation(services, { request }), failure, status),
111
+ )
112
+ if (!sameOrigin(request, services.config)) return refused('login_cross_origin', { kind: 'cross_origin' }, 403)
113
+ const form = await readForm(request)
114
+ if (form === null) return refused('password_malformed', { kind: 'malformed_form' }, 400)
115
+ const login = loginFormSchema.safeParse({ email: form.get('email'), password: form.get('password') })
116
+ // The form is a hint, not a permission: `readHandoff` re-checks the return URL against what the app
117
+ // has registered, so a hand-edited field buys nothing.
118
+ const reading = await readHandoff(
119
+ services,
120
+ stringValue(form.get('app')),
121
+ stringValue(form.get('redirect')),
122
+ stringValue(form.get(AUTH_HANDOFF_STATE_PARAM)),
123
+ stringValue(form.get(AUTH_HANDOFF_CHALLENGE_PARAM)),
124
+ )
125
+ if (reading.kind === 'refused') {
126
+ const presentation = await presentationFor(services, stringValue(form.get('app')), { request })
127
+ return refuseLogin(
128
+ services,
129
+ request,
130
+ { requestId, principalId: null, reason: 'handoff_refused' },
131
+ () => authFailurePage(presentation, reading.failure, 400),
132
+ )
133
+ }
134
+ const handoff = handoffOf(reading)
135
+ const redirect = handoffRedirectOr(handoff, stringValue(form.get('redirect')), services)
136
+ const retry = {
137
+ presentation: await presentationFor(services, handoff?.app ?? null, { request }),
138
+ redirect,
139
+ oidcEnabled: services.config.authentication.oidc.enabled,
140
+ forgotEnabled: services.email !== null,
141
+ ...await loginDestinationFields(services, handoff, redirect),
142
+ }
143
+ if (!login.success) {
144
+ return refuseLogin(
145
+ services,
146
+ request,
147
+ { requestId, principalId: null, reason: 'password_malformed' },
148
+ () => loginPage({ ...retry, invalidCredentials: true }),
149
+ )
150
+ }
151
+ const { email, password } = login.data
152
+ const passwordWithinLimit = Array.from(password).length <= PASSWORD_MAX_CODE_POINTS
153
+
154
+ const accountKey = await hashToken(`password-login:account:${email}`)
155
+ const globalKey = await hashToken('password-login:global')
156
+ const [accountThrottle, globalThrottle, lookup, device] = await Promise.all([
157
+ services.repositories.passwords.getLoginThrottle(accountKey),
158
+ services.repositories.passwords.getLoginThrottle(globalKey),
159
+ services.repositories.passwords.lookupLogin(email),
160
+ readKnownDevice(env, request),
161
+ ])
162
+ const now = Math.floor(Date.now() / 1000)
163
+ // A device cookie of another principal is ignored, so it neither exempts nor reveals which address it belongs to.
164
+ const deviceKey = device !== null && lookup.status === 'found' && device.principalId === lookup.principal.id
165
+ ? await hashToken(`password-login:device:${device.deviceId}`)
166
+ : null
167
+ // Taken atomically, like the client bucket: a burst with one cookie gets exactly `DEVICE_MAX_ATTEMPTS` admitted.
168
+ const knownDevice = deviceKey !== null && !await attemptBlocked(services, deviceKey, DEVICE_MAX_ATTEMPTS + 1)
169
+ // A known device spends its own bucket instead of all three, so a client that fills them cannot lock it out.
170
+ const blocked = !knownDevice && (
171
+ await clientBlocked(services, 'password-login', clientAddress, LOGIN_CLIENT_MAX_ATTEMPTS)
172
+ || (accountThrottle?.blocked_until ?? 0) > now
173
+ || (globalThrottle?.blocked_until ?? 0) > now
174
+ )
175
+ let valid = false
176
+ let needsRehash = false
177
+ if (!blocked && passwordWithinLimit && lookup.status === 'found') {
178
+ const verification = await services.passwordHasher.verify(password, {
179
+ algorithm: lookup.credential.algorithm,
180
+ parameters: lookup.credential.parameters,
181
+ salt: lookup.credential.salt,
182
+ passwordHash: lookup.credential.password_hash,
183
+ })
184
+ valid = verification.valid
185
+ needsRehash = verification.needsRehash
186
+ } else if (!blocked) {
187
+ // Spend derivation work when the request is allowed but no verifier can run.
188
+ await services.passwordHasher.hash(passwordWithinLimit ? password : 'oversized-password-dummy')
189
+ }
190
+
191
+ if (!blocked && valid && lookup.status === 'found') {
192
+ if (needsRehash) {
193
+ // Replacing derived material deliberately revokes older password sessions.
194
+ await services.repositories.passwords.upsertCredential(
195
+ lookup.principal.id,
196
+ await services.passwordHasher.hash(password),
197
+ selfEvent(requestId, lookup.principal.id, 'iam.password.rehash'),
198
+ )
199
+ }
200
+ // The password is proven, so the device's attempts start over; the client bucket is never cleared.
201
+ await Promise.all([
202
+ services.repositories.passwords.clearLoginFailures(accountKey),
203
+ deviceKey === null ? Promise.resolve() : services.repositories.passwords.clearLoginFailures(deviceKey),
204
+ ])
205
+ const session = await issueSession(request, services, ctx, {
206
+ principalId: lookup.principal.id,
207
+ email: lookup.principal.email,
208
+ authenticationMethod: 'password',
209
+ redirect,
210
+ reason: 'password_login',
211
+ requestId,
212
+ handoff,
213
+ })
214
+ // Only a recorded login (the 302) earns a device cookie; a 503 issued no session.
215
+ if (session.status === 302) session.headers.append('Set-Cookie', await knownDeviceCookie(env, lookup.principal.id))
216
+ return session
217
+ }
218
+
219
+ // A known device's attempt is already counted in its own bucket.
220
+ if (!blocked && !knownDevice) {
221
+ await Promise.all([
222
+ recordLoginFailure(services, accountKey, ACCOUNT_MAX_ATTEMPTS),
223
+ recordLoginFailure(services, globalKey, GLOBAL_MAX_ATTEMPTS),
224
+ ])
225
+ }
226
+ return refuseLogin(
227
+ services,
228
+ request,
229
+ {
230
+ requestId,
231
+ principalId: lookup.status === 'found' ? lookup.principal.id : null,
232
+ reason: blocked ? 'password_throttled' : 'password_invalid',
233
+ },
234
+ () => loginPage({ ...retry, invalidCredentials: true }),
235
+ )
236
+ }
237
+
238
+ async function recordLoginFailure(services: Services, loginKeyHash: string, maxAttempts: number): Promise<void> {
239
+ await services.repositories.passwords.recordLoginFailure({
240
+ loginKeyHash,
241
+ windowSeconds: LOGIN_WINDOW_SECONDS,
242
+ maxAttempts,
243
+ blockSeconds: LOGIN_BLOCK_SECONDS,
244
+ })
245
+ }
246
+
247
+ export async function handleForgotPassword(
248
+ request: Request,
249
+ services: Services,
250
+ ctx: RequestContext,
251
+ clientAddress: string | null,
252
+ requestId: string,
253
+ ): Promise<Response> {
254
+ // The application the sign-in came from, named by the link and the form's `?app=`: the action keeps it, so the mail
255
+ // and the pages speak its language and the completed reset lands in it.
256
+ const presentation = await presentationFor(services, new URL(request.url).searchParams.get('app'), { request })
257
+ if (!services.config.authentication.password.enabled) return authFailurePage(presentation, { kind: 'password_disabled' }, 404)
258
+ if (request.method === 'GET') return forgotPasswordPage({ presentation })
259
+ if (request.method !== 'POST') return methodNotAllowed()
260
+ if (!sameOrigin(request, services.config)) return authFailurePage(presentation, { kind: 'cross_origin' }, 403)
261
+ const form = await readForm(request)
262
+ if (form === null) return authFailurePage(presentation, { kind: 'malformed_form' }, 400)
263
+ const sent = forgotPasswordPage({ presentation, sent: true })
264
+ const parsedEmail = emailSchema.safeParse(form.get('email'))
265
+ if (services.email === null || !parsedEmail.success) return sent
266
+ const email = parsedEmail.data
267
+ const accountKey = await hashToken(`password-recovery:account:${email}`)
268
+ const globalKey = await hashToken('password-recovery:global')
269
+ const [accountThrottle, globalThrottle, clientOverLimit] = await Promise.all([
270
+ services.repositories.passwords.getLoginThrottle(accountKey),
271
+ services.repositories.passwords.getLoginThrottle(globalKey),
272
+ clientBlocked(services, 'password-recovery', clientAddress, RECOVERY_CLIENT_MAX_ATTEMPTS),
273
+ ])
274
+ const now = Math.floor(Date.now() / 1000)
275
+ if (clientOverLimit || (accountThrottle?.blocked_until ?? 0) > now || (globalThrottle?.blocked_until ?? 0) > now) {
276
+ return sent
277
+ }
278
+ await Promise.all([
279
+ recordLoginFailure(services, accountKey, RECOVERY_ACCOUNT_MAX_ATTEMPTS),
280
+ recordLoginFailure(services, globalKey, RECOVERY_GLOBAL_MAX_ATTEMPTS),
281
+ ])
282
+ ctx.waitUntil(runForgotPassword(services, email, requestId, presentation).catch(() => console.error('Password recovery request failed')))
283
+ return sent
284
+ }
285
+
286
+ async function runForgotPassword(services: Services, email: string, requestId: string, presentation: AppPresentation): Promise<void> {
287
+ let lookup = await services.repositories.passwords.lookupActionUser(email)
288
+ if (
289
+ lookup.status === 'missing'
290
+ && !services.config.authentication.oidc.enabled
291
+ && matchingBootstrapEmail(email, services.config) !== null
292
+ ) {
293
+ const principal = await safelyCreateBootstrapPrincipal(services, email, requestId)
294
+ if (principal !== null) lookup = { status: 'found', principal, account: await services.repositories.passwords.getAccount(principal.id) }
295
+ }
296
+
297
+ if (lookup.status === 'found' && lookup.principal.disabled_at === null) {
298
+ let purpose: PasswordActionPurpose | null = null
299
+ if (lookup.account?.state === 'enabled') purpose = 'reset'
300
+ if (lookup.account?.state === 'pending') purpose = 'enrollment'
301
+ // A bootstrap admin's account is opted into enrollment in the batch that issues its token.
302
+ const bootstrap = lookup.account === null && !services.config.authentication.oidc.enabled
303
+ && matchingBootstrapEmail(email, services.config) !== null
304
+ if (bootstrap) purpose = 'enrollment'
305
+ if (purpose !== null) {
306
+ const action = await issuePasswordAction(services, { principal: lookup.principal, purpose, presentation }, {
307
+ audit: recoveryEvent(requestId, lookup.principal.id, `iam.password.${purpose}.issue`),
308
+ enableEnrollment: bootstrap,
309
+ })
310
+ await deliverPasswordAction(services, action)
311
+ }
312
+ }
313
+ }
314
+
315
+ async function safelyCreateBootstrapPrincipal(services: Services, email: string, requestId: string) {
316
+ // Re-check through the case-insensitive, ambiguity-detecting lookup before the unique insert.
317
+ const existing = await services.repositories.passwords.lookupActionUser(email)
318
+ if (existing.status === 'found') return existing.principal
319
+ if (existing.status === 'ambiguous') return null
320
+ const canonical = matchingBootstrapEmail(email, services.config)
321
+ if (canonical === null) return null
322
+ try {
323
+ // Its enrollment opt-in commits with the token `runForgotPassword` issues next.
324
+ return await services.repositories.principals.inviteUser(
325
+ canonical,
326
+ canonical,
327
+ (principalId) => recoveryEvent(requestId, principalId, 'iam.principal.bootstrap'),
328
+ )
329
+ } catch {
330
+ const raced = await services.repositories.passwords.lookupActionUser(canonical)
331
+ return raced.status === 'found' ? raced.principal : null
332
+ }
333
+ }
334
+
335
+ export async function handlePasswordAction(
336
+ request: Request,
337
+ services: Services,
338
+ ctx: RequestContext,
339
+ purpose: PasswordActionPurpose,
340
+ requestId: string,
341
+ ): Promise<Response> {
342
+ // The link's `?app=` is a hint for the page's words and its `form-action`; the stored action decides where it lands.
343
+ const linked = await presentationFor(services, new URL(request.url).searchParams.get('app'), { request })
344
+ if (!services.config.authentication.password.enabled) return authFailurePage(linked, { kind: 'password_disabled' }, 404)
345
+ const minLength = await passwordMinLength(services)
346
+ if (request.method === 'GET') {
347
+ return setPasswordPage({ presentation: linked, landingOrigin: await actionLandingOrigin(services, linked), purpose, minLength })
348
+ }
349
+ if (request.method !== 'POST') return methodNotAllowed()
350
+ if (!sameOrigin(request, services.config)) return authFailurePage(linked, { kind: 'cross_origin' }, 403)
351
+ const form = await readForm(request)
352
+ if (form === null) return authFailurePage(linked, { kind: 'malformed_form' }, 400)
353
+ const submitted = passwordActionFormSchema.safeParse({ token: form.get('token'), password: form.get('password') })
354
+ if (!submitted.success) return invalidActionPage(linked)
355
+ const { token: submittedToken, password } = submitted.data
356
+ const tokenHash = await hashToken(submittedToken)
357
+ const action = await services.repositories.passwords.inspectActionToken(tokenHash, purpose)
358
+ if (action === null) return invalidActionPage(linked)
359
+ const presentation = await presentationFor(services, action.app, { request, brand: linked.brand, locale: action.locale })
360
+ const principal = await services.repositories.principals.getPrincipalById(action.principal_id)
361
+ if (principal === null || principal.disabled_at !== null) return invalidActionPage(presentation)
362
+ const policy = validatePassword(password, minLength, { email: principal.email, label: principal.label })
363
+ if (!policy.ok) {
364
+ return setPasswordPage({
365
+ presentation,
366
+ landingOrigin: await actionLandingOrigin(services, presentation),
367
+ token: submittedToken,
368
+ purpose,
369
+ minLength,
370
+ problem: policy.problem,
371
+ })
372
+ }
373
+ const completed = await services.repositories.passwords.completeAction({
374
+ tokenHash,
375
+ purpose,
376
+ password: await services.passwordHasher.hash(policy.password),
377
+ }, selfEvent(requestId, principal.id, `iam.password.${purpose}.complete`))
378
+ if (completed === null) return invalidActionPage(presentation)
379
+ const completedPrincipal = await services.repositories.principals.getPrincipalById(completed.principalId)
380
+ if (completedPrincipal === null || completedPrincipal.disabled_at !== null) return invalidActionPage(presentation)
381
+ // An action that keeps an application lands on its registered origin, any other on the installation's landing
382
+ // (`issueSession`); that application's proxy then signs the browser in through the normal handoff, which the
383
+ // session issued here makes silent.
384
+ return issueSession(request, services, ctx, {
385
+ principalId: completedPrincipal.id,
386
+ email: completedPrincipal.email,
387
+ authenticationMethod: 'password',
388
+ redirect: landingUrl(presentation),
389
+ reason: purpose === 'enrollment' ? 'password_enrollment' : 'password_reset',
390
+ requestId,
391
+ })
392
+ }
393
+
394
+ function matchingBootstrapEmail(email: string, config: Config): string | null {
395
+ const normalized = normalizeEmailIdentity(email)
396
+ return config.bootstrapAdmins.has(normalized) ? normalized : null
397
+ }
398
+
399
+ /** The record of a change a principal made to its own credentials: by it, about it, and with no email in it. */
400
+ function selfEvent(requestId: string, principalId: string, action: string): AuditEventInput {
401
+ return { requestId, principalId, principalLabel: principalId, app: 'propustka', action, resourceType: 'principal', resourceId: principalId }
402
+ }
403
+
404
+ /** The record of a change a public recovery request made: no principal is signed in, so the actor is anonymous. */
405
+ function recoveryEvent(requestId: string, principalId: string, action: string): AuditEventInput {
406
+ return {
407
+ requestId,
408
+ principalId: null,
409
+ principalLabel: 'password-recovery',
410
+ app: 'propustka',
411
+ action,
412
+ resourceType: 'principal',
413
+ resourceId: principalId,
414
+ metadata: { delivery: 'email' },
415
+ }
416
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The public IAM-host auth surface. App session delivery uses a browser-bound handoff; `/auth/mint/*`
3
+ * is intercepted upstream by `src/app.ts` for the proxy. Admin admission belongs to `admin/router.ts`.
4
+ */
5
+ import { installationConsole } from '../app-presentation'
6
+ import type { RequestContext } from '../env'
7
+ import { TERMINAL_COMPLETE_PATH } from '../identification'
8
+ import { installationBrand } from '../installation-brand'
9
+ import { INVITATION_ACCEPT_PATH } from '../membership'
10
+ import { ACCOUNT_CHOICE_PATH, logoutPage, TERMINAL_ENROL_PATH } from '../password-pages'
11
+ import { readerLocale } from '../person-locale'
12
+ import { generateRequestId } from '../request-id'
13
+ import type { Services } from '../services'
14
+ import { getSigner } from '../signing'
15
+ import { methodNotAllowed, safeRedirect } from './http'
16
+ import { handleInvitation } from './invitations'
17
+ import { handleAccountChoice, handleLogin } from './login'
18
+ import { handleCallback, handleOidcStart } from './oidc'
19
+ import type { AuthEnv } from './oidc-flight'
20
+ import { handleForgotPassword, handlePasswordAction, handlePasswordLogin } from './password'
21
+ import { handleLogout } from './sessions'
22
+ import { handleTerminalCompletion, handleTerminalEnrolment, handleTerminalRelease, TERMINAL_RELEASE_PATH } from './terminals'
23
+
24
+ /**
25
+ * `clientAddress` is what the composition's ingress observed, or `null` when it cannot see a client
26
+ * (`src/client-address.ts`). It keys the per-client abuse bucket and NOTHING else — it is never an
27
+ * identity, never a credential, and never stored in the clear. Defaulting to `null` is deliberate: a
28
+ * caller that has not been given a trustworthy coordinate gets the account and deployment-wide buckets
29
+ * alone, which is what existed before, rather than one keyed on a guess.
30
+ *
31
+ * `requestId` is the correlation id the composition root allowed (`src/request-id.ts`); a caller that
32
+ * supplies none gets a generated one, never a header read here.
33
+ */
34
+ export async function handleAuth(
35
+ request: Request,
36
+ services: Services,
37
+ env: AuthEnv,
38
+ ctx: RequestContext,
39
+ clientAddress: string | null = null,
40
+ requestId: string = generateRequestId(),
41
+ ): Promise<Response> {
42
+ const url = new URL(request.url)
43
+
44
+ if (url.pathname === '/.well-known/jwks.json') {
45
+ return handleJwks(env)
46
+ }
47
+ if (url.pathname === '/auth/login') {
48
+ if (request.method === 'POST') return handlePasswordLogin(request, services, env, ctx, clientAddress, requestId)
49
+ if (request.method === 'GET') return handleLogin(request, services, env, ctx, requestId)
50
+ return methodNotAllowed()
51
+ }
52
+ if (url.pathname === ACCOUNT_CHOICE_PATH) {
53
+ return request.method === 'POST' ? handleAccountChoice(request, services, requestId) : methodNotAllowed()
54
+ }
55
+ if (url.pathname === '/auth/oidc/start') {
56
+ return request.method === 'GET' ? handleOidcStart(request, services, env) : methodNotAllowed()
57
+ }
58
+ if (url.pathname === '/auth/callback') {
59
+ return request.method === 'GET' ? handleCallback(request, services, env, ctx, requestId) : methodNotAllowed()
60
+ }
61
+ if (url.pathname === '/auth/forgot-password') {
62
+ return handleForgotPassword(request, services, ctx, clientAddress, requestId)
63
+ }
64
+ if (url.pathname === '/auth/password/enroll') {
65
+ return handlePasswordAction(request, services, ctx, 'enrollment', requestId)
66
+ }
67
+ if (url.pathname === '/auth/password/reset') {
68
+ return handlePasswordAction(request, services, ctx, 'reset', requestId)
69
+ }
70
+ if (url.pathname === INVITATION_ACCEPT_PATH) {
71
+ return handleInvitation(request, services, ctx, requestId)
72
+ }
73
+ if (url.pathname === TERMINAL_ENROL_PATH) {
74
+ return request.method === 'GET' || request.method === 'POST' ? handleTerminalEnrolment(request, services, requestId) : methodNotAllowed()
75
+ }
76
+ if (url.pathname === TERMINAL_COMPLETE_PATH) {
77
+ return request.method === 'GET' ? handleTerminalCompletion(request, services, requestId) : methodNotAllowed()
78
+ }
79
+ if (url.pathname === TERMINAL_RELEASE_PATH) {
80
+ return request.method === 'GET' ? handleTerminalRelease(request, services, requestId) : methodNotAllowed()
81
+ }
82
+ if (url.pathname === '/auth/logout') {
83
+ // Logging out is a state change, so it needs a method that can carry an origin check. A GET
84
+ // stays usable — it renders the same-origin form that posts — because a cross-site
85
+ // `location = '…/auth/logout'` used to revoke the login and every app session under it.
86
+ if (request.method === 'POST') return handleLogout(request, services, requestId)
87
+ if (request.method === 'GET') {
88
+ const redirect = safeRedirect(url.searchParams.get('redirect'), services.config)
89
+ return logoutPage({
90
+ redirect,
91
+ landingOrigin: redirect === null ? await installationConsole(services) : null,
92
+ brand: await installationBrand(services),
93
+ locale: readerLocale(request),
94
+ })
95
+ }
96
+ return methodNotAllowed()
97
+ }
98
+ return new Response('Not found', { status: 404 })
99
+ }
100
+
101
+ async function handleJwks(env: AuthEnv): Promise<Response> {
102
+ const signer = await getSigner(env)
103
+ return Response.json(signer.jwks(), {
104
+ headers: { 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },
105
+ })
106
+ }
107
+
108
+ export { safeRedirect } from './http'