@fabrika/iam 0.9.0-dev.32 → 0.9.0-dev.33
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 +11 -3
- package/migrations/0032_second_factor.sql +29 -0
- package/migrations-postgres/0032_second_factor.sql +29 -0
- package/package.json +11 -10
- package/src/admin/api-keys.ts +15 -5
- package/src/admin/grant-support.ts +10 -0
- package/src/admin/grants.ts +5 -2
- package/src/admin/handlers.ts +3 -0
- package/src/admin/principals.ts +2 -5
- package/src/admin/rpc.ts +8 -0
- package/src/admin/second-factor.ts +39 -0
- package/src/admin/sessions.ts +4 -4
- package/src/auth/failure.ts +5 -0
- package/src/auth/http.ts +1 -1
- package/src/auth/invitations.ts +11 -3
- package/src/auth/login.ts +3 -2
- package/src/auth/oidc.ts +1 -1
- package/src/auth/password.ts +6 -6
- package/src/auth/routes.ts +11 -3
- package/src/auth/second-factor-challenge.ts +114 -0
- package/src/auth/second-factor.ts +276 -0
- package/src/auth/sessions.ts +72 -21
- package/src/auth.ts +19 -4
- package/src/catalog/cs.ts +32 -0
- package/src/catalog/en.ts +33 -0
- package/src/catalog/index.ts +28 -0
- package/src/catalog/uk.ts +33 -0
- package/src/data-key.ts +92 -0
- package/src/db.ts +12 -1
- package/src/env.ts +12 -0
- package/src/node/runtime.ts +7 -0
- package/src/oauth.ts +7 -3
- package/src/oidc-session.ts +25 -0
- package/src/repositories/second-factors.ts +165 -0
- package/src/repositories/sessions.ts +17 -9
- package/src/second-factor-pages.ts +129 -0
- package/src/services.ts +11 -2
- package/src/tokens.ts +3 -3
- package/src/totp.ts +132 -0
- package/types/src/admin/api-keys.d.ts +3 -3
- package/types/src/admin/grant-support.d.ts +2 -0
- package/types/src/admin/handlers.d.ts +3 -0
- package/types/src/admin/second-factor.d.ts +5 -0
- package/types/src/auth/failure.d.ts +10 -0
- package/types/src/auth/http.d.ts +1 -1
- package/types/src/auth/invitations.d.ts +2 -1
- package/types/src/auth/password.d.ts +1 -1
- package/types/src/auth/second-factor-challenge.d.ts +34 -0
- package/types/src/auth/second-factor.d.ts +19 -0
- package/types/src/auth/sessions.d.ts +22 -9
- package/types/src/auth.d.ts +9 -3
- package/types/src/catalog/index.d.ts +28 -0
- package/types/src/data-key.d.ts +19 -0
- package/types/src/db.d.ts +4 -1
- package/types/src/env.d.ts +12 -0
- package/types/src/oidc-session.d.ts +12 -0
- package/types/src/repositories/second-factors.d.ts +68 -0
- package/types/src/repositories/sessions.d.ts +7 -3
- package/types/src/second-factor-pages.d.ts +42 -0
- package/types/src/services.d.ts +4 -0
- package/types/src/totp.d.ts +32 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// A sign-in that proved its first factor and waits for its second. What it would open rides in a signed `__Host-` cookie
|
|
2
|
+
// for five minutes, like the OIDC flight: the signature proves IAM wrote it, the prefix that this browser holds it. The
|
|
3
|
+
// code form carries nothing of it, so a posted form names no principal and no destination.
|
|
4
|
+
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import { installationConsole, presentationFor } from '../app-presentation'
|
|
7
|
+
import { normalizeOrigin } from '../handoff'
|
|
8
|
+
import { type ChallengeProblem, secondFactorChallengePage } from '../second-factor-pages'
|
|
9
|
+
import type { Services } from '../services'
|
|
10
|
+
import { getSigner, verifyInternal } from '../signing'
|
|
11
|
+
import { clearCookie, readCookie, serializeCookie } from './cookies'
|
|
12
|
+
import type { Handoff } from './handoff'
|
|
13
|
+
import { endingFlightCookies } from './oidc-flight'
|
|
14
|
+
import type { AuthEnv } from './oidc-flight'
|
|
15
|
+
|
|
16
|
+
/** Host-only on IAM's host, outside the `__Host-px_` prefix the proxy strips upstream, so no application receives it. */
|
|
17
|
+
export const SECOND_FACTOR_COOKIE = '__Host-fabrika_second_factor'
|
|
18
|
+
|
|
19
|
+
/** Long enough to open an authenticator app and type a code; a sign-in that takes longer proves its first factor again. */
|
|
20
|
+
export const SECOND_FACTOR_CHALLENGE_TTL_SECONDS = 5 * 60
|
|
21
|
+
|
|
22
|
+
/** Audience of the challenge token — never an app id, so it passes as no access token, flight or device cookie. */
|
|
23
|
+
const SECOND_FACTOR_AUDIENCE = 'fabrika:iam:second-factor'
|
|
24
|
+
|
|
25
|
+
/** The login a verified code opens: what `issueSession` was given, less the request's own id. */
|
|
26
|
+
export interface PendingLogin {
|
|
27
|
+
readonly principalId: string
|
|
28
|
+
readonly idpSub: string | null
|
|
29
|
+
readonly email: string | null
|
|
30
|
+
readonly authenticationMethod: 'oidc' | 'password'
|
|
31
|
+
readonly redirect: string | null
|
|
32
|
+
readonly reason: string
|
|
33
|
+
readonly handoff: Handoff | null
|
|
34
|
+
/** A password login earns the known-device cookie once it is recorded. */
|
|
35
|
+
readonly rememberDevice: boolean
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const handoffSchema = z.object({ app: z.string(), returnUrl: z.string(), state: z.string(), challenge: z.string() })
|
|
39
|
+
const pendingSchema = z.object({
|
|
40
|
+
sub: z.string().min(1),
|
|
41
|
+
idp: z.string().nullable(),
|
|
42
|
+
em: z.string().nullable(),
|
|
43
|
+
am: z.enum(['oidc', 'password']),
|
|
44
|
+
rd: z.string().nullable(),
|
|
45
|
+
rs: z.string(),
|
|
46
|
+
ho: handoffSchema.nullable(),
|
|
47
|
+
dv: z.boolean(),
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
/** The pending login the request's challenge cookie proves, or null when it is absent, forged, expired or malformed. */
|
|
51
|
+
export async function readPendingLogin(env: AuthEnv, request: Request): Promise<PendingLogin | null> {
|
|
52
|
+
const raw = readCookie(request.headers.get('cookie'), SECOND_FACTOR_COOKIE)
|
|
53
|
+
if (raw === null || raw === '') return null
|
|
54
|
+
const parsed = pendingSchema.safeParse(await verifyInternal(await getSigner(env), raw, SECOND_FACTOR_AUDIENCE))
|
|
55
|
+
if (!parsed.success) return null
|
|
56
|
+
const { sub, idp, em, am, rd, rs, ho, dv } = parsed.data
|
|
57
|
+
return { principalId: sub, idpSub: idp, email: em, authenticationMethod: am, redirect: rd, reason: rs, handoff: ho, rememberDevice: dv }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Answer a first factor with the code form and the cookie that holds the pending login. An OIDC flight is spent here,
|
|
62
|
+
* as on every other end of its callback.
|
|
63
|
+
*/
|
|
64
|
+
export async function challengeSecondFactor(services: Services, env: AuthEnv, request: Request, pending: PendingLogin): Promise<Response> {
|
|
65
|
+
const token = await (await getSigner(env)).signInternal(
|
|
66
|
+
{
|
|
67
|
+
sub: pending.principalId,
|
|
68
|
+
idp: pending.idpSub,
|
|
69
|
+
em: pending.email,
|
|
70
|
+
am: pending.authenticationMethod,
|
|
71
|
+
rd: pending.redirect,
|
|
72
|
+
rs: pending.reason,
|
|
73
|
+
ho: pending.handoff,
|
|
74
|
+
dv: pending.rememberDevice,
|
|
75
|
+
},
|
|
76
|
+
SECOND_FACTOR_AUDIENCE,
|
|
77
|
+
SECOND_FACTOR_CHALLENGE_TTL_SECONDS,
|
|
78
|
+
)
|
|
79
|
+
const response = await challengePage(services, request, pending)
|
|
80
|
+
response.headers.append(
|
|
81
|
+
'Set-Cookie',
|
|
82
|
+
serializeCookie(SECOND_FACTOR_COOKIE, token, {
|
|
83
|
+
httpOnly: true,
|
|
84
|
+
secure: true,
|
|
85
|
+
sameSite: 'Lax',
|
|
86
|
+
maxAge: SECOND_FACTOR_CHALLENGE_TTL_SECONDS,
|
|
87
|
+
path: '/',
|
|
88
|
+
}),
|
|
89
|
+
)
|
|
90
|
+
if (pending.authenticationMethod === 'oidc') {
|
|
91
|
+
for (const cookie of endingFlightCookies()) response.headers.append('Set-Cookie', cookie)
|
|
92
|
+
}
|
|
93
|
+
return response
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The code form for `pending`, again with `problem`. Its `form-action` admits the one origin the verified login lands
|
|
98
|
+
* on: the handoff's registered origin, the IAM-chosen landing, or the console for a login with no destination.
|
|
99
|
+
*/
|
|
100
|
+
export async function challengePage(services: Services, request: Request, pending: PendingLogin, problem?: ChallengeProblem): Promise<Response> {
|
|
101
|
+
const presentation = await presentationFor(services, pending.handoff?.app ?? null, { request })
|
|
102
|
+
const destination = pending.handoff?.returnUrl ?? pending.redirect ?? await installationConsole(services)
|
|
103
|
+
const origin = destination === null ? null : normalizeOrigin(destination)
|
|
104
|
+
return secondFactorChallengePage({
|
|
105
|
+
presentation,
|
|
106
|
+
...(origin === null ? {} : { redirectOrigin: origin }),
|
|
107
|
+
...(problem === undefined ? {} : { problem }),
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The `Set-Cookie` that spends the challenge. */
|
|
112
|
+
export function endingChallengeCookie(): string {
|
|
113
|
+
return clearCookie(SECOND_FACTOR_COOKIE, { path: '/' })
|
|
114
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// The second factor: verifying the code of a sign-in that proved its first factor, and enrolling an authenticator app.
|
|
2
|
+
// A TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`); recovery codes are stored as hashes only.
|
|
3
|
+
|
|
4
|
+
import { IAM_APP } from '../admin/router'
|
|
5
|
+
import { type AppPresentation, INSTALLATION_PRESENTATION, installationLanding } from '../app-presentation'
|
|
6
|
+
import { openValue, sealValue } from '../data-key'
|
|
7
|
+
import type { AuditEventInput, PrincipalRow } from '../db'
|
|
8
|
+
import type { RequestContext } from '../env'
|
|
9
|
+
import { installationBrand } from '../installation-brand'
|
|
10
|
+
import { logError } from '../log'
|
|
11
|
+
import { authFailurePage } from '../password-pages'
|
|
12
|
+
import { readerLocale } from '../person-locale'
|
|
13
|
+
import { sealedValueOf } from '../repositories/second-factors'
|
|
14
|
+
import { unixNow } from '../repositories/sql'
|
|
15
|
+
import {
|
|
16
|
+
type EnrolPageBase,
|
|
17
|
+
recoveryCodesPage,
|
|
18
|
+
SECOND_FACTOR_ENROL_PATH,
|
|
19
|
+
secondFactorEnrolledPage,
|
|
20
|
+
secondFactorEnrolPage,
|
|
21
|
+
secondFactorIntroPage,
|
|
22
|
+
secondFactorUnavailablePage,
|
|
23
|
+
} from '../second-factor-pages'
|
|
24
|
+
import { hashToken } from '../secret'
|
|
25
|
+
import type { Services } from '../services'
|
|
26
|
+
import {
|
|
27
|
+
base32,
|
|
28
|
+
generateRecoveryCodes,
|
|
29
|
+
generateTotpSecret,
|
|
30
|
+
matchingStep,
|
|
31
|
+
otpauthUri,
|
|
32
|
+
parseRecoveryCode,
|
|
33
|
+
parseTotpCode,
|
|
34
|
+
qrCodeDataUri,
|
|
35
|
+
recoveryCodeHash,
|
|
36
|
+
} from '../totp'
|
|
37
|
+
import { readForm, redirectHeaders, sameOrigin, stringValue } from './http'
|
|
38
|
+
import type { AuthEnv } from './oidc-flight'
|
|
39
|
+
import { challengePage, type PendingLogin, readPendingLogin } from './second-factor-challenge'
|
|
40
|
+
import { administersIam, type CurrentLogin, currentLogin, issueSession, refuseLogin } from './sessions'
|
|
41
|
+
|
|
42
|
+
/** Codes one account may try in a window before the next waits out the block: a burst, not a person mistyping. */
|
|
43
|
+
export const SECOND_FACTOR_MAX_ATTEMPTS = 5
|
|
44
|
+
const SECOND_FACTOR_WINDOW_SECONDS = 15 * 60
|
|
45
|
+
const SECOND_FACTOR_BLOCK_SECONDS = 15 * 60
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The code form's POST. The pending login comes from the challenge cookie only. Each attempt is counted per account
|
|
49
|
+
* before the code is checked, from the row the counting statement returns, so a parallel burst gets no more than
|
|
50
|
+
* `SECOND_FACTOR_MAX_ATTEMPTS` checks; the attempt that starts a block writes `iam.second_factor.throttle` to the
|
|
51
|
+
* audit log. Every refusal writes its `auth_log` row; an accepted code opens the login through `issueSession`.
|
|
52
|
+
*/
|
|
53
|
+
export async function handleSecondFactor(
|
|
54
|
+
request: Request,
|
|
55
|
+
services: Services,
|
|
56
|
+
env: AuthEnv,
|
|
57
|
+
ctx: RequestContext,
|
|
58
|
+
requestId: string,
|
|
59
|
+
): Promise<Response> {
|
|
60
|
+
const readerFailure = (): AppPresentation => ({ ...INSTALLATION_PRESENTATION, locale: readerLocale(request) })
|
|
61
|
+
if (!sameOrigin(request, services.config)) {
|
|
62
|
+
return refuseLogin(
|
|
63
|
+
services,
|
|
64
|
+
request,
|
|
65
|
+
{ requestId, principalId: null, reason: 'login_cross_origin' },
|
|
66
|
+
() => authFailurePage(readerFailure(), { kind: 'cross_origin' }, 403),
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
const pending = await readPendingLogin(env, request)
|
|
70
|
+
if (pending === null) {
|
|
71
|
+
return refuseLogin(
|
|
72
|
+
services,
|
|
73
|
+
request,
|
|
74
|
+
{ requestId, principalId: null, reason: 'second_factor_expired' },
|
|
75
|
+
() => authFailurePage(readerFailure(), { kind: 'second_factor_expired' }, 400),
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
// The held login is up to five minutes old: a principal disabled, or a method switched off, since then signs in no more.
|
|
79
|
+
const principal = await services.repositories.principals.getPrincipalById(pending.principalId)
|
|
80
|
+
const methodEnabled = pending.authenticationMethod === 'oidc'
|
|
81
|
+
? services.config.authentication.oidc.enabled
|
|
82
|
+
: services.config.authentication.password.enabled
|
|
83
|
+
if (principal === null || principal.disabled_at !== null || !methodEnabled) {
|
|
84
|
+
return refuseLogin(
|
|
85
|
+
services,
|
|
86
|
+
request,
|
|
87
|
+
{ requestId, principalId: principal === null ? null : pending.principalId, reason: 'second_factor_expired' },
|
|
88
|
+
() => authFailurePage(readerFailure(), { kind: 'second_factor_expired' }, 400),
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
const form = await readForm(request)
|
|
92
|
+
const submitted = stringValue(form?.get('code') ?? null) ?? ''
|
|
93
|
+
const refuse = (reason: 'second_factor_invalid' | 'second_factor_throttled', problem: 'invalid' | 'throttled' | 'app_codes_unavailable') =>
|
|
94
|
+
refuseLogin(services, request, { requestId, principalId: pending.principalId, reason }, () => challengePage(services, request, pending, problem))
|
|
95
|
+
|
|
96
|
+
const attempt = await countAttempt(services, pending.principalId, requestId)
|
|
97
|
+
if (attempt === 'blocked') return refuse('second_factor_throttled', 'throttled')
|
|
98
|
+
|
|
99
|
+
const outcome = await verifySecondFactor(services, pending, submitted, requestId)
|
|
100
|
+
if (outcome === 'app_codes_unavailable') return refuse('second_factor_invalid', 'app_codes_unavailable')
|
|
101
|
+
if (outcome === 'invalid') return refuse('second_factor_invalid', 'invalid')
|
|
102
|
+
|
|
103
|
+
await services.repositories.passwords.clearLoginFailures(await attemptKey(pending.principalId))
|
|
104
|
+
return issueSession(request, services, env, ctx, {
|
|
105
|
+
principalId: pending.principalId,
|
|
106
|
+
idpSub: pending.idpSub,
|
|
107
|
+
email: pending.email,
|
|
108
|
+
authenticationMethod: pending.authenticationMethod,
|
|
109
|
+
redirect: pending.redirect,
|
|
110
|
+
reason: pending.reason,
|
|
111
|
+
requestId,
|
|
112
|
+
handoff: pending.handoff,
|
|
113
|
+
rememberDevice: pending.rememberDevice,
|
|
114
|
+
secondFactor: 'verified',
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function attemptKey(principalId: string): Promise<string> {
|
|
119
|
+
return hashToken(`second-factor:account:${principalId}`)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Count one attempt and decide from the row the counting statement returns. The attempt that turns the bucket from
|
|
124
|
+
* open to blocked records the burst; the ones refused after it do not, so a burst is one audit row.
|
|
125
|
+
*/
|
|
126
|
+
async function countAttempt(services: Services, principalId: string, requestId: string): Promise<'admitted' | 'blocked'> {
|
|
127
|
+
const key = await attemptKey(principalId)
|
|
128
|
+
const now = unixNow()
|
|
129
|
+
const before = await services.repositories.passwords.getLoginThrottle(key)
|
|
130
|
+
const row = await services.repositories.passwords.recordLoginFailure({
|
|
131
|
+
loginKeyHash: key,
|
|
132
|
+
windowSeconds: SECOND_FACTOR_WINDOW_SECONDS,
|
|
133
|
+
// The attempt that reaches the limit is the first one refused, so the limit is one past the admitted attempts.
|
|
134
|
+
maxAttempts: SECOND_FACTOR_MAX_ATTEMPTS + 1,
|
|
135
|
+
blockSeconds: SECOND_FACTOR_BLOCK_SECONDS,
|
|
136
|
+
})
|
|
137
|
+
if ((row.blocked_until ?? 0) <= now) return 'admitted'
|
|
138
|
+
if ((before?.blocked_until ?? 0) <= now) {
|
|
139
|
+
await services.repositories.audit.writeAuditEvent(selfEvent(requestId, principalId, 'iam.second_factor.throttle', {
|
|
140
|
+
attempts: SECOND_FACTOR_MAX_ATTEMPTS,
|
|
141
|
+
blockedUntil: row.blocked_until,
|
|
142
|
+
}))
|
|
143
|
+
}
|
|
144
|
+
return 'blocked'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* A six-digit code is checked against the sealed secret and accepted once per time step; anything shaped like a
|
|
149
|
+
* recovery code spends one. A code the data key cannot check (unset, or a key that does not open the secret) is
|
|
150
|
+
* `app_codes_unavailable`, so a recovery code still signs the person in.
|
|
151
|
+
*/
|
|
152
|
+
async function verifySecondFactor(
|
|
153
|
+
services: Services,
|
|
154
|
+
pending: PendingLogin,
|
|
155
|
+
submitted: string,
|
|
156
|
+
requestId: string,
|
|
157
|
+
): Promise<'verified' | 'invalid' | 'app_codes_unavailable'> {
|
|
158
|
+
const code = parseTotpCode(submitted)
|
|
159
|
+
if (code !== null) {
|
|
160
|
+
const factor = await services.repositories.secondFactors.get(pending.principalId)
|
|
161
|
+
if (factor === null || factor.confirmed_at === null) return 'invalid'
|
|
162
|
+
if (services.dataKey === null) return 'app_codes_unavailable'
|
|
163
|
+
let secret: Uint8Array<ArrayBuffer>
|
|
164
|
+
try {
|
|
165
|
+
secret = await openValue(services.dataKey, pending.principalId, sealedValueOf(factor))
|
|
166
|
+
} catch (err) {
|
|
167
|
+
logError(`the authenticator of request '${requestId}' could not be opened with FABRIKA_IAM_DATA_KEY`, err)
|
|
168
|
+
return 'app_codes_unavailable'
|
|
169
|
+
}
|
|
170
|
+
const step = await matchingStep(secret, code, unixNow(), factor.last_step)
|
|
171
|
+
if (step === null) return 'invalid'
|
|
172
|
+
return await services.repositories.secondFactors.acceptStep(pending.principalId, step) ? 'verified' : 'invalid'
|
|
173
|
+
}
|
|
174
|
+
if (parseRecoveryCode(submitted) !== null) {
|
|
175
|
+
const spent = await services.repositories.secondFactors.spendRecoveryCode(
|
|
176
|
+
pending.principalId,
|
|
177
|
+
await recoveryCodeHash(pending.principalId, submitted),
|
|
178
|
+
selfEvent(requestId, pending.principalId, 'iam.second_factor.recovery_code.use'),
|
|
179
|
+
)
|
|
180
|
+
return spent ? 'verified' : 'invalid'
|
|
181
|
+
}
|
|
182
|
+
return 'invalid'
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Enrolment, on IAM's host, for a signed-in principal that administers (`administersIam`). `GET` shows the state;
|
|
187
|
+
* `POST step=start` seals a new secret that waits for its first code and shows it; `POST step=confirm` checks that
|
|
188
|
+
* code, confirms the factor, replaces the recovery codes and records `iam.second_factor.enrol` in one transaction, and
|
|
189
|
+
* shows the codes once. A confirmed factor is never replaced here: only an administrator's reset removes it.
|
|
190
|
+
*/
|
|
191
|
+
export async function handleSecondFactorEnrolment(request: Request, services: Services, requestId: string): Promise<Response> {
|
|
192
|
+
const locale = readerLocale(request)
|
|
193
|
+
const readerFailure: AppPresentation = { ...INSTALLATION_PRESENTATION, locale }
|
|
194
|
+
if (request.method === 'POST' && !sameOrigin(request, services.config)) {
|
|
195
|
+
return authFailurePage(readerFailure, { kind: 'cross_origin' }, 403)
|
|
196
|
+
}
|
|
197
|
+
const login = await currentLogin(request, services)
|
|
198
|
+
if (login === null) {
|
|
199
|
+
if (request.method === 'POST') return authFailurePage(readerFailure, { kind: 'second_factor_not_allowed' }, 403)
|
|
200
|
+
const back = new URL(SECOND_FACTOR_ENROL_PATH, services.config.issuer).toString()
|
|
201
|
+
return new Response(null, { status: 302, headers: redirectHeaders(`/auth/login?redirect=${encodeURIComponent(back)}`) })
|
|
202
|
+
}
|
|
203
|
+
if (!await administersIam(services, login.principal.id)) {
|
|
204
|
+
return authFailurePage(readerFailure, { kind: 'second_factor_not_allowed' }, 403)
|
|
205
|
+
}
|
|
206
|
+
const brand = await installationBrand(services)
|
|
207
|
+
const page = { brand, locale }
|
|
208
|
+
const status = await services.repositories.secondFactors.status(login.principal.id)
|
|
209
|
+
if (status.confirmedAt !== null) {
|
|
210
|
+
return secondFactorEnrolledPage({ ...page, confirmedAt: status.confirmedAt, recoveryCodesLeft: status.recoveryCodesLeft })
|
|
211
|
+
}
|
|
212
|
+
const dataKey = services.dataKey
|
|
213
|
+
if (dataKey === null) return secondFactorUnavailablePage(page)
|
|
214
|
+
if (request.method === 'GET') return secondFactorIntroPage(page)
|
|
215
|
+
|
|
216
|
+
const form = await readForm(request)
|
|
217
|
+
const step = stringValue(form?.get('step') ?? null)
|
|
218
|
+
if (step === 'start') {
|
|
219
|
+
const secret = generateTotpSecret()
|
|
220
|
+
if (!await services.repositories.secondFactors.begin(login.principal.id, await sealValue(dataKey, login.principal.id, secret))) {
|
|
221
|
+
return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 409)
|
|
222
|
+
}
|
|
223
|
+
return enrolPage(services, login, secret, page)
|
|
224
|
+
}
|
|
225
|
+
if (step !== 'confirm') return authFailurePage(readerFailure, { kind: 'malformed_form' }, 400)
|
|
226
|
+
|
|
227
|
+
const factor = await services.repositories.secondFactors.get(login.principal.id)
|
|
228
|
+
if (factor === null) return secondFactorIntroPage(page)
|
|
229
|
+
let secret: Uint8Array<ArrayBuffer>
|
|
230
|
+
try {
|
|
231
|
+
secret = await openValue(dataKey, login.principal.id, sealedValueOf(factor))
|
|
232
|
+
} catch (err) {
|
|
233
|
+
logError(`a waiting authenticator could not be opened for request '${requestId}'`, err)
|
|
234
|
+
return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 503)
|
|
235
|
+
}
|
|
236
|
+
const code = parseTotpCode(stringValue(form?.get('code') ?? null) ?? '')
|
|
237
|
+
const matched = code === null ? null : await matchingStep(secret, code, unixNow(), null)
|
|
238
|
+
if (matched === null) return enrolPage(services, login, secret, page, true)
|
|
239
|
+
|
|
240
|
+
const codes = generateRecoveryCodes()
|
|
241
|
+
const confirmed = await services.repositories.secondFactors.confirm(
|
|
242
|
+
{
|
|
243
|
+
principalId: login.principal.id,
|
|
244
|
+
ciphertext: factor.ciphertext,
|
|
245
|
+
step: matched,
|
|
246
|
+
recoveryCodeHashes: await Promise.all(codes.map((recovery) => recoveryCodeHash(login.principal.id, recovery))),
|
|
247
|
+
},
|
|
248
|
+
selfEvent(requestId, login.principal.id, 'iam.second_factor.enrol', { recoveryCodes: codes.length }),
|
|
249
|
+
)
|
|
250
|
+
if (!confirmed) return authFailurePage(readerFailure, { kind: 'second_factor_unavailable' }, 409)
|
|
251
|
+
return recoveryCodesPage({ ...page, codes, landing: await installationLanding(services) })
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function enrolPage(services: Services, login: CurrentLogin, secret: Uint8Array<ArrayBuffer>, page: EnrolPageBase, invalidCode?: boolean): Response {
|
|
255
|
+
const uri = otpauthUri({ issuer: new URL(services.config.issuer).hostname, account: accountName(login.principal), secret })
|
|
256
|
+
return secondFactorEnrolPage({ ...page, qrCode: qrCodeDataUri(uri), key: base32(secret), ...(invalidCode === true ? { invalidCode } : {}) })
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** What the authenticator app lists the entry as: the person's sign-in address, as the person knows it. */
|
|
260
|
+
function accountName(principal: PrincipalRow): string {
|
|
261
|
+
return principal.label ?? principal.email ?? principal.id
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** A principal's own change to its second factor: by it, about it, with no email in it. */
|
|
265
|
+
function selfEvent(requestId: string, principalId: string, action: string, metadata?: unknown): AuditEventInput {
|
|
266
|
+
return {
|
|
267
|
+
requestId,
|
|
268
|
+
principalId,
|
|
269
|
+
principalLabel: principalId,
|
|
270
|
+
app: IAM_APP,
|
|
271
|
+
action,
|
|
272
|
+
resourceType: 'principal',
|
|
273
|
+
resourceId: principalId,
|
|
274
|
+
...(metadata === undefined ? {} : { metadata }),
|
|
275
|
+
}
|
|
276
|
+
}
|
package/src/auth/sessions.ts
CHANGED
|
@@ -17,7 +17,9 @@ import { type Handoff, handoffLocation } from './handoff'
|
|
|
17
17
|
import { authFailurePage } from '../password-pages'
|
|
18
18
|
import { redirectHeaders, safeRedirect, sameOrigin } from './http'
|
|
19
19
|
|
|
20
|
-
import {
|
|
20
|
+
import { knownDeviceCookie } from './known-device'
|
|
21
|
+
import { type AuthEnv, endingFlightCookies } from './oidc-flight'
|
|
22
|
+
import { challengeSecondFactor, endingChallengeCookie } from './second-factor-challenge'
|
|
21
23
|
|
|
22
24
|
/** SSO session lifetime — the long-lived credential a browser carries (30 days). */
|
|
23
25
|
const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
|
|
@@ -37,7 +39,7 @@ export async function currentSession(request: Request, services: Services) {
|
|
|
37
39
|
return null
|
|
38
40
|
}
|
|
39
41
|
// And a session whose method is no longer enabled must not silently father a handoff.
|
|
40
|
-
return sessionUsable(session, services.config) ? session : null
|
|
42
|
+
return sessionUsable(session, services.config, Math.floor(Date.now() / 1000)) ? session : null
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
/** A login a handoff may continue: the browser's IAM session and its principal, an active user. */
|
|
@@ -55,32 +57,72 @@ export async function currentLogin(request: Request, services: Services): Promis
|
|
|
55
57
|
return { session, principal }
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
/** A login a proven first factor opens. */
|
|
61
|
+
export interface LoginInput {
|
|
62
|
+
principalId: string
|
|
63
|
+
idpSub?: string | null
|
|
64
|
+
email?: string | null
|
|
65
|
+
authenticationMethod?: AuthenticationMethod
|
|
66
|
+
/** Where the login lands; null for no destination of its own, which is the installation's landing. */
|
|
67
|
+
redirect: string | null
|
|
68
|
+
reason: string
|
|
69
|
+
/** The correlation id the composition root allowed; see `src/request-id.ts`. */
|
|
70
|
+
requestId: string
|
|
71
|
+
clearOidc?: boolean
|
|
72
|
+
/** When set, land on the app's callback with a code instead of on `redirect` (ADR-0022). */
|
|
73
|
+
handoff?: Handoff | null
|
|
74
|
+
/** Set the known-device cookie once the login is recorded: a password login's (`auth/known-device.ts`). */
|
|
75
|
+
rememberDevice?: boolean
|
|
76
|
+
/** Set only by the second-factor form, after the principal's code or recovery code was accepted. */
|
|
77
|
+
secondFactor?: 'verified'
|
|
78
|
+
}
|
|
79
|
+
|
|
58
80
|
/**
|
|
59
81
|
* Open a login: the session and its `auth_log` row are written in one batch, before the answer. A login that cannot
|
|
60
82
|
* be logged opens no session and answers 503. A principal that administers at IAM, the installation or the people of
|
|
61
83
|
* an application (ADR-0058), is logged `privileged`.
|
|
84
|
+
*
|
|
85
|
+
* A principal with a confirmed second factor gets no session here until its code is verified: the answer is the code
|
|
86
|
+
* form and a challenge cookie holding this login (`second-factor-challenge.ts`). Every password, OIDC, password-action
|
|
87
|
+
* and invitation login passes through here, so none skips the factor; only the local-dev bypass does, which no
|
|
88
|
+
* installation outside `ENVIRONMENT=local` serves. A terminal's assertion (`identification.ts`) opens no session here
|
|
89
|
+
* and asks no factor: it reaches only the asserting application, never IAM's administration.
|
|
62
90
|
*/
|
|
63
91
|
export async function issueSession(
|
|
64
92
|
request: Request,
|
|
65
93
|
services: Services,
|
|
94
|
+
env: AuthEnv,
|
|
66
95
|
ctx: RequestContext,
|
|
67
|
-
input:
|
|
68
|
-
principalId: string
|
|
69
|
-
idpSub?: string | null
|
|
70
|
-
email?: string | null
|
|
71
|
-
authenticationMethod?: AuthenticationMethod
|
|
72
|
-
/** Where the login lands; null for no destination of its own, which is the installation's landing. */
|
|
73
|
-
redirect: string | null
|
|
74
|
-
reason: string
|
|
75
|
-
/** The correlation id the composition root allowed; see `src/request-id.ts`. */
|
|
76
|
-
requestId: string
|
|
77
|
-
clearOidc?: boolean
|
|
78
|
-
/** When set, land on the app's callback with a code instead of on `redirect` (ADR-0022). */
|
|
79
|
-
handoff?: Handoff | null
|
|
80
|
-
},
|
|
96
|
+
input: LoginInput,
|
|
81
97
|
): Promise<Response> {
|
|
98
|
+
const method = input.authenticationMethod ?? 'oidc'
|
|
99
|
+
if (input.secondFactor !== 'verified' && (method === 'oidc' || method === 'password')) {
|
|
100
|
+
let required: boolean
|
|
101
|
+
try {
|
|
102
|
+
required = await services.repositories.secondFactors.isConfirmed(input.principalId)
|
|
103
|
+
} catch (err) {
|
|
104
|
+
logError(`the second factor of login for request '${input.requestId}' could not be read`, err)
|
|
105
|
+
return authFailurePage(await installationPresentation(services, { request }), { kind: 'login_unavailable' }, 503)
|
|
106
|
+
}
|
|
107
|
+
if (required) {
|
|
108
|
+
return challengeSecondFactor(services, env, request, {
|
|
109
|
+
principalId: input.principalId,
|
|
110
|
+
idpSub: input.idpSub ?? null,
|
|
111
|
+
email: input.email ?? null,
|
|
112
|
+
authenticationMethod: method,
|
|
113
|
+
redirect: input.redirect,
|
|
114
|
+
reason: input.reason,
|
|
115
|
+
handoff: input.handoff ?? null,
|
|
116
|
+
rememberDevice: input.rememberDevice === true,
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
}
|
|
82
120
|
const sessionToken = randomToken(32)
|
|
83
|
-
|
|
121
|
+
// An OIDC login stores the installation's cap as its expiry, so its app sessions, OAuth grants and cookie end with it.
|
|
122
|
+
const lifetime = (input.authenticationMethod ?? 'oidc') === 'oidc'
|
|
123
|
+
? Math.min(SESSION_TTL_SECONDS, services.config.authentication.oidc.sessionCapSeconds)
|
|
124
|
+
: SESSION_TTL_SECONDS
|
|
125
|
+
const expiresAt = Math.floor(Date.now() / 1000) + lifetime
|
|
84
126
|
let sessionId: string
|
|
85
127
|
try {
|
|
86
128
|
sessionId = await services.repositories.sessions.createSession({
|
|
@@ -110,7 +152,7 @@ export async function issueSession(
|
|
|
110
152
|
? input.redirect ?? await installationLanding(services)
|
|
111
153
|
: await handoffLocation(services, input.handoff, sessionId)
|
|
112
154
|
const headers = redirectHeaders(location)
|
|
113
|
-
headers.append('Set-Cookie', sessionCookie(sessionToken))
|
|
155
|
+
headers.append('Set-Cookie', sessionCookie(sessionToken, lifetime))
|
|
114
156
|
// A person with a language of their own keeps it on this browser's next sign-in page here (`LOCALE_COOKIE`); one
|
|
115
157
|
// without clears the language a previous person left on a shared browser.
|
|
116
158
|
// The session has committed and the cookie picks words only: a failed read leaves the remembered language as it is.
|
|
@@ -129,6 +171,12 @@ export async function issueSession(
|
|
|
129
171
|
headers.append('Set-Cookie', cookie)
|
|
130
172
|
}
|
|
131
173
|
}
|
|
174
|
+
if (input.secondFactor === 'verified') {
|
|
175
|
+
headers.append('Set-Cookie', endingChallengeCookie())
|
|
176
|
+
}
|
|
177
|
+
if (input.rememberDevice === true) {
|
|
178
|
+
headers.append('Set-Cookie', await knownDeviceCookie(env, input.principalId))
|
|
179
|
+
}
|
|
132
180
|
return new Response(null, { status: 302, headers })
|
|
133
181
|
}
|
|
134
182
|
|
|
@@ -151,6 +199,9 @@ export type LoginRefusal =
|
|
|
151
199
|
| 'oidc_unknown_principal'
|
|
152
200
|
| 'oidc_external_principal'
|
|
153
201
|
| 'local_login_refused'
|
|
202
|
+
| 'second_factor_invalid'
|
|
203
|
+
| 'second_factor_throttled'
|
|
204
|
+
| 'second_factor_expired'
|
|
154
205
|
|
|
155
206
|
export async function refuseLogin(
|
|
156
207
|
services: Services,
|
|
@@ -236,14 +287,14 @@ export function signedOutRedirect(location: string): Response {
|
|
|
236
287
|
* TLS-TERMINATING BALANCER (the socket is plain HTTP, the browser spoke HTTPS) and over plain HTTP on
|
|
237
288
|
* `localhost` / `*.localhost`, which browsers treat as potentially trustworthy. An installation
|
|
238
289
|
* served over cleartext HTTP on a public hostname can hold no session at all — which is the correct
|
|
239
|
-
* outcome for a 30
|
|
290
|
+
* outcome for a credential that lasts up to 30 days, not a regression to work around.
|
|
240
291
|
*/
|
|
241
|
-
function sessionCookie(value: string): string {
|
|
292
|
+
function sessionCookie(value: string, maxAge: number): string {
|
|
242
293
|
return serializeCookie(SESSION_COOKIE, value, {
|
|
243
294
|
httpOnly: true,
|
|
244
295
|
secure: true,
|
|
245
296
|
sameSite: 'Lax',
|
|
246
|
-
maxAge
|
|
297
|
+
maxAge,
|
|
247
298
|
path: '/',
|
|
248
299
|
})
|
|
249
300
|
}
|
package/src/auth.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { API_KEY_PREFIX, isWorkloadKind, type PermissionEntry, type PrincipalType, type TokenPrincipalType } from '@fabrika/auth-core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { SignedInSessionRow } from './db'
|
|
3
3
|
import type { Env } from './env'
|
|
4
4
|
import { hashToken, timingSafeEqualHex } from './secret'
|
|
5
5
|
import type { Config, Services } from './services'
|
|
@@ -11,23 +11,28 @@ export const LOCAL_DEV_ADMIN_ID = 'local-dev-admin'
|
|
|
11
11
|
export const LOCAL_DEV_ADMIN_EMAIL = 'admin@local.test'
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
|
-
* May this session still be used, given what the installation enables NOW?
|
|
14
|
+
* May this session still be used at `now` (unix seconds), given what the installation enables NOW?
|
|
15
15
|
*
|
|
16
16
|
* **Checked at USE, not at creation, and that is the point.** Turning a method off changes what the
|
|
17
17
|
* next login may do and nothing about what was already issued. Sessions live 30 days, so an
|
|
18
18
|
* installation that moved to password-only kept honouring every OIDC login for a month — and, for the
|
|
19
19
|
* bypass, every one of those is a global admin.
|
|
20
20
|
*
|
|
21
|
+
* An OIDC login is usable for `sessionCapSeconds` after it signed in; then the provider is asked again, so a person
|
|
22
|
+
* blocked there loses access within the cap. Measured here, from the login's sign-in, so it also ends logins issued
|
|
23
|
+
* before the cap was lowered, and the app sessions derived from them.
|
|
24
|
+
*
|
|
21
25
|
* The bypass carries `local_dev` as its own method rather than an exemption
|
|
22
26
|
* here, so this stays a total function over the enum: a method added later has to answer the question.
|
|
23
27
|
*/
|
|
24
28
|
export function sessionUsable(
|
|
25
|
-
session: Pick<
|
|
29
|
+
session: Pick<SignedInSessionRow, 'authentication_method' | 'expires_at' | 'signed_in_at'>,
|
|
26
30
|
config: Pick<Config, 'authentication' | 'localDevLogin'>,
|
|
31
|
+
now: number,
|
|
27
32
|
): boolean {
|
|
28
33
|
switch (session.authentication_method) {
|
|
29
34
|
case 'oidc':
|
|
30
|
-
return config.authentication.oidc.enabled
|
|
35
|
+
return config.authentication.oidc.enabled && now < sessionEndsAt(session, config)
|
|
31
36
|
case 'password':
|
|
32
37
|
return config.authentication.password.enabled
|
|
33
38
|
case 'local_dev':
|
|
@@ -38,6 +43,16 @@ export function sessionUsable(
|
|
|
38
43
|
}
|
|
39
44
|
}
|
|
40
45
|
|
|
46
|
+
/** When a session ends by its own clock: its expiry, or earlier for an OIDC login, its sign-in plus the installation's cap. */
|
|
47
|
+
export function sessionEndsAt(
|
|
48
|
+
session: Pick<SignedInSessionRow, 'authentication_method' | 'expires_at' | 'signed_in_at'>,
|
|
49
|
+
config: Pick<Config, 'authentication'>,
|
|
50
|
+
): number {
|
|
51
|
+
return session.authentication_method === 'oidc'
|
|
52
|
+
? Math.min(session.expires_at, session.signed_in_at + config.authentication.oidc.sessionCapSeconds)
|
|
53
|
+
: session.expires_at
|
|
54
|
+
}
|
|
55
|
+
|
|
41
56
|
/**
|
|
42
57
|
* Fixed identity for the SEEDED PROVISIONING KEY below. A stable `service` principal with this id is
|
|
43
58
|
* seeded into `principals` (migration `0001_init.sql`) so the audit the provisioning
|
package/src/catalog/cs.ts
CHANGED
|
@@ -90,6 +90,12 @@ export const cs: Catalog = {
|
|
|
90
90
|
return 'Registrace teď není k dispozici. Zkuste to později.'
|
|
91
91
|
case 'terminal_completion_refused':
|
|
92
92
|
return 'Toto přihlášení vypršelo nebo už bylo použito. Identifikujte se znovu.'
|
|
93
|
+
case 'second_factor_expired':
|
|
94
|
+
return 'Přihlášení vypršelo dřív, než jste zadali kód. Přihlaste se znovu.'
|
|
95
|
+
case 'second_factor_not_allowed':
|
|
96
|
+
return 'Dvoufázové přihlášení si nastavíte po přihlášení účtem administrátora.'
|
|
97
|
+
case 'second_factor_unavailable':
|
|
98
|
+
return 'Dvoufázové přihlášení teď není k dispozici. Zkuste to později.'
|
|
93
99
|
}
|
|
94
100
|
},
|
|
95
101
|
},
|
|
@@ -113,6 +119,32 @@ export const cs: Catalog = {
|
|
|
113
119
|
enrolledTitle: 'Terminál je zaregistrovaný',
|
|
114
120
|
enrolledText: (label) => `Tento prohlížeč je teď terminál ${label}. Jste odhlášeni. Které aplikace obsluhuje, nastaví administrátor.`,
|
|
115
121
|
},
|
|
122
|
+
secondFactor: {
|
|
123
|
+
challengeTitle: 'Dvoufázové přihlášení',
|
|
124
|
+
challengeText: 'Zadejte šestimístný kód z ověřovací aplikace, nebo jeden ze svých záložních kódů.',
|
|
125
|
+
codeLabel: 'Kód',
|
|
126
|
+
submit: 'Ověřit',
|
|
127
|
+
invalidCode: 'Tento kód neplatí. Zadejte aktuální kód, nebo záložní kód, který jste ještě nepoužili.',
|
|
128
|
+
throttled: 'Příliš mnoho chybných kódů. Počkejte 15 minut a zkuste to znovu.',
|
|
129
|
+
appCodesUnavailable: 'Kódy z ověřovací aplikace tu teď nejde ověřit. Použijte záložní kód, nebo se obraťte na administrátora.',
|
|
130
|
+
startOver: 'Přihlásit se znovu',
|
|
131
|
+
enrolTitle: 'Nastavit dvoufázové přihlášení',
|
|
132
|
+
enrolText:
|
|
133
|
+
'Po hesle nebo jednotném přihlášení si každé přihlášení k tomuto účtu vyžádá kód z ověřovací aplikace ve vašem telefonu. Dostanete také záložní kódy pro chvíle, kdy telefon nemáte po ruce.',
|
|
134
|
+
start: 'Nastavit ověřovací aplikaci',
|
|
135
|
+
scanText: 'Naskenujte QR kód ověřovací aplikací, nebo do ní opište klíč. Pak zadejte šestimístný kód, který zobrazí.',
|
|
136
|
+
secretLabel: 'Klíč',
|
|
137
|
+
confirmLabel: 'Kód z aplikace',
|
|
138
|
+
confirm: 'Zapnout dvoufázové přihlášení',
|
|
139
|
+
enrolledTitle: 'Dvoufázové přihlášení je zapnuté',
|
|
140
|
+
enrolledText: (enrolledOn, left) =>
|
|
141
|
+
`Od ${enrolledOn} si každé přihlášení k tomuto účtu vyžádá kód. Zbývající záložní kódy: ${left}. Při přechodu na nový telefon požádejte administrátora o zrušení ověřovací aplikace.`,
|
|
142
|
+
recoveryTitle: 'Uložte si záložní kódy',
|
|
143
|
+
recoveryText: 'Každý kód vás jednou přihlásí, když telefon nemáte po ruce. Zobrazují se jen teď: uložte je na bezpečné místo mimo telefon.',
|
|
144
|
+
continue: 'Pokračovat',
|
|
145
|
+
unavailableTitle: 'Dvoufázové přihlášení není k dispozici',
|
|
146
|
+
unavailableText: 'Tato instalace zatím neumí ukládat klíče ověřovacích aplikací. Požádejte jejího provozovatele o nastavení.',
|
|
147
|
+
},
|
|
116
148
|
invitation: {
|
|
117
149
|
title: 'Přijetí pozvánky',
|
|
118
150
|
text: 'Přijměte pozvánku. V dalším kroku se přihlásíte pozvanou adresou, nebo si zvolíte heslo, pokud pozvánka zakládá nový účet.',
|