@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.
- package/fabrika.config.ts +267 -0
- package/migrations/0001_init.sql +316 -0
- package/migrations/0002_oauth.sql +38 -0
- package/migrations/0003_contract_apps.sql +11 -0
- package/migrations/0004_membership.sql +93 -0
- package/migrations/0005_workloads.sql +23 -0
- package/migrations/0006_membership_transport_keys.sql +16 -0
- package/migrations/0007_member_directory.sql +7 -0
- package/migrations/0008_durable_audit.sql +28 -0
- package/migrations/0009_member_lookups.sql +7 -0
- package/migrations/0010_workload_issues.sql +6 -0
- package/migrations/0011_app_presentation.sql +15 -0
- package/migrations/0012_external_principals.sql +10 -0
- package/migrations/0013_app_mail_templates.sql +14 -0
- package/migrations/0014_invitation_wording.sql +8 -0
- package/migrations/0015_app_schema_revisions.sql +15 -0
- package/migrations/0016_principal_grant_revision.sql +9 -0
- package/migrations/0017_app_sign_ins.sql +12 -0
- package/migrations/0018_app_members.sql +13 -0
- package/migrations/0019_app_mail_html.sql +7 -0
- package/migrations/0020_public_workloads.sql +34 -0
- package/migrations/0021_installation_brand.sql +19 -0
- package/migrations/0022_password_policy.sql +12 -0
- package/migrations/0023_terminals.sql +155 -0
- package/migrations/0024_app_terminals.sql +10 -0
- package/migrations/0025_terminal_completion.sql +10 -0
- package/migrations/0026_terminal_generation.sql +12 -0
- package/migrations/0027_application_exact_actions.sql +28 -0
- package/migrations/0028_oauth_client_assertions.sql +10 -0
- package/migrations/0029_role_via.sql +6 -0
- package/migrations/0030_membership_role_via.sql +12 -0
- package/migrations/0031_person_locale.sql +11 -0
- package/migrations-postgres/0001_init.sql +331 -0
- package/migrations-postgres/0002_oauth.sql +36 -0
- package/migrations-postgres/0003_contract_apps.sql +8 -0
- package/migrations-postgres/0004_membership.sql +92 -0
- package/migrations-postgres/0005_workloads.sql +18 -0
- package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
- package/migrations-postgres/0007_member_directory.sql +7 -0
- package/migrations-postgres/0008_durable_audit.sql +8 -0
- package/migrations-postgres/0009_member_lookups.sql +7 -0
- package/migrations-postgres/0010_workload_issues.sql +6 -0
- package/migrations-postgres/0011_app_presentation.sql +15 -0
- package/migrations-postgres/0012_external_principals.sql +10 -0
- package/migrations-postgres/0013_app_mail_templates.sql +14 -0
- package/migrations-postgres/0014_invitation_wording.sql +8 -0
- package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
- package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
- package/migrations-postgres/0017_app_sign_ins.sql +12 -0
- package/migrations-postgres/0018_app_members.sql +13 -0
- package/migrations-postgres/0019_app_mail_html.sql +7 -0
- package/migrations-postgres/0020_public_workloads.sql +9 -0
- package/migrations-postgres/0021_installation_brand.sql +19 -0
- package/migrations-postgres/0022_password_policy.sql +12 -0
- package/migrations-postgres/0023_terminals.sql +70 -0
- package/migrations-postgres/0024_app_terminals.sql +10 -0
- package/migrations-postgres/0025_terminal_completion.sql +10 -0
- package/migrations-postgres/0026_terminal_generation.sql +12 -0
- package/migrations-postgres/0027_application_exact_actions.sql +28 -0
- package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
- package/migrations-postgres/0029_role_via.sql +4 -0
- package/migrations-postgres/0030_membership_role_via.sql +7 -0
- package/migrations-postgres/0031_person_locale.sql +11 -0
- package/package.json +70 -5
- package/src/admin/access.ts +47 -0
- package/src/admin/api-keys.ts +280 -0
- package/src/admin/app-people.ts +209 -0
- package/src/admin/app-schema.ts +308 -0
- package/src/admin/audit.ts +81 -0
- package/src/admin/brand.ts +54 -0
- package/src/admin/connections.ts +48 -0
- package/src/admin/context.ts +70 -0
- package/src/admin/grant-support.ts +192 -0
- package/src/admin/grants.ts +189 -0
- package/src/admin/handlers.ts +102 -0
- package/src/admin/http.ts +24 -0
- package/src/admin/membership-keys.ts +38 -0
- package/src/admin/pagination.ts +28 -0
- package/src/admin/password-policy.ts +48 -0
- package/src/admin/passwords.ts +78 -0
- package/src/admin/policies.ts +136 -0
- package/src/admin/principals.ts +226 -0
- package/src/admin/router.ts +291 -0
- package/src/admin/rpc.ts +387 -0
- package/src/admin/sessions.ts +115 -0
- package/src/admin/share-links.ts +127 -0
- package/src/admin/terminals.ts +115 -0
- package/src/admin/user-admin.ts +76 -0
- package/src/admin/workloads.ts +85 -0
- package/src/app-presentation.ts +178 -0
- package/src/app.ts +158 -0
- package/src/auth/cookies.ts +64 -0
- package/src/auth/failure.ts +25 -0
- package/src/auth/handoff.ts +136 -0
- package/src/auth/http.ts +88 -0
- package/src/auth/invitations.ts +220 -0
- package/src/auth/known-device.ts +44 -0
- package/src/auth/login.ts +162 -0
- package/src/auth/oidc-flight.ts +91 -0
- package/src/auth/oidc.ts +148 -0
- package/src/auth/password.ts +416 -0
- package/src/auth/routes.ts +108 -0
- package/src/auth/sessions.ts +249 -0
- package/src/auth/terminals.ts +284 -0
- package/src/auth.ts +193 -0
- package/src/binding-identity.ts +25 -0
- package/src/bounded-body.ts +35 -0
- package/src/catalog/cs.ts +147 -0
- package/src/catalog/en.ts +148 -0
- package/src/catalog/index.ts +122 -0
- package/src/catalog/uk.ts +164 -0
- package/src/client-address.ts +39 -0
- package/src/common-passwords.ts +37 -0
- package/src/contract-rules.ts +80 -0
- package/src/cron.ts +54 -0
- package/src/db.ts +128 -0
- package/src/delegation.ts +100 -0
- package/src/device-http.ts +39 -0
- package/src/device.ts +269 -0
- package/src/email-identity.ts +2 -0
- package/src/env.ts +132 -0
- package/src/handoff.ts +175 -0
- package/src/html.ts +4 -0
- package/src/human-admission.ts +40 -0
- package/src/identification.ts +185 -0
- package/src/index.ts +292 -0
- package/src/installation-brand.ts +82 -0
- package/src/issue.ts +265 -0
- package/src/json.ts +30 -0
- package/src/log.ts +26 -0
- package/src/membership-http.ts +135 -0
- package/src/membership.ts +1210 -0
- package/src/messages.ts +44 -0
- package/src/narrow-permissions.ts +26 -0
- package/src/node/browser-identity.ts +69 -0
- package/src/node/migrate.ts +52 -0
- package/src/node/prune.ts +34 -0
- package/src/node/runtime.ts +221 -0
- package/src/node/server.ts +104 -0
- package/src/oauth-client-auth.ts +93 -0
- package/src/oauth-client.ts +145 -0
- package/src/oauth-config.ts +72 -0
- package/src/oauth-http.ts +262 -0
- package/src/oauth.ts +272 -0
- package/src/oidc.ts +260 -0
- package/src/origin.ts +29 -0
- package/src/password-crypto.ts +148 -0
- package/src/password-db.ts +419 -0
- package/src/password-minimum.ts +44 -0
- package/src/password-pages.ts +397 -0
- package/src/password-policy.ts +79 -0
- package/src/password-service.ts +67 -0
- package/src/person-locale.ts +103 -0
- package/src/proxy-proof.ts +36 -0
- package/src/relay-mail.ts +64 -0
- package/src/repositories/app-schema.ts +550 -0
- package/src/repositories/audit.ts +405 -0
- package/src/repositories/brand.ts +66 -0
- package/src/repositories/credentials.ts +331 -0
- package/src/repositories/device.ts +137 -0
- package/src/repositories/grants.ts +404 -0
- package/src/repositories/handoff.ts +103 -0
- package/src/repositories/membership-transport.ts +49 -0
- package/src/repositories/membership.ts +875 -0
- package/src/repositories/oauth.ts +122 -0
- package/src/repositories/password-policy.ts +44 -0
- package/src/repositories/principals.ts +358 -0
- package/src/repositories/sessions.ts +339 -0
- package/src/repositories/sql.ts +23 -0
- package/src/repositories/terminals.ts +346 -0
- package/src/repositories/workloads.ts +134 -0
- package/src/request-id.ts +46 -0
- package/src/resolve.ts +396 -0
- package/src/retention.ts +34 -0
- package/src/roles.ts +54 -0
- package/src/rpc-http.ts +333 -0
- package/src/rpc-inputs.ts +110 -0
- package/src/rpc.ts +440 -0
- package/src/secret.ts +45 -0
- package/src/service.ts +59 -0
- package/src/services.ts +199 -0
- package/src/signing.ts +260 -0
- package/src/stored-chain.ts +23 -0
- package/src/stored-permissions.ts +34 -0
- package/src/terminals.ts +15 -0
- package/src/tokens.ts +506 -0
- package/src/workload-token.ts +130 -0
- package/types/fabrika.config.d.ts +11 -0
- package/types/src/admin/access.d.ts +19 -0
- package/types/src/admin/api-keys.d.ts +26 -0
- package/types/src/admin/app-people.d.ts +8 -0
- package/types/src/admin/app-schema.d.ts +32 -0
- package/types/src/admin/audit.d.ts +10 -0
- package/types/src/admin/brand.d.ts +10 -0
- package/types/src/admin/connections.d.ts +5 -0
- package/types/src/admin/context.d.ts +46 -0
- package/types/src/admin/grant-support.d.ts +59 -0
- package/types/src/admin/grants.d.ts +8 -0
- package/types/src/admin/handlers.d.ts +82 -0
- package/types/src/admin/http.d.ts +9 -0
- package/types/src/admin/membership-keys.d.ts +8 -0
- package/types/src/admin/pagination.d.ts +5 -0
- package/types/src/admin/password-policy.d.ts +9 -0
- package/types/src/admin/passwords.d.ts +5 -0
- package/types/src/admin/policies.d.ts +15 -0
- package/types/src/admin/principals.d.ts +15 -0
- package/types/src/admin/router.d.ts +75 -0
- package/types/src/admin/rpc.d.ts +6 -0
- package/types/src/admin/sessions.d.ts +14 -0
- package/types/src/admin/share-links.d.ts +21 -0
- package/types/src/admin/terminals.d.ts +13 -0
- package/types/src/admin/user-admin.d.ts +30 -0
- package/types/src/admin/workloads.d.ts +5 -0
- package/types/src/app-presentation.d.ts +86 -0
- package/types/src/app.d.ts +62 -0
- package/types/src/auth/cookies.d.ts +29 -0
- package/types/src/auth/failure.d.ts +47 -0
- package/types/src/auth/handoff.d.ts +66 -0
- package/types/src/auth/http.d.ts +29 -0
- package/types/src/auth/invitations.d.ts +18 -0
- package/types/src/auth/known-device.d.ts +12 -0
- package/types/src/auth/login.d.ts +10 -0
- package/types/src/auth/oidc-flight.d.ts +39 -0
- package/types/src/auth/oidc.d.ts +7 -0
- package/types/src/auth/password.d.ts +7 -0
- package/types/src/auth/routes.d.ts +15 -0
- package/types/src/auth/sessions.d.ts +60 -0
- package/types/src/auth/terminals.d.ts +47 -0
- package/types/src/auth.d.ts +70 -0
- package/types/src/binding-identity.d.ts +12 -0
- package/types/src/bounded-body.d.ts +12 -0
- package/types/src/catalog/cs.d.ts +2 -0
- package/types/src/catalog/en.d.ts +2 -0
- package/types/src/catalog/index.d.ts +112 -0
- package/types/src/catalog/uk.d.ts +2 -0
- package/types/src/client-address.d.ts +31 -0
- package/types/src/common-passwords.d.ts +2 -0
- package/types/src/contract-rules.d.ts +25 -0
- package/types/src/cron.d.ts +15 -0
- package/types/src/db.d.ts +58 -0
- package/types/src/delegation.d.ts +38 -0
- package/types/src/device-http.d.ts +2 -0
- package/types/src/device.d.ts +11 -0
- package/types/src/email-identity.d.ts +1 -0
- package/types/src/env.d.ts +127 -0
- package/types/src/handoff.d.ts +57 -0
- package/types/src/html.d.ts +2 -0
- package/types/src/human-admission.d.ts +22 -0
- package/types/src/identification.d.ts +30 -0
- package/types/src/index.d.ts +62 -0
- package/types/src/installation-brand.d.ts +22 -0
- package/types/src/issue.d.ts +62 -0
- package/types/src/json.d.ts +15 -0
- package/types/src/log.d.ts +15 -0
- package/types/src/membership-http.d.ts +8 -0
- package/types/src/membership.d.ts +156 -0
- package/types/src/messages.d.ts +20 -0
- package/types/src/narrow-permissions.d.ts +7 -0
- package/types/src/node/browser-identity.d.ts +1 -0
- package/types/src/node/migrate.d.ts +4 -0
- package/types/src/node/prune.d.ts +1 -0
- package/types/src/node/runtime.d.ts +51 -0
- package/types/src/node/server.d.ts +5 -0
- package/types/src/oauth-client-auth.d.ts +26 -0
- package/types/src/oauth-client.d.ts +17 -0
- package/types/src/oauth-config.d.ts +16 -0
- package/types/src/oauth-http.d.ts +7 -0
- package/types/src/oauth.d.ts +51 -0
- package/types/src/oidc.d.ts +81 -0
- package/types/src/origin.d.ts +9 -0
- package/types/src/password-crypto.d.ts +37 -0
- package/types/src/password-db.d.ts +134 -0
- package/types/src/password-minimum.d.ts +23 -0
- package/types/src/password-pages.d.ts +143 -0
- package/types/src/password-policy.d.ts +19 -0
- package/types/src/password-service.d.ts +24 -0
- package/types/src/person-locale.d.ts +50 -0
- package/types/src/proxy-proof.d.ts +21 -0
- package/types/src/relay-mail.d.ts +25 -0
- package/types/src/repositories/app-schema.d.ts +244 -0
- package/types/src/repositories/audit.d.ts +187 -0
- package/types/src/repositories/brand.d.ts +41 -0
- package/types/src/repositories/credentials.d.ts +148 -0
- package/types/src/repositories/device.d.ts +50 -0
- package/types/src/repositories/grants.d.ts +177 -0
- package/types/src/repositories/handoff.d.ts +52 -0
- package/types/src/repositories/membership-transport.d.ts +31 -0
- package/types/src/repositories/membership.d.ts +273 -0
- package/types/src/repositories/oauth.d.ts +55 -0
- package/types/src/repositories/password-policy.d.ts +25 -0
- package/types/src/repositories/principals.d.ts +159 -0
- package/types/src/repositories/sessions.d.ts +150 -0
- package/types/src/repositories/sql.d.ts +13 -0
- package/types/src/repositories/terminals.d.ts +144 -0
- package/types/src/repositories/workloads.d.ts +61 -0
- package/types/src/request-id.d.ts +25 -0
- package/types/src/resolve.d.ts +118 -0
- package/types/src/retention.d.ts +18 -0
- package/types/src/roles.d.ts +34 -0
- package/types/src/rpc-http.d.ts +53 -0
- package/types/src/rpc-inputs.d.ts +707 -0
- package/types/src/rpc.d.ts +4 -0
- package/types/src/secret.d.ts +21 -0
- package/types/src/service.d.ts +19 -0
- package/types/src/services.d.ts +72 -0
- package/types/src/signing.d.ts +72 -0
- package/types/src/stored-chain.d.ts +6 -0
- package/types/src/stored-permissions.d.ts +12 -0
- package/types/src/terminals.d.ts +7 -0
- package/types/src/tokens.d.ts +113 -0
- package/types/src/workload-token.d.ts +7 -0
- package/README.md +0 -3
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import type { InstallationBrand } from '@fabrika/proxy-core/brand'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import { actionLandingOrigin, type AppPresentation, appQuery, landingUrl, localeQuery, presentationFor, withPersonLocale } from '../app-presentation'
|
|
4
|
+
import { type InvitationRow, principalStatus } from '../db'
|
|
5
|
+
import { type RequestContext } from '../env'
|
|
6
|
+
import { acceptCreatingPrincipal, acceptInvitation, INVITATION_ACCEPT_PATH, invitationOffer } from '../membership'
|
|
7
|
+
import { passwordMinLength } from '../password-minimum'
|
|
8
|
+
import { authFailurePage, invitationOutcomePage, invitationPage, invitationPasswordPage } from '../password-pages'
|
|
9
|
+
import { validatePassword } from '../password-policy'
|
|
10
|
+
import { parseLocale, rememberLocaleCookie } from '../person-locale'
|
|
11
|
+
import type { Services } from '../services'
|
|
12
|
+
import { methodNotAllowed, readForm, redirectHeaders, sameOrigin, stringValue } from './http'
|
|
13
|
+
import { currentSession, issueSession } from './sessions'
|
|
14
|
+
|
|
15
|
+
const tokenSchema = z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/)
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `GET|POST /auth/invitations/accept`. The emailed link opens the GET page; its fragment carries the
|
|
19
|
+
* one-time token, which never reaches a server log. Accepting is a POST from that page, same-origin
|
|
20
|
+
* only, by the principal signed in HERE, on IAM's host — the mailbox's owner, proven by the token.
|
|
21
|
+
*
|
|
22
|
+
* An invitation that creates its principal (`invitationOffer`) answers that POST with a set-password form instead;
|
|
23
|
+
* its POST, with the password, creates the external principal and accepts in one transaction, then signs the browser
|
|
24
|
+
* in on IAM. Neither the GET nor the POST without a password changes anything, so a mail scanner spends nothing. A
|
|
25
|
+
* browser signed in here as anyone gets neither: it is told to sign out or use another browser profile first. An
|
|
26
|
+
* invitation whose mailbox no principal holds and whose acceptance creates none (`no_account`, a role not declared
|
|
27
|
+
* external among them) answers that the address has no account here instead of a sign-in it could not pass.
|
|
28
|
+
*
|
|
29
|
+
* The link's `?app=` picks the page's language; an accepted invitation lands on its own application's
|
|
30
|
+
* registered origin, where the application's proxy signs the browser in through the normal handoff.
|
|
31
|
+
*/
|
|
32
|
+
export async function handleInvitation(request: Request, services: Services, ctx: RequestContext, requestId: string): Promise<Response> {
|
|
33
|
+
const linked = await presentationFor(services, new URL(request.url).searchParams.get('app'), { request })
|
|
34
|
+
if (request.method === 'GET') {
|
|
35
|
+
return invitationPage(linked)
|
|
36
|
+
}
|
|
37
|
+
if (request.method !== 'POST') {
|
|
38
|
+
return methodNotAllowed()
|
|
39
|
+
}
|
|
40
|
+
if (!sameOrigin(request, services.config)) {
|
|
41
|
+
return authFailurePage(linked, { kind: 'cross_origin' }, 403)
|
|
42
|
+
}
|
|
43
|
+
const form = await readForm(request)
|
|
44
|
+
const token = tokenSchema.safeParse(stringValue(form?.get('token') ?? null))
|
|
45
|
+
const invalid = () => invitationOutcomePage({ presentation: linked, title: (t) => t.invalidTitle, text: (t) => t.invalidText, status: 400 })
|
|
46
|
+
if (!token.success) {
|
|
47
|
+
return invalid()
|
|
48
|
+
}
|
|
49
|
+
const offer = await invitationOffer(services, token.data)
|
|
50
|
+
if (offer.kind === 'invalid') {
|
|
51
|
+
return invalid()
|
|
52
|
+
}
|
|
53
|
+
if (offer.kind === 'not_allowed') {
|
|
54
|
+
return invitationOutcomePage({ presentation: linked, title: (t) => t.unavailableTitle, text: (t) => t.inviterCannotGrant, status: 403 })
|
|
55
|
+
}
|
|
56
|
+
if (offer.kind === 'create') {
|
|
57
|
+
// The new account would replace the browser's session silently, and the application would keep the old identity.
|
|
58
|
+
if ((await currentSession(request, services)) !== null) {
|
|
59
|
+
return invitationOutcomePage({
|
|
60
|
+
presentation: await presentationFor(services, offer.invitation.app, { request, brand: linked.brand, locale: offer.invitation.locale }),
|
|
61
|
+
title: (t) => t.otherAccountTitle,
|
|
62
|
+
text: (t) => t.otherAccountText(offer.invitation.email),
|
|
63
|
+
status: 409,
|
|
64
|
+
signOut: '/auth/logout',
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
const password = stringValue(form?.get('password') ?? null)
|
|
68
|
+
if (password !== null) {
|
|
69
|
+
return createAndAccept(request, services, ctx, { invitation: offer.invitation, token: token.data, password, requestId, brand: linked.brand })
|
|
70
|
+
}
|
|
71
|
+
const presentation = await presentationFor(services, offer.invitation.app, { request, brand: linked.brand, locale: offer.invitation.locale })
|
|
72
|
+
return invitationPasswordPage({
|
|
73
|
+
presentation,
|
|
74
|
+
landingOrigin: await actionLandingOrigin(services, presentation),
|
|
75
|
+
token: token.data,
|
|
76
|
+
address: offer.invitation.email,
|
|
77
|
+
minLength: await passwordMinLength(services),
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
const session = await currentSession(request, services)
|
|
81
|
+
if (session === null) {
|
|
82
|
+
if (offer.kind === 'no_account') {
|
|
83
|
+
// A sign-in form would be a dead end: no principal holds the mailbox and no sign-in here creates one.
|
|
84
|
+
return invitationOutcomePage({
|
|
85
|
+
presentation: await presentationFor(services, offer.invitation.app, { request, brand: linked.brand, locale: offer.invitation.locale }),
|
|
86
|
+
title: (t) => t.noAccountTitle,
|
|
87
|
+
text: (t) => t.noAccountText(offer.invitation.email),
|
|
88
|
+
status: 403,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
// The invitation's own language beats the link's, as on every other page of this flow.
|
|
92
|
+
return signInFirst(services, withPersonLocale(linked, parseLocale(offer.invitation.locale)))
|
|
93
|
+
}
|
|
94
|
+
const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
|
|
95
|
+
if (principal === null || principalStatus(principal) === 'disabled') {
|
|
96
|
+
return invitationOutcomePage({ presentation: linked, title: (t) => t.unavailableTitle, text: (t) => t.accountCannotAccept, status: 403 })
|
|
97
|
+
}
|
|
98
|
+
const outcome = await acceptInvitation(services, principal, token.data, requestId)
|
|
99
|
+
if (!outcome.ok) {
|
|
100
|
+
switch (outcome.reason) {
|
|
101
|
+
case 'invalid':
|
|
102
|
+
return invalid()
|
|
103
|
+
case 'wrong_principal':
|
|
104
|
+
return invitationOutcomePage({ presentation: linked, title: (t) => t.wrongAddressTitle, text: (t) => t.wrongAddressText, status: 403 })
|
|
105
|
+
case 'not_eligible':
|
|
106
|
+
return invitationOutcomePage({ presentation: linked, title: (t) => t.unavailableTitle, text: (t) => t.roleNotEligible, status: 403 })
|
|
107
|
+
case 'not_allowed':
|
|
108
|
+
return invitationOutcomePage({ presentation: linked, title: (t) => t.unavailableTitle, text: (t) => t.inviterCannotGrant, status: 403 })
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const { invitation } = outcome
|
|
112
|
+
const presentation = await presentationFor(services, invitation.app, { request, brand: linked.brand, locale: invitation.locale ?? principal.locale })
|
|
113
|
+
const landing = landingUrl(presentation)
|
|
114
|
+
if (landing !== null) {
|
|
115
|
+
return new Response(null, { status: 302, headers: redirectHeaders(landing) })
|
|
116
|
+
}
|
|
117
|
+
const role = await services.repositories.appSchema.getRole(invitation.app, invitation.role_key)
|
|
118
|
+
return invitationOutcomePage({
|
|
119
|
+
presentation,
|
|
120
|
+
title: (t) => t.acceptedTitle,
|
|
121
|
+
text: (t) =>
|
|
122
|
+
t.acceptedText({ role: role?.name ?? invitation.role_key, scope: invitation.scope_type, appName: presentation.displayName ?? invitation.app }),
|
|
123
|
+
status: 200,
|
|
124
|
+
})
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The set-password form's POST: the password policy, then the external principal, its password and the acceptance in
|
|
129
|
+
* one transaction, then the IAM session, and the browser lands on the application, whose proxy hands the session off.
|
|
130
|
+
*/
|
|
131
|
+
async function createAndAccept(
|
|
132
|
+
request: Request,
|
|
133
|
+
services: Services,
|
|
134
|
+
ctx: RequestContext,
|
|
135
|
+
input: {
|
|
136
|
+
readonly invitation: InvitationRow
|
|
137
|
+
readonly token: string
|
|
138
|
+
readonly password: string
|
|
139
|
+
readonly requestId: string
|
|
140
|
+
/** The logo the request's page already read. */
|
|
141
|
+
readonly brand: InstallationBrand | null
|
|
142
|
+
},
|
|
143
|
+
): Promise<Response> {
|
|
144
|
+
const { invitation } = input
|
|
145
|
+
const presentation = await presentationFor(services, invitation.app, { request, brand: input.brand, locale: invitation.locale })
|
|
146
|
+
const minLength = await passwordMinLength(services)
|
|
147
|
+
const policy = validatePassword(input.password, minLength, { email: invitation.email, label: invitation.email })
|
|
148
|
+
if (!policy.ok) {
|
|
149
|
+
return invitationPasswordPage({
|
|
150
|
+
presentation,
|
|
151
|
+
landingOrigin: await actionLandingOrigin(services, presentation),
|
|
152
|
+
token: input.token,
|
|
153
|
+
address: invitation.email,
|
|
154
|
+
minLength,
|
|
155
|
+
problem: policy.problem,
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
const outcome = await acceptCreatingPrincipal(services, invitation, await services.passwordHasher.hash(policy.password), input.requestId)
|
|
159
|
+
if (!outcome.ok) {
|
|
160
|
+
return creationRefused(services, presentation, outcome.reason)
|
|
161
|
+
}
|
|
162
|
+
return issueSession(request, services, ctx, {
|
|
163
|
+
principalId: outcome.principal.id,
|
|
164
|
+
email: outcome.principal.email,
|
|
165
|
+
authenticationMethod: 'password',
|
|
166
|
+
redirect: landingUrl(presentation),
|
|
167
|
+
reason: 'invitation_enrollment',
|
|
168
|
+
requestId: input.requestId,
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function creationRefused(
|
|
173
|
+
services: Services,
|
|
174
|
+
presentation: AppPresentation,
|
|
175
|
+
reason: 'invalid' | 'not_allowed' | 'not_eligible' | 'sign_in',
|
|
176
|
+
): Response {
|
|
177
|
+
switch (reason) {
|
|
178
|
+
case 'invalid':
|
|
179
|
+
return invitationOutcomePage({ presentation, title: (t) => t.invalidTitle, text: (t) => t.invalidText, status: 400 })
|
|
180
|
+
case 'not_allowed':
|
|
181
|
+
return invitationOutcomePage({ presentation, title: (t) => t.unavailableTitle, text: (t) => t.inviterCannotGrant, status: 403 })
|
|
182
|
+
case 'not_eligible':
|
|
183
|
+
return invitationOutcomePage({ presentation, title: (t) => t.unavailableTitle, text: (t) => t.roleNotEligible, status: 403 })
|
|
184
|
+
case 'sign_in':
|
|
185
|
+
return signInFirst(services, presentation)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The page that asks the person to sign in with the invited address and open the link again. The application's own
|
|
191
|
+
* address signs the browser in through its handoff; without one, IAM's own sign-in does. The handoff's sign-in page is
|
|
192
|
+
* built from the proxy's bounce and carries no `?locale=` of IAM's, so the page's language (`personLocale`: the
|
|
193
|
+
* invitation's, else the link's `?locale=`, else IAM's cookie) is remembered for this browser (`rememberLocaleCookie`)
|
|
194
|
+
* and that page speaks it too, unless the application's own language cookie names another. IAM's own sign-in carries
|
|
195
|
+
* it as `?locale=`. It picks words only.
|
|
196
|
+
*/
|
|
197
|
+
function signInFirst(services: Services, presentation: AppPresentation): Response {
|
|
198
|
+
const locale = presentation.personLocale
|
|
199
|
+
const landing = landingUrl(presentation)
|
|
200
|
+
const response = invitationOutcomePage({
|
|
201
|
+
presentation,
|
|
202
|
+
title: (t) => t.signInFirstTitle,
|
|
203
|
+
text: (t) => t.signInFirstText,
|
|
204
|
+
status: 401,
|
|
205
|
+
signIn: landing ?? ownSignIn(services, presentation),
|
|
206
|
+
})
|
|
207
|
+
if (landing !== null && locale !== null) {
|
|
208
|
+
response.headers.append('Set-Cookie', rememberLocaleCookie(locale))
|
|
209
|
+
}
|
|
210
|
+
return response
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** IAM's own sign-in, back to this page: the browser opens the invitation link again there. */
|
|
214
|
+
function ownSignIn(services: Services, presentation: AppPresentation): string {
|
|
215
|
+
const accept = new URL(`${INVITATION_ACCEPT_PATH}${appQuery(presentation)}`, services.config.issuer)
|
|
216
|
+
// The sign-in page speaks the person's language too, not only the invitation page it returns to.
|
|
217
|
+
const signIn = new URL(`/auth/login${localeQuery(presentation)}`, services.config.issuer)
|
|
218
|
+
signIn.searchParams.set('redirect', accept.toString())
|
|
219
|
+
return signIn.toString()
|
|
220
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The known-device cookie (OWASP "device cookies"): a browser that completed a password login for a
|
|
3
|
+
* principal carries a signed proof of it, and a later login FOR THAT PRINCIPAL from that browser is
|
|
4
|
+
* throttled by its own per-device bucket instead of the client, account and deployment-wide ones. Those
|
|
5
|
+
* buckets are keyed on values an attacker can pick or share (an address, a mailbox, nothing at all), so
|
|
6
|
+
* without this one client could lock out a known account, or every password user, including the owners.
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod'
|
|
9
|
+
import { randomToken } from '../oidc'
|
|
10
|
+
import { getSigner, verifyInternal } from '../signing'
|
|
11
|
+
import { readCookie, serializeCookie } from './cookies'
|
|
12
|
+
import type { AuthEnv } from './oidc-flight'
|
|
13
|
+
|
|
14
|
+
// Host-only on IAM's host, so no application upstream receives it; outside the proxy's stripped `__Host-px_` prefix on purpose.
|
|
15
|
+
export const KNOWN_DEVICE_COOKIE = '__Host-fabrika_device'
|
|
16
|
+
|
|
17
|
+
/** Three session lifetimes: a regular user keeps the exemption across renewals, a lost browser drops out within a quarter. */
|
|
18
|
+
export const KNOWN_DEVICE_TTL_SECONDS = 90 * 24 * 60 * 60
|
|
19
|
+
|
|
20
|
+
/** Audience of the device token — never an app id, so it can never pass as an access token or an OIDC flight. */
|
|
21
|
+
const KNOWN_DEVICE_AUDIENCE = 'fabrika:iam:known-device'
|
|
22
|
+
|
|
23
|
+
export interface KnownDevice {
|
|
24
|
+
principalId: string
|
|
25
|
+
deviceId: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const knownDeviceSchema = z.object({ sub: z.string().min(1), dev: z.string().min(1) })
|
|
29
|
+
|
|
30
|
+
/** A `Set-Cookie` naming a fresh device id for `principalId`. */
|
|
31
|
+
export async function knownDeviceCookie(env: AuthEnv, principalId: string): Promise<string> {
|
|
32
|
+
const signer = await getSigner(env)
|
|
33
|
+
const token = await signer.signInternal({ sub: principalId, dev: randomToken(16) }, KNOWN_DEVICE_AUDIENCE, KNOWN_DEVICE_TTL_SECONDS)
|
|
34
|
+
return serializeCookie(KNOWN_DEVICE_COOKIE, token, { httpOnly: true, secure: true, sameSite: 'Lax', maxAge: KNOWN_DEVICE_TTL_SECONDS, path: '/' })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The device the request's cookie proves, or null when it is absent, forged, expired or malformed. */
|
|
38
|
+
export async function readKnownDevice(env: AuthEnv, request: Request): Promise<KnownDevice | null> {
|
|
39
|
+
const raw = readCookie(request.headers.get('cookie'), KNOWN_DEVICE_COOKIE)
|
|
40
|
+
if (raw === null || raw === '') return null
|
|
41
|
+
const payload = await verifyInternal(await getSigner(env), raw, KNOWN_DEVICE_AUDIENCE)
|
|
42
|
+
const parsed = knownDeviceSchema.safeParse(payload)
|
|
43
|
+
return parsed.success ? { principalId: parsed.data.sub, deviceId: parsed.data.dev } : null
|
|
44
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { AUTH_HANDOFF_CHALLENGE_PARAM, AUTH_HANDOFF_STATE_PARAM } from '@fabrika/auth-core'
|
|
2
|
+
import { type AppPresentation, installationPresentation, presentationFor, withPersonLocale } from '../app-presentation'
|
|
3
|
+
import { LOCAL_DEV_ADMIN_EMAIL, LOCAL_DEV_ADMIN_ID } from '../auth'
|
|
4
|
+
import { type SessionRow } from '../db'
|
|
5
|
+
|
|
6
|
+
import { type RequestContext } from '../env'
|
|
7
|
+
import { authFailurePage, chooseAccountPage, loginPage } from '../password-pages'
|
|
8
|
+
import { parseLocale } from '../person-locale'
|
|
9
|
+
import { resolveUserPrincipal } from '../resolve'
|
|
10
|
+
import { type Services } from '../services'
|
|
11
|
+
import { type Handoff, handoffLocation, handoffLoginUrl, handoffOf, handoffRedirectOr, loginDestinationFields, readHandoff } from './handoff'
|
|
12
|
+
import { readForm, redirectHeaders, sameOrigin, stringValue } from './http'
|
|
13
|
+
|
|
14
|
+
import { startOidc } from './oidc'
|
|
15
|
+
import { type AuthEnv } from './oidc-flight'
|
|
16
|
+
import { currentLogin, endLogin, issueSession, refuseLogin, signedOutRedirect } from './sessions'
|
|
17
|
+
import { identificationRedirect } from './terminals'
|
|
18
|
+
|
|
19
|
+
export async function handleLogin(
|
|
20
|
+
request: Request,
|
|
21
|
+
services: Services,
|
|
22
|
+
env: AuthEnv,
|
|
23
|
+
ctx: RequestContext,
|
|
24
|
+
requestId: string,
|
|
25
|
+
): Promise<Response> {
|
|
26
|
+
const url = new URL(request.url)
|
|
27
|
+
const reading = await readHandoff(
|
|
28
|
+
services,
|
|
29
|
+
url.searchParams.get('app'),
|
|
30
|
+
url.searchParams.get('redirect'),
|
|
31
|
+
url.searchParams.get(AUTH_HANDOFF_STATE_PARAM),
|
|
32
|
+
url.searchParams.get(AUTH_HANDOFF_CHALLENGE_PARAM),
|
|
33
|
+
)
|
|
34
|
+
if (reading.kind === 'refused') {
|
|
35
|
+
return authFailurePage(await presentationFor(services, url.searchParams.get('app'), { request }), reading.failure, 400)
|
|
36
|
+
}
|
|
37
|
+
const handoff = handoffOf(reading)
|
|
38
|
+
const presentation = await presentationFor(services, handoff?.app ?? null, { request })
|
|
39
|
+
// A handoff's destination is already validated against the app's registry, so `safeRedirect` must
|
|
40
|
+
// not get a say: it admits IAM's own origin only, which by definition excludes the app host this
|
|
41
|
+
// exists for. Passing its refusal to the form would send the login to the installation's landing.
|
|
42
|
+
const redirect = handoffRedirectOr(handoff, url.searchParams.get('redirect'), services)
|
|
43
|
+
|
|
44
|
+
// Already signed in HERE? Then a handoff needs no password. It continues silently when this login already chose the
|
|
45
|
+
// app, and otherwise asks which account to use; no code exists until the answer. Token renewal never comes here: the
|
|
46
|
+
// proxy re-mints from its app session server-side.
|
|
47
|
+
if (handoff !== null) {
|
|
48
|
+
const login = await currentLogin(request, services)
|
|
49
|
+
if (login !== null) {
|
|
50
|
+
if (await loginChoseApp(services, login.session, handoff.app)) {
|
|
51
|
+
return new Response(null, { status: 302, headers: redirectHeaders(await handoffLocation(services, handoff, login.session.id)) })
|
|
52
|
+
}
|
|
53
|
+
return chooseAccountPage({
|
|
54
|
+
// The signed-in person is known: their own language beats the browser's hints and the application's.
|
|
55
|
+
presentation: withPersonLocale(presentation, parseLocale(login.principal.locale)),
|
|
56
|
+
label: login.principal.label,
|
|
57
|
+
handoff,
|
|
58
|
+
redirectOrigin: (await loginDestinationFields(services, handoff, redirect)).redirectOrigin,
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
// No login here, but a terminal: the application identifies the person at it (ADR-0067 §2).
|
|
62
|
+
const identification = await identificationRedirect(request, services, handoff, presentation, requestId)
|
|
63
|
+
if (identification !== null) {
|
|
64
|
+
return identification
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (services.config.localDevLogin) {
|
|
69
|
+
return handleLocalLogin(request, services, ctx, requestId, redirect, handoff, presentation)
|
|
70
|
+
}
|
|
71
|
+
if (services.config.authentication.password.enabled) {
|
|
72
|
+
return loginPage({
|
|
73
|
+
presentation,
|
|
74
|
+
redirect,
|
|
75
|
+
oidcEnabled: services.config.authentication.oidc.enabled,
|
|
76
|
+
forgotEnabled: services.email !== null,
|
|
77
|
+
...await loginDestinationFields(services, handoff, redirect),
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
return startOidc(request, services, env, redirect, handoff)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* How long a new login counts as the choice of the application it lands on. A completed password action, an invitation
|
|
85
|
+
* enrollment or a sign-in on IAM's own page issues a login and lands on an application, whose proxy starts a handoff
|
|
86
|
+
* moments later; asking that person which account to use would ask what they just answered.
|
|
87
|
+
*/
|
|
88
|
+
const JUST_SIGNED_IN_SECONDS = 60
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Whether `login` already chose `app`: it holds a live session there (the browser lost that cookie), or it was issued
|
|
92
|
+
* moments ago. Otherwise the handoff asks before it uses the login.
|
|
93
|
+
*/
|
|
94
|
+
async function loginChoseApp(services: Services, login: SessionRow, app: string): Promise<boolean> {
|
|
95
|
+
if (login.created_at > Math.floor(Date.now() / 1000) - JUST_SIGNED_IN_SECONDS) return true
|
|
96
|
+
return services.repositories.sessions.hasActiveChild(login.id, app)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The answer to `chooseAccountPage`. Same-origin only, and it reads the handoff and the login again. `continue` hands off
|
|
101
|
+
* from the login the browser holds now; `another` ends that login like a sign-out and returns to the sign-in page of the
|
|
102
|
+
* same handoff, whose verifier the app's proxy still holds.
|
|
103
|
+
*/
|
|
104
|
+
export async function handleAccountChoice(request: Request, services: Services, requestId: string): Promise<Response> {
|
|
105
|
+
if (!sameOrigin(request, services.config)) {
|
|
106
|
+
return authFailurePage(await installationPresentation(services, { request }), { kind: 'cross_origin' }, 403)
|
|
107
|
+
}
|
|
108
|
+
const form = await readForm(request)
|
|
109
|
+
if (form === null) return authFailurePage(await installationPresentation(services, { request }), { kind: 'malformed_form' }, 400)
|
|
110
|
+
const app = stringValue(form.get('app'))
|
|
111
|
+
const reading = await readHandoff(
|
|
112
|
+
services,
|
|
113
|
+
app,
|
|
114
|
+
stringValue(form.get('redirect')),
|
|
115
|
+
stringValue(form.get(AUTH_HANDOFF_STATE_PARAM)),
|
|
116
|
+
stringValue(form.get(AUTH_HANDOFF_CHALLENGE_PARAM)),
|
|
117
|
+
)
|
|
118
|
+
const presentation = await presentationFor(services, app, { request })
|
|
119
|
+
if (reading.kind === 'refused') return authFailurePage(presentation, reading.failure, 400)
|
|
120
|
+
const handoff = handoffOf(reading)
|
|
121
|
+
const decision = form.get('decision')
|
|
122
|
+
if (handoff === null || (decision !== 'continue' && decision !== 'another')) return authFailurePage(presentation, { kind: 'malformed_form' }, 400)
|
|
123
|
+
if (decision === 'another') {
|
|
124
|
+
if (!await endLogin(request, services, requestId)) return authFailurePage(presentation, { kind: 'logout_unavailable' }, 503)
|
|
125
|
+
return signedOutRedirect(handoffLoginUrl(services, handoff))
|
|
126
|
+
}
|
|
127
|
+
const login = await currentLogin(request, services)
|
|
128
|
+
// The login ended after the page was rendered: sign in again, and the handoff continues from there.
|
|
129
|
+
const location = login === null ? handoffLoginUrl(services, handoff) : await handoffLocation(services, handoff, login.session.id)
|
|
130
|
+
return new Response(null, { status: 302, headers: redirectHeaders(location) })
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function handleLocalLogin(
|
|
134
|
+
request: Request,
|
|
135
|
+
services: Services,
|
|
136
|
+
ctx: RequestContext,
|
|
137
|
+
requestId: string,
|
|
138
|
+
redirect: string | null,
|
|
139
|
+
handoff: Handoff | null,
|
|
140
|
+
presentation: AppPresentation,
|
|
141
|
+
): Promise<Response> {
|
|
142
|
+
const resolved = await resolveUserPrincipal(services.repositories.principals, LOCAL_DEV_ADMIN_ID, LOCAL_DEV_ADMIN_EMAIL, requestId)
|
|
143
|
+
if (!resolved.ok) {
|
|
144
|
+
return refuseLogin(
|
|
145
|
+
services,
|
|
146
|
+
request,
|
|
147
|
+
{ requestId, principalId: null, reason: 'local_login_refused' },
|
|
148
|
+
() => authFailurePage(presentation, { kind: 'login_refused', reason: `local ${resolved.reason}` }, 403),
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
return issueSession(request, services, ctx, {
|
|
152
|
+
principalId: resolved.principal.id,
|
|
153
|
+
idpSub: LOCAL_DEV_ADMIN_ID,
|
|
154
|
+
email: LOCAL_DEV_ADMIN_EMAIL,
|
|
155
|
+
// The bypass's own method, so the session dies with the flag rather than passing as an OIDC login.
|
|
156
|
+
authenticationMethod: 'local_dev',
|
|
157
|
+
redirect,
|
|
158
|
+
reason: 'local_login',
|
|
159
|
+
requestId,
|
|
160
|
+
handoff,
|
|
161
|
+
})
|
|
162
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { AppPresentation } from '../app-presentation'
|
|
3
|
+
import { type Env } from '../env'
|
|
4
|
+
import { authFailurePage } from '../password-pages'
|
|
5
|
+
import { getSigner, verifyInternal } from '../signing'
|
|
6
|
+
|
|
7
|
+
import { clearCookie } from './cookies'
|
|
8
|
+
import type { AuthFailure } from './failure'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* In-flight OIDC cookie: a SIGNED token carrying state + PKCE verifier + redirect; `__Host-`, 10 min.
|
|
12
|
+
* Outside the `__Host-px_` prefix the proxy strips upstream; host-only on IAM's host, so no application receives it.
|
|
13
|
+
*/
|
|
14
|
+
export const OIDC_COOKIE = '__Host-fabrika_oidc'
|
|
15
|
+
|
|
16
|
+
/** The flight's name before it took the `__Host-` prefix. Never read; only cleared, so old copies expire. */
|
|
17
|
+
const LEGACY_OIDC_COOKIE = 'px_oidc'
|
|
18
|
+
|
|
19
|
+
export const OIDC_TTL_SECONDS = 600
|
|
20
|
+
|
|
21
|
+
/** The only env the auth surface touches directly is the signing config — the JWKS, and the flight. */
|
|
22
|
+
export type AuthEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
|
|
23
|
+
|
|
24
|
+
/** The in-flight OIDC state carried between /auth/login and /auth/callback. */
|
|
25
|
+
interface Flight {
|
|
26
|
+
state: string
|
|
27
|
+
verifier: string
|
|
28
|
+
/** Absent for a login with no return address, which lands on the installation's landing. */
|
|
29
|
+
redirect?: string
|
|
30
|
+
/** The handoff app, when this SSO detour started from one (ADR-0022). */
|
|
31
|
+
app?: string
|
|
32
|
+
handoffState?: string
|
|
33
|
+
handoffChallenge?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Audience of the flight token — never an app id, so a flight can never pass as an access token. */
|
|
37
|
+
const OIDC_FLIGHT_AUDIENCE = 'fabrika:iam:oidc-flight'
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* SIGN the flight, with IAM's own key, and keep it in a `__Host-` cookie. Both are needed.
|
|
41
|
+
*
|
|
42
|
+
* The `state` match alone is not a CSRF check when whoever writes the cookie also writes `state`.
|
|
43
|
+
* The signature proves IAM issued the flight, but an attacker can start a login of their own and
|
|
44
|
+
* get a validly signed flight too. Cookie-tossing from any host under a shared registrable domain
|
|
45
|
+
* would plant it in the victim's browser ahead of the victim's own, and IAM would issue the victim
|
|
46
|
+
* a session for the ATTACKER'S identity. The browser refuses a `__Host-` cookie that names a
|
|
47
|
+
* `Domain`, so the prefix proves this browser's flight was set by IAM's host.
|
|
48
|
+
*/
|
|
49
|
+
export async function encodeFlight(env: AuthEnv, flight: Flight): Promise<string> {
|
|
50
|
+
const signer = await getSigner(env)
|
|
51
|
+
return signer.signInternal({ ...flight }, OIDC_FLIGHT_AUDIENCE, OIDC_TTL_SECONDS)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const flightSchema = z.object({
|
|
55
|
+
state: z.string(),
|
|
56
|
+
verifier: z.string(),
|
|
57
|
+
redirect: z.string().optional(),
|
|
58
|
+
app: z.string().optional().catch(undefined),
|
|
59
|
+
handoffState: z.string().optional().catch(undefined),
|
|
60
|
+
handoffChallenge: z.string().optional().catch(undefined),
|
|
61
|
+
}).transform(({ state, verifier, redirect, app, handoffState, handoffChallenge }, ctx) => {
|
|
62
|
+
if (app === undefined || app === '') return { state, verifier, redirect }
|
|
63
|
+
if (handoffState === undefined || handoffChallenge === undefined) {
|
|
64
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Incomplete handoff' })
|
|
65
|
+
return z.NEVER
|
|
66
|
+
}
|
|
67
|
+
return { state, verifier, redirect, app, handoffState, handoffChallenge }
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
export async function decodeFlight(env: AuthEnv, raw: string | null): Promise<Flight | null> {
|
|
71
|
+
if (!raw) {
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
const payload = await verifyInternal(await getSigner(env), raw, OIDC_FLIGHT_AUDIENCE)
|
|
75
|
+
const parsed = flightSchema.safeParse(payload)
|
|
76
|
+
return parsed.success ? parsed.data : null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The `Set-Cookie` values that spend the flight, the legacy `/auth` one included. */
|
|
80
|
+
export function endingFlightCookies(): string[] {
|
|
81
|
+
return [clearCookie(OIDC_COOKIE), clearCookie(LEGACY_OIDC_COOKIE, { path: '/auth' })]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A refusal page that also spends the OIDC flight — every terminal callback outcome goes through here. */
|
|
85
|
+
export function authFailureEndingFlight(presentation: AppPresentation, failure: AuthFailure, status: number): Response {
|
|
86
|
+
const response = authFailurePage(presentation, failure, status)
|
|
87
|
+
for (const cookie of endingFlightCookies()) {
|
|
88
|
+
response.headers.append('set-cookie', cookie)
|
|
89
|
+
}
|
|
90
|
+
return response
|
|
91
|
+
}
|
package/src/auth/oidc.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { AUTH_HANDOFF_CHALLENGE_PARAM, AUTH_HANDOFF_STATE_PARAM } from '@fabrika/auth-core'
|
|
2
|
+
import { type RequestContext } from '../env'
|
|
3
|
+
import { admitted } from '../human-admission'
|
|
4
|
+
import { generatePkce, randomToken } from '../oidc'
|
|
5
|
+
import { resolveUserPrincipal } from '../resolve'
|
|
6
|
+
import { type Services } from '../services'
|
|
7
|
+
|
|
8
|
+
import { presentationFor } from '../app-presentation'
|
|
9
|
+
import { authFailurePage } from '../password-pages'
|
|
10
|
+
import { readCookie, serializeCookie } from './cookies'
|
|
11
|
+
import type { AuthFailure } from './failure'
|
|
12
|
+
import { type Handoff, handoffOf, handoffRedirectOr, readHandoff } from './handoff'
|
|
13
|
+
import { redirectHeaders, safeRedirect } from './http'
|
|
14
|
+
import { type AuthEnv, authFailureEndingFlight, decodeFlight, encodeFlight, OIDC_COOKIE, OIDC_TTL_SECONDS } from './oidc-flight'
|
|
15
|
+
import { issueSession, type LoginRefusal, refuseLogin } from './sessions'
|
|
16
|
+
|
|
17
|
+
export async function handleOidcStart(request: Request, services: Services, env: AuthEnv): Promise<Response> {
|
|
18
|
+
const url = new URL(request.url)
|
|
19
|
+
const linked = await presentationFor(services, url.searchParams.get('app'), { request })
|
|
20
|
+
if (!services.config.authentication.oidc.enabled) return authFailurePage(linked, { kind: 'oidc_disabled' }, 404)
|
|
21
|
+
const reading = await readHandoff(
|
|
22
|
+
services,
|
|
23
|
+
url.searchParams.get('app'),
|
|
24
|
+
url.searchParams.get('redirect'),
|
|
25
|
+
url.searchParams.get(AUTH_HANDOFF_STATE_PARAM),
|
|
26
|
+
url.searchParams.get(AUTH_HANDOFF_CHALLENGE_PARAM),
|
|
27
|
+
)
|
|
28
|
+
if (reading.kind === 'refused') {
|
|
29
|
+
return authFailurePage(linked, reading.failure, 400)
|
|
30
|
+
}
|
|
31
|
+
const handoff = handoffOf(reading)
|
|
32
|
+
return startOidc(request, services, env, handoffRedirectOr(handoff, url.searchParams.get('redirect'), services), handoff)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function startOidc(
|
|
36
|
+
request: Request,
|
|
37
|
+
services: Services,
|
|
38
|
+
env: AuthEnv,
|
|
39
|
+
redirect: string | null,
|
|
40
|
+
handoff: Handoff | null = null,
|
|
41
|
+
): Promise<Response> {
|
|
42
|
+
if (!services.config.authentication.oidc.enabled || services.oidc === null) {
|
|
43
|
+
return authFailurePage(await presentationFor(services, handoff?.app ?? null, { request }), { kind: 'oidc_disabled' }, 404)
|
|
44
|
+
}
|
|
45
|
+
const { verifier, challenge } = await generatePkce()
|
|
46
|
+
const state = randomToken(16)
|
|
47
|
+
const location = await services.oidc.authorizationUrl({ state, codeChallenge: challenge })
|
|
48
|
+
|
|
49
|
+
const flight = await encodeFlight(env, {
|
|
50
|
+
state,
|
|
51
|
+
verifier,
|
|
52
|
+
...(redirect === null ? {} : { redirect }),
|
|
53
|
+
...(handoff === null
|
|
54
|
+
? {}
|
|
55
|
+
: { app: handoff.app, handoffState: handoff.state, handoffChallenge: handoff.challenge }),
|
|
56
|
+
})
|
|
57
|
+
const headers = redirectHeaders(location)
|
|
58
|
+
// The in-flight cookie is single-use, `__Host-` and SIGNED — see `encodeFlight`.
|
|
59
|
+
headers.append('Set-Cookie', serializeCookie(OIDC_COOKIE, flight, { httpOnly: true, secure: true, sameSite: 'Lax', maxAge: OIDC_TTL_SECONDS }))
|
|
60
|
+
return new Response(null, { status: 302, headers })
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function handleCallback(
|
|
64
|
+
request: Request,
|
|
65
|
+
services: Services,
|
|
66
|
+
env: AuthEnv,
|
|
67
|
+
ctx: RequestContext,
|
|
68
|
+
requestId: string,
|
|
69
|
+
): Promise<Response> {
|
|
70
|
+
const url = new URL(request.url)
|
|
71
|
+
const code = url.searchParams.get('code')
|
|
72
|
+
const state = url.searchParams.get('state')
|
|
73
|
+
const flight = await decodeFlight(env, readCookie(request.headers.get('Cookie'), OIDC_COOKIE))
|
|
74
|
+
// The flight we signed names the application the login started from; its refusals speak that language.
|
|
75
|
+
const presentation = await presentationFor(services, flight?.app ?? null, { request })
|
|
76
|
+
if (!services.config.authentication.oidc.enabled || services.oidc === null) {
|
|
77
|
+
return authFailureEndingFlight(presentation, { kind: 'oidc_disabled' }, 404)
|
|
78
|
+
}
|
|
79
|
+
// EVERY terminal outcome below consumes the flight. The cookie holds a live PKCE verifier and the
|
|
80
|
+
// state nonce; leaving it behind on a failure kept both replayable for the rest of their 600s.
|
|
81
|
+
// Every refusal is a refused login, logged before the answer.
|
|
82
|
+
const refuse = (reason: LoginRefusal, failure: AuthFailure, status: number): Promise<Response> =>
|
|
83
|
+
refuseLogin(services, request, { requestId, principalId: null, reason }, () => authFailureEndingFlight(presentation, failure, status))
|
|
84
|
+
|
|
85
|
+
// CSRF: the state echoed by the IdP must match the one in the flight WE signed.
|
|
86
|
+
if (!code || !state || !flight || flight.state !== state) {
|
|
87
|
+
return refuse('oidc_invalid_state', { kind: 'oidc_invalid_state' }, 400)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const idToken = await services.oidc.exchangeCode(code, flight.verifier)
|
|
91
|
+
if (!idToken) {
|
|
92
|
+
return refuse('oidc_code_exchange_failed', { kind: 'oidc_exchange_failed' }, 502)
|
|
93
|
+
}
|
|
94
|
+
const identity = await services.oidc.verifyIdToken(idToken)
|
|
95
|
+
if (!identity) {
|
|
96
|
+
return refuse('oidc_invalid_id_token', { kind: 'oidc_invalid_id_token' }, 401)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Admission: who may log in as a human. The central allowlist (`HUMAN_EMAIL_DOMAINS`/
|
|
100
|
+
// `HUMAN_EMAILS`, with a `*` entry meaning admit-all) gates SELF-PROVISIONING of a new identity.
|
|
101
|
+
// An already-known or invited INTERNAL principal (and a bootstrap admin) is always admitted regardless —
|
|
102
|
+
// so check existence WITHOUT lazily creating before refusing a non-allowlisted newcomer. An external
|
|
103
|
+
// principal is no reason to admit anyone: OIDC never claims it (ADR-0051).
|
|
104
|
+
if (!admitted(identity.email, services.config)) {
|
|
105
|
+
const known = (await services.repositories.principals.getUserByExternalId(identity.sub))
|
|
106
|
+
?? (await services.repositories.principals.getUserByEmail(identity.email))
|
|
107
|
+
if (!known || known.affiliation === 'external') {
|
|
108
|
+
return refuse('oidc_not_admitted', { kind: 'not_admitted' }, 403)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Resolve (or claim/lazy-create) the principal from the verified OIDC identity — the 3-step flow
|
|
113
|
+
// keyed on the IdP `sub` and verified email.
|
|
114
|
+
const resolved = await resolveUserPrincipal(services.repositories.principals, identity.sub, identity.email, requestId)
|
|
115
|
+
if (!resolved.ok) {
|
|
116
|
+
// The answer does not say an external principal holds the address.
|
|
117
|
+
const failure: AuthFailure = resolved.reason === 'external_principal'
|
|
118
|
+
? { kind: 'not_admitted' }
|
|
119
|
+
: { kind: 'login_refused', reason: resolved.reason }
|
|
120
|
+
return refuse(`oidc_${resolved.reason}`, failure, 403)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Re-validate the handoff on the way back: the flight is ours (signature-checked), but the registry
|
|
124
|
+
// may have changed while the human was away at the IdP.
|
|
125
|
+
const reading = flight.app === undefined
|
|
126
|
+
? { kind: 'none' as const }
|
|
127
|
+
: await readHandoff(
|
|
128
|
+
services,
|
|
129
|
+
flight.app,
|
|
130
|
+
flight.redirect ?? null,
|
|
131
|
+
flight.handoffState ?? null,
|
|
132
|
+
flight.handoffChallenge ?? null,
|
|
133
|
+
)
|
|
134
|
+
if (reading.kind === 'refused') {
|
|
135
|
+
return refuse('handoff_refused', reading.failure, 400)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return issueSession(request, services, ctx, {
|
|
139
|
+
principalId: resolved.principal.id,
|
|
140
|
+
idpSub: identity.sub,
|
|
141
|
+
email: identity.email,
|
|
142
|
+
redirect: safeRedirect(flight.redirect ?? null, services.config),
|
|
143
|
+
reason: 'login',
|
|
144
|
+
requestId,
|
|
145
|
+
clearOidc: true,
|
|
146
|
+
handoff: handoffOf(reading),
|
|
147
|
+
})
|
|
148
|
+
}
|