@sssb/kit 0.7.0 → 0.8.0

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/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"1afa32103ec8db683cacb679224809baa89457b6"}
1
+ {"commit":"80b2e6707b2431643c0b903a30a2d888ee697327"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The origins whose Clerk session tokens this deployment accepts: `CLERK_AUTHORIZED_PARTIES`, the app's own origins,
3
+ * comma-separated (`https://app.example.org,https://preview.example.org`), handed to Clerk's middleware as
4
+ * `authorizedParties` (./clerk-proxy.ts). Unset, it is `undefined` and Clerk accepts any session token its instance
5
+ * signed, as before the setting existed.
6
+ *
7
+ * What Clerk does with it (@clerk/backend 3.29, `assertAuthorizedPartiesClaim`, run on every session token it verifies:
8
+ * the cookie's, a refreshed one's and a handshake's): a token whose `azp` claim is not exactly one of the listed strings
9
+ * is refused, and so is a token with no `azp` at all; the request is then signed out, with no handshake. It compares
10
+ * strings, never origins, so `https://App.example.org` or a trailing slash would match nothing and sign everyone out.
11
+ * An empty list turns the check off. So every entry is held to the form Clerk's own `azp` takes, the browser's origin
12
+ * (`new URL(entry).origin`), and a value that would leave the check off while looking set is refused rather than
13
+ * ignored.
14
+ *
15
+ * Refused, with the reason: an empty value or entry, a wildcard (Clerk has none), anything that is not exactly its own
16
+ * origin (a path, a query, a trailing slash, upper case, a default port, user info), a scheme other than `https`, but
17
+ * `http` for the loopback hosts (`localhost`, `127.0.0.1`, `[::1]`), and a duplicate.
18
+ */
19
+ export function clerkAuthorizedParties(value: string | undefined): string[] | undefined {
20
+ if (value === undefined) return undefined
21
+ const entries = value.split(',').map((entry) => entry.trim())
22
+ const problems = entries.map((entry, index) => {
23
+ const problem = originProblem(entry)
24
+ if (problem) return `"${entry}" ${problem}`
25
+ return entries.indexOf(entry) === index ? null : `"${entry}" is listed twice`
26
+ })
27
+ const found = problems.filter((problem): problem is string => problem !== null)
28
+ if (found.length > 0) {
29
+ throw new Error(
30
+ `CLERK_AUTHORIZED_PARTIES: ${found.join('; ')}. List the origins the app is served from ` +
31
+ '(https://host[:port]), comma-separated, or unset it to accept a session token from any origin',
32
+ )
33
+ }
34
+ return entries
35
+ }
36
+
37
+ /** The hosts a browser reaches on the machine itself, the only ones served over plain `http` in a real run. */
38
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
39
+
40
+ function originProblem(entry: string): string | null {
41
+ if (entry === '') return 'is empty (an empty list would turn the check off)'
42
+ if (entry.includes('*')) return 'is a wildcard, which Clerk does not expand: list each origin'
43
+ let url: URL
44
+ try {
45
+ url = new URL(entry)
46
+ } catch {
47
+ return 'is not a URL'
48
+ }
49
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK.has(url.hostname))) {
50
+ return 'is not https (http is for localhost, 127.0.0.1 and [::1] only)'
51
+ }
52
+ if (url.origin !== entry) return `is not a bare origin: write it as ${url.origin}`
53
+ return null
54
+ }
@@ -1,6 +1,7 @@
1
1
  import { createPublicKey } from 'node:crypto'
2
2
  import { clerkMiddleware } from '@clerk/nextjs/server'
3
3
  import { NextRequest, type NextFetchEvent, type NextProxy } from 'next/server'
4
+ import { clerkAuthorizedParties } from './clerk-authorized-parties'
4
5
 
5
6
  /**
6
7
  * Real mode's half of `withAuthProxy` (../proxy.ts): the app's proxy run inside Clerk's `clerkMiddleware`, which the
@@ -24,11 +25,18 @@ import { NextRequest, type NextFetchEvent, type NextProxy } from 'next/server'
24
25
  * - A session token whose key id Clerk has not cached, which makes Clerk fetch its signing keys. `CLERK_JWT_KEY` stops
25
26
  * that: Clerk does not read it from the environment, so it is passed on here as `jwtKey`, and Clerk then verifies
26
27
  * every session token locally.
28
+ *
29
+ * `CLERK_AUTHORIZED_PARTIES`, the app's own origins, is passed on as `authorizedParties` the same way (Clerk does not
30
+ * read it from the environment either), and refused at once if it is malformed (./clerk-authorized-parties.ts). With
31
+ * it, Clerk refuses a session token minted for any other origin, or naming none. This is the one place SSSB verifies a
32
+ * Clerk session token: the auth adapter's `auth()` and `currentUser()` (./auth.ts) read what this middleware decided,
33
+ * from the request headers it writes over any a client sent, and do not verify the token again.
27
34
  */
28
35
  export function withClerk(
29
36
  proxy: NextProxy,
30
37
  ): (request: NextRequest, event: NextFetchEvent) => Promise<Response | null | undefined | void> {
31
38
  const jwtKey = clerkJwtKey(process.env['CLERK_JWT_KEY'])
39
+ const authorizedParties = clerkAuthorizedParties(process.env['CLERK_AUTHORIZED_PARTIES'])
32
40
  // Clerk hands its handler the request it was given, which may be the copy: the app's proxy gets the original. What
33
41
  // the handler learns (whether the app's proxy listed the headers to forward) decides whether Authorization is put
34
42
  // back.
@@ -41,7 +49,7 @@ export function withClerk(
41
49
  state.proxyListed = Boolean(response?.headers.get(OVERRIDE))
42
50
  return response
43
51
  },
44
- jwtKey ? { jwtKey } : {},
52
+ { ...(jwtKey && { jwtKey }), ...(authorizedParties && { authorizedParties }) },
45
53
  )
46
54
  return async (request, event) => {
47
55
  const authorization = request.headers.get('authorization')
@@ -12,6 +12,7 @@ import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
12
  import { configuredAuth } from '../configured-auth'
13
13
  import { orgNameForSlugs } from '../../db/org-lookup'
14
14
  import { clerkIdentitySource, realAuth } from './auth'
15
+ import { clerkAuthorizedParties } from './clerk-authorized-parties'
15
16
  import { DATABASE_ENV, databaseResumeBudgetMs, databaseTransport } from './database-transport'
16
17
  import { noAnalytics } from './no-analytics'
17
18
  import { optionalPortsEnv, portChoice } from './optional-ports'
@@ -90,6 +91,13 @@ export function assertRealEnv(): void {
90
91
  problem = (error as Error).message
91
92
  }
92
93
  if (problem) throw new CutoverPendingError(['auth-tenancy'], problem)
94
+ // The origins Clerk accepts session tokens from, optional: Clerk's middleware refuses a malformed list when it loads
95
+ // (./clerk-proxy.ts), and this refuses it too, so `sssb check-real-env` reports it before a deploy.
96
+ try {
97
+ clerkAuthorizedParties(process.env['CLERK_AUTHORIZED_PARTIES'])
98
+ } catch (error) {
99
+ throw new CutoverPendingError(['auth-dev'], (error as Error).message)
100
+ }
93
101
  }
94
102
 
95
103
  /**
@@ -3,57 +3,151 @@
3
3
  import { useSignIn } from '@clerk/nextjs'
4
4
  import { Button, PasswordInput, Stack, Text, TextInput } from '@mantine/core'
5
5
  import { useForm } from '@mantine/form'
6
- import { useState } from 'react'
6
+ import { useTranslations } from 'next-intl'
7
+ import { useEffect, useRef, useState } from 'react'
7
8
 
9
+ import { SecondFactorStep, type SecondFactor, type SecondFactorKind } from '../../components/auth/second-factor-step'
8
10
  import { sameOriginPath } from '../../core/same-origin-path'
9
11
 
12
+ type SignIn = ReturnType<typeof useSignIn>['signIn']
13
+
10
14
  /**
11
- * Clerk-headless credential form (ADR-0003) using @clerk/nextjs v7's signals API
12
- * (signIn.password → status → finalize). MFA verification (status 'needs_second_factor') is a
13
- * documented follow-up slice — see ADR-0003's MFA rider seam.
15
+ * Clerk-headless credential form (ADR-0003) using @clerk/nextjs v7's signals API: `signIn.password`, then `status`, then
16
+ * `finalize`, with `signIn.mfa` between them when Clerk asks for a second step.
17
+ *
18
+ * Only `complete` finishes a sign-in: Clerk gives an attempt a session (`createdSessionId`, which `finalize` needs) at
19
+ * no other status, and the form calls `finalize` at no other. Every other status goes one of three ways (`proceed`):
20
+ *
21
+ * - `needs_second_factor`, and `needs_client_trust` (Clerk's check of a device it does not know, verified by the same
22
+ * `signIn.mfa` calls), show the code step for the factors SSSB takes a code for, and the unsupported message when the
23
+ * account offers none of them (a passkey, an emailed link).
24
+ * - `needs_identifier` and `needs_first_factor`: Clerk did not take the password. The generic error.
25
+ * - Any other (`needs_new_password`, `needs_protect_check`, one a later Clerk adds): the unsupported message.
14
26
  *
15
27
  * AUTHORED — CUTOVER (`auth-dev`): never run against a real Clerk instance.
16
- * Lives in packages/kit/src/adapters because it imports the vendor SDK; the SignInScreen renders it as a slot.
28
+ * Lives in packages/kit/src/adapters because it imports the vendor SDK; the SignInScreen renders it as a slot. The
29
+ * password step's copy is the page's `labels`; what comes after it reads the framework's catalog itself (`auth`), so it
30
+ * renders under `NextIntlClientProvider`, as `SignInScreen` does.
17
31
  *
18
32
  * `returnTo` usually comes from the URL, so the form goes there only when `sameOriginPath` accepts it, and to `/`
19
33
  * otherwise: a page that forgot to check it must not turn sign-in into an open redirect (`/\evil.example` and
20
34
  * `/<tab>/evil.example` pass a `startsWith('/')` check and leave the origin).
21
35
  */
22
36
  export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; returnTo: string }) {
23
- const { signIn, fetchStatus } = useSignIn()
37
+ const { signIn } = useSignIn()
38
+ const t = useTranslations('auth')
24
39
  const [formError, setFormError] = useState<string | null>(null)
40
+ // Not the hook's `fetchStatus`, which a code still being sent holds after the person has gone back from the step.
41
+ const [busy, setBusy] = useState(false)
42
+ const [step, setStep] = useState<Step | null>(null)
25
43
  const form = useForm({ initialValues: { email: '', password: '' } })
26
44
 
45
+ // Clerk accepted the step's code, kept for a `finalize` that fails after it: a code is spent once verified, so
46
+ // trying again finalizes the same attempt, while it is still complete, and verifies nothing.
47
+ const [accepted, setAccepted] = useState(false)
48
+
49
+ // Leaving the step puts focus back where the person types next.
50
+ const password = useRef<HTMLInputElement>(null)
51
+ const [leftStep, setLeftStep] = useState(false)
52
+ useEffect(() => {
53
+ if (leftStep) password.current?.focus()
54
+ }, [leftStep])
55
+
56
+ function leaveStep(error: string | null) {
57
+ setLeftStep(step !== null)
58
+ setStep(null)
59
+ setFormError(error)
60
+ }
61
+
62
+ /** Acts on the attempt's status, and answers whether that moved it on from `from`, the step it is on. */
63
+ async function proceed(attempt: SignIn, from: Step | null): Promise<boolean> {
64
+ const { status } = attempt
65
+ switch (status) {
66
+ case 'complete': {
67
+ const { error } = await attempt.finalize()
68
+ if (error) return false
69
+ window.location.assign(sameOriginPath(returnTo) ?? '/')
70
+ return true
71
+ }
72
+ case 'needs_identifier':
73
+ case 'needs_first_factor':
74
+ return false
75
+ case 'needs_second_factor':
76
+ case 'needs_client_trust': {
77
+ if (status === from?.status) return false
78
+ const factors = supportedFactors(attempt)
79
+ if (factors) {
80
+ form.setFieldValue('password', '')
81
+ setAccepted(false)
82
+ setLeftStep(false)
83
+ setStep({ attempt, status, factors })
84
+ } else {
85
+ leaveStep(t('signInUnsupported'))
86
+ }
87
+ return true
88
+ }
89
+ default:
90
+ leaveStep(t('signInUnsupported'))
91
+ return true
92
+ }
93
+ }
94
+
27
95
  const submit = form.onSubmit(async (values) => {
28
96
  setFormError(null)
97
+ setBusy(true)
29
98
  // A Clerk call that throws (the network, not a refused password) is shown as the same generic error, never left
30
99
  // as an unhandled rejection with nothing on screen.
31
100
  try {
32
- const { error } = await signIn.password({ identifier: values.email, password: values.password })
33
- if (error) {
34
- setFormError(labels.genericError)
35
- return
36
- }
37
- if (signIn.status === 'complete') {
38
- const finalized = await signIn.finalize()
39
- if (finalized.error) setFormError(labels.genericError)
40
- else window.location.assign(sameOriginPath(returnTo) ?? '/')
41
- } else if (signIn.status === 'needs_second_factor') {
42
- setFormError(labels.mfaNotImplemented)
43
- } else {
44
- setFormError(labels.genericError)
45
- }
101
+ const taken = await succeeds(signIn, () =>
102
+ signIn.password({ identifier: values.email, password: values.password }),
103
+ )
104
+ if (!taken || !(await proceed(signIn, null))) setFormError(labels.genericError)
46
105
  } catch {
47
106
  setFormError(labels.genericError)
107
+ } finally {
108
+ setBusy(false)
48
109
  }
49
110
  })
50
111
 
112
+ if (step) {
113
+ const { attempt } = step
114
+ return (
115
+ <SecondFactorStep
116
+ key={step.status}
117
+ factors={step.factors}
118
+ newDevice={step.status === 'needs_client_trust'}
119
+ onSend={(kind) =>
120
+ succeeds(attempt, () =>
121
+ kind === 'phone' ? attempt.mfa.sendPhoneCode() : attempt.mfa.sendEmailCode(),
122
+ )
123
+ }
124
+ // A throw (the network) is the step's to show, as a code Clerk refused is.
125
+ onVerify={async (kind, code) => {
126
+ if (!accepted || attempt.status !== 'complete') {
127
+ const { error } = await verifyCode(attempt, kind, code)
128
+ if (error) return false
129
+ setAccepted(true)
130
+ }
131
+ return proceed(attempt, step)
132
+ }}
133
+ onBack={() => {
134
+ leaveStep(null)
135
+ // Clerk's attempt is dropped too (local state only, no request). The next password starts a new one
136
+ // either way, so a reset that fails changes nothing.
137
+ void Promise.resolve()
138
+ .then(() => signIn.reset())
139
+ .catch(() => {})
140
+ }}
141
+ />
142
+ )
143
+ }
144
+
51
145
  return (
52
146
  <form onSubmit={submit}>
53
147
  <Stack>
54
148
  <TextInput label={labels.email} type="email" required {...form.getInputProps('email')} />
55
- <PasswordInput label={labels.password} required {...form.getInputProps('password')} />
56
- <Button type="submit" loading={fetchStatus === 'fetching'}>
149
+ <PasswordInput label={labels.password} required ref={password} {...form.getInputProps('password')} />
150
+ <Button type="submit" loading={busy}>
57
151
  {labels.submit}
58
152
  </Button>
59
153
  {formError ? (
@@ -66,10 +160,99 @@ export function RealSignInForm({ labels, returnTo }: { labels: SignInLabels; ret
66
160
  )
67
161
  }
68
162
 
163
+ /** What the code step answers, and the factors the account offered for it when the step opened. */
164
+ interface Step {
165
+ /**
166
+ * The attempt the password opened, which every call of the step is made on, rather than the hook's current `signIn`,
167
+ * which a client update can replace: another tab's attempt, a code sent before the person went back, or the empty
168
+ * attempt `finalize` can leave when it fails half-way. (A password submitted before clerk-js has loaded is the
169
+ * exception: what the hook answers then is a placeholder that follows its current attempt.)
170
+ */
171
+ attempt: SignIn
172
+ status: 'needs_second_factor' | 'needs_client_trust'
173
+ factors: [SecondFactor, ...SecondFactor[]]
174
+ }
175
+
176
+ /**
177
+ * Whether Clerk took a call. Where clerk-js takes the browser to be offline (its test includes the user agent), it drops a
178
+ * failed request and answers no error, with the attempt as it was: an accepted password, or a code sent, that never
179
+ * left. So a call is taken when it answers no error and anything about the attempt has changed. A password moves its
180
+ * status or, posted to Clerk's collection of attempts, is answered with another id, so no password depends on the
181
+ * verification alone; a sent code moves neither, and there the verification says (clerk-js rebuilds it from every
182
+ * success). Before clerk-js has loaded, every read is a default, so a call made then counts as taken whenever it answers
183
+ * no error (safeinsights/sssb#198).
184
+ */
185
+ async function succeeds(attempt: SignIn, call: () => Promise<{ error: unknown }>): Promise<boolean> {
186
+ const before = fingerprint(attempt)
187
+ const { error } = await call()
188
+ const after = fingerprint(attempt)
189
+ return !error && after.some((value, index) => !Object.is(value, before[index]))
190
+ }
191
+
192
+ /** What a Clerk answer changes about an attempt. */
193
+ function fingerprint(attempt: SignIn): unknown[] {
194
+ const { id, status, secondFactorVerification: verification } = attempt
195
+ return [
196
+ id,
197
+ status,
198
+ verification,
199
+ // Its values too, for one updated in place, read so that nothing a build answers can throw and break the password.
200
+ verification?.status,
201
+ verification?.strategy,
202
+ Number(verification?.expireAt),
203
+ ]
204
+ }
205
+
206
+ /**
207
+ * The account's factors SSSB takes a code for, in Clerk's order with backup codes last, or null when there is none.
208
+ * One per kind, Clerk's first: `signIn.mfa.sendPhoneCode` and `sendEmailCode` take no address, and send to the first
209
+ * number or address the attempt lists, so that is the one to name.
210
+ */
211
+ function supportedFactors(signIn: SignIn): [SecondFactor, ...SecondFactor[]] | null {
212
+ const found = new Map<SecondFactorKind, SecondFactor>()
213
+ for (const offered of signIn.supportedSecondFactors) {
214
+ const factor = toFactor(offered)
215
+ if (factor && !found.has(factor.kind)) found.set(factor.kind, factor)
216
+ }
217
+ const factors = [...found.values()]
218
+ const [first, ...rest] = [
219
+ ...factors.filter(({ kind }) => kind !== 'backup'),
220
+ ...factors.filter(({ kind }) => kind === 'backup'),
221
+ ]
222
+ return first ? [first, ...rest] : null
223
+ }
224
+
225
+ function toFactor(offered: SignIn['supportedSecondFactors'][number]): SecondFactor | null {
226
+ switch (offered.strategy) {
227
+ case 'totp':
228
+ return { kind: 'authenticator' }
229
+ case 'backup_code':
230
+ return { kind: 'backup' }
231
+ case 'phone_code':
232
+ return { kind: 'phone', destination: offered.safeIdentifier }
233
+ case 'email_code':
234
+ return { kind: 'email', destination: offered.safeIdentifier }
235
+ default:
236
+ return null
237
+ }
238
+ }
239
+
240
+ function verifyCode(signIn: SignIn, kind: SecondFactorKind, code: string) {
241
+ switch (kind) {
242
+ case 'authenticator':
243
+ return signIn.mfa.verifyTOTP({ code })
244
+ case 'backup':
245
+ return signIn.mfa.verifyBackupCode({ code })
246
+ case 'phone':
247
+ return signIn.mfa.verifyPhoneCode({ code })
248
+ case 'email':
249
+ return signIn.mfa.verifyEmailCode({ code })
250
+ }
251
+ }
252
+
69
253
  export interface SignInLabels {
70
254
  email: string
71
255
  password: string
72
256
  submit: string
73
257
  genericError: string
74
- mfaNotImplemented: string
75
258
  }
@@ -0,0 +1,254 @@
1
+ 'use client'
2
+
3
+ import { Button, Stack, Text, TextInput, Title } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import { useEffect, useEffectEvent, useId, useRef, useState, type SubmitEvent } from 'react'
6
+
7
+ /** A second factor the step can take a code for, in this app's words, never the identity provider's. */
8
+ export type SecondFactorKind = 'authenticator' | 'phone' | 'email' | 'backup'
9
+
10
+ export type SecondFactor =
11
+ | { kind: 'authenticator' | 'backup' }
12
+ /** `destination` is where the provider sends the code, masked by it (`+1*******99`). */
13
+ | { kind: 'phone' | 'email'; destination: string }
14
+
15
+ /** How long a person waits before a sent code can be sent again. */
16
+ export const RESEND_COOLDOWN_SECONDS = 30
17
+
18
+ /** Milliseconds on a clock that a change of the date or time does not move. */
19
+ const clock = () => performance.now()
20
+
21
+ /** How soon after a choice a click is the second of a double click: choosing a factor moves the buttons. */
22
+ const DOUBLE_CLICK_MS = 500
23
+
24
+ /** A long address, or a longer language, wraps at phone width rather than being cut off. */
25
+ const WRAPS = {
26
+ h: 'auto',
27
+ mih: 36,
28
+ styles: { label: { whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.4 } },
29
+ } as const
30
+
31
+ const COPY = {
32
+ authenticator: { label: 'codeLabelAuthenticator', choice: 'codeChoiceAuthenticator' },
33
+ phone: { label: 'codeLabelPhone', choice: 'codeChoicePhone' },
34
+ email: { label: 'codeLabelEmail', choice: 'codeChoiceEmail' },
35
+ backup: { label: 'codeLabelBackup', choice: 'codeChoiceBackup' },
36
+ } as const
37
+
38
+ /**
39
+ * The second step of sign-in, after the password was accepted: one code from one of the factors the account offers,
40
+ * the first of them chosen, with a button for each of the others. It knows no identity provider: the caller
41
+ * (`adapters/real/sign-in-form.tsx`) says which factors there are and what sending and verifying do.
42
+ *
43
+ * - `onSend` sends a code (`phone`, `email`) and answers whether it went. The step calls it when it opens on such a
44
+ * factor, when the person chooses one, and when they ask for another code, which they can do once
45
+ * `RESEND_COOLDOWN_SECONDS` have passed since the last one that went.
46
+ * - `onVerify` answers whether the caller took it from here: `true` keeps the spinner (the page is navigating, or the
47
+ * caller replaces this step), and `false`, or a rejection, shows the one generic error and leaves the person here
48
+ * with every choice still open. A refused, expired or rate-limited code all read the same.
49
+ * - `onBack` returns to the password, offered whenever no code is being verified or has been taken.
50
+ *
51
+ * Opening the step moves focus to its code field, inside a group named and described by the heading and the lead, so a
52
+ * screen reader hears the step change; a code's sending is told through a status region and an error as an alert.
53
+ */
54
+ export function SecondFactorStep({
55
+ factors,
56
+ newDevice = false,
57
+ onSend,
58
+ onVerify,
59
+ onBack,
60
+ }: {
61
+ factors: readonly [SecondFactor, ...SecondFactor[]]
62
+ /** The provider asks because it does not know the device, not because the account has a second factor. */
63
+ newDevice?: boolean
64
+ onSend: (kind: 'phone' | 'email') => Promise<boolean>
65
+ onVerify: (kind: SecondFactorKind, code: string) => Promise<boolean>
66
+ onBack: () => void
67
+ }) {
68
+ const t = useTranslations('auth')
69
+ const id = useId()
70
+ const [factor, setFactor] = useState<SecondFactor>(factors[0])
71
+ const [code, setCode] = useState('')
72
+ const [busy, setBusy] = useState<'sending' | 'verifying' | null>(null)
73
+ const [error, setError] = useState<'code' | 'send' | null>(null)
74
+ /** Per kind, when another code may be sent. Absent until one has gone. */
75
+ const [resendAt, setResendAt] = useState<Partial<Record<SecondFactorKind, number>>>({})
76
+ const [now, setNow] = useState(0)
77
+ const input = useRef<HTMLInputElement>(null)
78
+
79
+ const { kind } = factor
80
+ const sentUntil = resendAt[kind]
81
+ const wait = sentUntil === undefined ? 0 : Math.max(0, Math.ceil((sentUntil - now) / 1000))
82
+
83
+ // The field is a new element for each kind (its autofill attributes differ), so focus follows it.
84
+ useEffect(() => {
85
+ input.current?.focus()
86
+ }, [kind])
87
+
88
+ // `now` runs until the last cooldown has ended, whichever factor is showing: `choose` reads it too.
89
+ useEffect(() => {
90
+ const last = Math.max(0, ...Object.values(resendAt))
91
+ if (last === 0) return
92
+ const timer = setInterval(() => {
93
+ const at = clock()
94
+ setNow(at)
95
+ if (at >= last) clearInterval(timer)
96
+ }, 1000)
97
+ return () => clearInterval(timer)
98
+ }, [resendAt])
99
+
100
+ async function send(target: 'phone' | 'email') {
101
+ setError(null)
102
+ setBusy('sending')
103
+ let sent = false
104
+ try {
105
+ sent = await onSend(target)
106
+ } catch {
107
+ // Shown below, as a send the provider refused.
108
+ }
109
+ setBusy(null)
110
+ if (sent) {
111
+ const at = clock()
112
+ setNow(at)
113
+ setResendAt((before) => ({ ...before, [target]: at + RESEND_COOLDOWN_SECONDS * 1000 }))
114
+ } else {
115
+ setError('send')
116
+ }
117
+ // Pressing a button that was disabled meanwhile leaves focus nowhere. Anywhere else, it is where the person went.
118
+ if (document.activeElement === document.body) input.current?.focus()
119
+ }
120
+
121
+ // The code for the factor the step opens on. Once: a development double-run of effects must not send two.
122
+ const opened = useRef(false)
123
+ const sendFirst = useEffectEvent(() => {
124
+ if (factor.kind === 'phone' || factor.kind === 'email') void send(factor.kind)
125
+ })
126
+ useEffect(() => {
127
+ if (opened.current) return
128
+ opened.current = true
129
+ sendFirst()
130
+ }, [])
131
+
132
+ const chosenAt = useRef(-Infinity)
133
+ /** Whether a click comes too soon after a choice to be meant for the button now under it. Keeps focus on the field. */
134
+ function isSecondClick(): boolean {
135
+ if (clock() - chosenAt.current >= DOUBLE_CLICK_MS) return false
136
+ input.current?.focus()
137
+ return true
138
+ }
139
+
140
+ function choose(next: SecondFactor) {
141
+ if (isSecondClick()) return
142
+ chosenAt.current = clock()
143
+ setFactor(next)
144
+ setCode('')
145
+ setError(null)
146
+ // One that went a moment ago is still good: going back and forth between factors sends nothing more.
147
+ if ((next.kind === 'phone' || next.kind === 'email') && (resendAt[next.kind] ?? 0) <= now) void send(next.kind)
148
+ }
149
+
150
+ async function verify(event: SubmitEvent<HTMLFormElement>) {
151
+ event.preventDefault()
152
+ // Authenticator apps and text messages print a code in groups; the provider wants its characters alone.
153
+ const typed = kind === 'backup' ? code.trim() : code.replace(/\s/g, '')
154
+ if (busy !== null || typed === '') return
155
+ setError(null)
156
+ setBusy('verifying')
157
+ let taken = false
158
+ try {
159
+ taken = await onVerify(kind, typed)
160
+ } catch {
161
+ // Shown below, as a code the provider refused.
162
+ }
163
+ if (taken) return
164
+ setBusy(null)
165
+ setError('code')
166
+ input.current?.focus()
167
+ input.current?.select()
168
+ }
169
+
170
+ const others = factors.filter((candidate) => candidate.kind !== kind)
171
+ const sends = kind === 'phone' || kind === 'email'
172
+ return (
173
+ <form onSubmit={(event) => void verify(event)} data-testid="second-factor-step">
174
+ <Stack role="group" aria-labelledby={`${id}-title`} aria-describedby={`${id}-lead`}>
175
+ <Title order={2} size="h4" id={`${id}-title`}>
176
+ {t('secondFactorTitle')}
177
+ </Title>
178
+ <Text size="sm" id={`${id}-lead`}>
179
+ {t(newDevice ? 'secondFactorNewDevice' : 'secondFactorLead')}
180
+ </Text>
181
+ <TextInput
182
+ key={kind}
183
+ ref={input}
184
+ label={t(COPY[kind].label)}
185
+ name="code"
186
+ required
187
+ value={code}
188
+ onChange={(event) => setCode(event.currentTarget.value)}
189
+ error={error === 'code'}
190
+ // Mantine's error red is too pale for text; the border, aria-invalid and the alert say it is wrong.
191
+ styles={{ input: { color: 'var(--mantine-color-text)' } }}
192
+ // A backup code is no one-time-code: a password manager would fill the authenticator's instead.
193
+ autoComplete={kind === 'backup' ? 'off' : 'one-time-code'}
194
+ inputMode={kind === 'backup' ? 'text' : 'numeric'}
195
+ autoCapitalize="none"
196
+ spellCheck={false}
197
+ />
198
+ <Text role="status" size="sm" c="gray.7" data-testid="second-factor-status">
199
+ {busy === 'sending'
200
+ ? t('codeSending')
201
+ : sends && sentUntil !== undefined && error !== 'send'
202
+ ? t('codeSent', { destination: factor.destination })
203
+ : null}
204
+ </Text>
205
+ {error ? (
206
+ <Text c="red.8" role="alert">
207
+ {t(error === 'code' ? 'codeError' : 'codeSendError')}
208
+ </Text>
209
+ ) : null}
210
+ <Button type="submit" {...WRAPS} loading={busy === 'verifying'} disabled={busy === 'sending'}>
211
+ {t('codeVerify')}
212
+ </Button>
213
+ {sends ? (
214
+ <Button
215
+ variant="default"
216
+ {...WRAPS}
217
+ disabled={busy !== null || wait > 0}
218
+ onClick={() => {
219
+ // This button is about to be disabled; the code goes in the field.
220
+ input.current?.focus()
221
+ void send(kind)
222
+ }}
223
+ data-testid="second-factor-resend"
224
+ >
225
+ {wait > 0 ? t('codeResendIn', { seconds: wait }) : t('codeResend')}
226
+ </Button>
227
+ ) : null}
228
+ {others.map((other) => (
229
+ <Button
230
+ key={other.kind}
231
+ variant="default"
232
+ {...WRAPS}
233
+ disabled={busy !== null}
234
+ onClick={() => choose(other)}
235
+ data-testid={`second-factor-choose-${other.kind}`}
236
+ >
237
+ {t(COPY[other.kind].choice, 'destination' in other ? { destination: other.destination } : {})}
238
+ </Button>
239
+ ))}
240
+ <Button
241
+ variant="subtle"
242
+ {...WRAPS}
243
+ disabled={busy === 'verifying'}
244
+ onClick={() => {
245
+ if (!isSecondClick()) onBack()
246
+ }}
247
+ data-testid="second-factor-back"
248
+ >
249
+ {t('secondFactorBack')}
250
+ </Button>
251
+ </Stack>
252
+ </form>
253
+ )
254
+ }
@@ -12,7 +12,26 @@
12
12
  "passwordLabel": "Password",
13
13
  "signInButton": "Sign in",
14
14
  "signInError": "Sign-in failed. Check your email and password.",
15
- "mfaNotImplemented": "This account requires MFA, which arrives with a later slice.",
15
+ "signInUnsupported": "This account needs a sign-in step that this page cannot complete. Ask whoever manages your account for help.",
16
+ "secondFactorTitle": "Confirm it is you",
17
+ "secondFactorLead": "Your account asks for a code after your password.",
18
+ "secondFactorNewDevice": "You have not signed in on this device before, so enter a code to confirm it is you.",
19
+ "secondFactorBack": "Back to email and password",
20
+ "codeLabelAuthenticator": "Code from your authenticator app",
21
+ "codeLabelPhone": "Code from the text message",
22
+ "codeLabelEmail": "Code from the email",
23
+ "codeLabelBackup": "Backup code",
24
+ "codeChoiceAuthenticator": "Use your authenticator app",
25
+ "codeChoicePhone": "Get a text message at {destination}",
26
+ "codeChoiceEmail": "Get an email at {destination}",
27
+ "codeChoiceBackup": "Use a backup code",
28
+ "codeSending": "Sending a code…",
29
+ "codeSent": "A code was sent to {destination}.",
30
+ "codeSendError": "The code could not be sent. Try again.",
31
+ "codeResend": "Send a new code",
32
+ "codeResendIn": "Send a new code in {seconds} s",
33
+ "codeVerify": "Verify code",
34
+ "codeError": "That did not work. Check the code and try again, or go back and sign in again.",
16
35
  "userMenuLabel": "{name}, account menu",
17
36
  "profileLink": "Profile",
18
37
  "signOut": "Sign out",
@@ -12,7 +12,26 @@
12
12
  "passwordLabel": "Contraseña",
13
13
  "signInButton": "Iniciar sesión",
14
14
  "signInError": "No se pudo iniciar sesión. Revisa tu correo y contraseña.",
15
- "mfaNotImplemented": "Esta cuenta requiere MFA, que llegará en una fase posterior.",
15
+ "signInUnsupported": "Esta cuenta requiere un paso de inicio de sesión que esta página no puede completar. Pide ayuda a quien administra tu cuenta.",
16
+ "secondFactorTitle": "Confirma que eres tú",
17
+ "secondFactorLead": "Tu cuenta pide un código después de la contraseña.",
18
+ "secondFactorNewDevice": "No has iniciado sesión antes en este dispositivo; introduce un código para confirmar que eres tú.",
19
+ "secondFactorBack": "Volver al correo y la contraseña",
20
+ "codeLabelAuthenticator": "Código de tu aplicación de autenticación",
21
+ "codeLabelPhone": "Código del mensaje de texto",
22
+ "codeLabelEmail": "Código del correo electrónico",
23
+ "codeLabelBackup": "Código de respaldo",
24
+ "codeChoiceAuthenticator": "Usar tu aplicación de autenticación",
25
+ "codeChoicePhone": "Recibir un mensaje de texto en {destination}",
26
+ "codeChoiceEmail": "Recibir un correo en {destination}",
27
+ "codeChoiceBackup": "Usar un código de respaldo",
28
+ "codeSending": "Enviando un código…",
29
+ "codeSent": "Se envió un código a {destination}.",
30
+ "codeSendError": "No se pudo enviar el código. Inténtalo de nuevo.",
31
+ "codeResend": "Enviar un código nuevo",
32
+ "codeResendIn": "Enviar un código nuevo en {seconds} s",
33
+ "codeVerify": "Verificar código",
34
+ "codeError": "Eso no funcionó. Revisa el código e inténtalo de nuevo, o vuelve e inicia sesión otra vez.",
16
35
  "userMenuLabel": "{name}, menú de la cuenta",
17
36
  "profileLink": "Perfil",
18
37
  "signOut": "Cerrar sesión",