@sssb/kit 0.7.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/edge-headers.ts +171 -0
  4. package/src/adapters/fake/simulator-admin.ts +7 -3
  5. package/src/adapters/fake/storage.ts +60 -8
  6. package/src/adapters/origin-form.ts +24 -0
  7. package/src/adapters/real/auth.ts +3 -2
  8. package/src/adapters/real/clerk-authorized-parties.ts +43 -0
  9. package/src/adapters/real/clerk-proxy.ts +9 -1
  10. package/src/adapters/real/index.ts +16 -0
  11. package/src/adapters/real/optional-ports.ts +3 -2
  12. package/src/adapters/real/s3-storage.ts +66 -5
  13. package/src/adapters/real/sign-in-form.tsx +206 -23
  14. package/src/adapters/real/storage-settings.ts +7 -4
  15. package/src/adapters/real/storage.ts +9 -7
  16. package/src/authz/route-policy.ts +7 -4
  17. package/src/components/auth/second-factor-step.tsx +254 -0
  18. package/src/components/simulator/actors-app.tsx +1 -1
  19. package/src/components/simulator/errors-app.tsx +4 -1
  20. package/src/components/simulator/inbound-app.tsx +1 -1
  21. package/src/components/simulator/jobs-app.tsx +3 -3
  22. package/src/components/simulator/mail-app.tsx +1 -1
  23. package/src/components/simulator/mail-link.ts +27 -0
  24. package/src/components/simulator/simulator-host.tsx +556 -82
  25. package/src/components/simulator/simulator-panel.tsx +1 -1
  26. package/src/db/inbound-email.ts +7 -5
  27. package/src/db/migrations/0018_organizations_write.ts +87 -0
  28. package/src/db/migrations/index.ts +2 -0
  29. package/src/db/org-lookup.ts +4 -4
  30. package/src/db/rls-coverage.ts +140 -24
  31. package/src/db/rls-proofs.ts +147 -0
  32. package/src/demo-static/world.ts +2 -2
  33. package/src/guide.md +6 -0
  34. package/src/i18n/messages/en.json +20 -1
  35. package/src/i18n/messages/es.json +20 -1
  36. package/src/ports/storage.ts +50 -9
  37. package/src/server-lib/invite.ts +5 -1
  38. package/src/server-lib/simulator-api.ts +320 -3
  39. package/src/service-auth/secret-env.ts +19 -0
  40. package/src/service-auth/standard-webhooks.ts +358 -0
  41. package/src/service-auth/webhook.ts +39 -12
@@ -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
  }
@@ -5,10 +5,13 @@
5
5
  * secret pasted into the wrong one never reaches a log, never repeats a value that could hold one (the endpoint).
6
6
  */
7
7
 
8
- /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
9
- export function parseUploadTarget(value: string): 'post' | 'none' {
10
- if (value === 'post' || value === 'none') return value
11
- throw new Error(`STORAGE_UPLOAD_TARGET must be post or none (got "${value}")`)
8
+ /**
9
+ * `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `put` if it takes a presigned PUT instead
10
+ * (Cloudflare R2), `none` if the app takes no browser uploads.
11
+ */
12
+ export function parseUploadTarget(value: string): 'post' | 'put' | 'none' {
13
+ if (value === 'post' || value === 'put' || value === 'none') return value
14
+ throw new Error(`STORAGE_UPLOAD_TARGET must be post, put or none (got "${value}")`)
12
15
  }
13
16
 
14
17
  /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (an empty value counts as unset) for the SDK's own addressing. */
@@ -26,7 +26,7 @@ export interface CompatibleStorageSettings {
26
26
  accessKeyId: string
27
27
  /** `STORAGE_SECRET_ACCESS_KEY`. */
28
28
  secretAccessKey: string
29
- /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
29
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `put` if it takes a presigned PUT, `none` for no browser upload. */
30
30
  uploadTarget: string
31
31
  /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (empty counts as unset) for the SDK's own addressing. */
32
32
  forcePathStyle?: string | undefined
@@ -35,8 +35,9 @@ export interface CompatibleStorageSettings {
35
35
  /**
36
36
  * The storage port on an S3-compatible store: the same adapter as `createRealStorage`, pointed at `endpoint` with the
37
37
  * store's own key pair. Everything but the upload target is S3's API, which these stores implement (ADR-0015, section
38
- * 6 lists what R2 does). `createUploadTarget` is an S3 presigned POST, which R2 does not accept, so it follows
39
- * `uploadTarget`: with `none` it fails naming the setting rather than minting a URL the store would refuse.
38
+ * 6 lists what R2 does). `createUploadTarget` follows `uploadTarget`: an S3 presigned POST for `post` (MinIO),
39
+ * a presigned PUT for `put` (R2, which has no POST), and with `none` it fails naming the setting rather than minting a
40
+ * URL the store would refuse.
40
41
  *
41
42
  * AUTHORED — CUTOVER (`storage-compatible-store`, `storage-compatible-credentials`, and the live round trip
42
43
  * `storage-compatible-live`): typechecked and run with the SDK's transport replaced, never against a real store.
@@ -53,6 +54,7 @@ export function createCompatibleStorage(settings: CompatibleStorageSettings): St
53
54
  endpoint,
54
55
  credentials: { accessKeyId, secretAccessKey },
55
56
  forcePathStyle,
57
+ uploadTarget: target === 'put' ? 'put' : 'post',
56
58
  // The SDK's default (since v3.729, `WHEN_SUPPORTED`) puts a CRC32 checksum on every PutObject, which stores
57
59
  // older than that default can reject; Cloudflare tells R2 users to ask for checksums only where an operation
58
60
  // requires one. `WHEN_REQUIRED` does that, and no more: DeleteObjects requires one, so it still carries CRC32
@@ -61,14 +63,14 @@ export function createCompatibleStorage(settings: CompatibleStorageSettings): St
61
63
  requestChecksumCalculation: 'WHEN_REQUIRED',
62
64
  responseChecksumValidation: 'WHEN_REQUIRED',
63
65
  })
64
- if (target === 'post') return s3
66
+ if (target !== 'none') return s3
65
67
  return {
66
68
  ...s3,
67
69
  createUploadTarget: async () => {
68
70
  throw new Error(
69
- 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=none, so this store is declared not to accept a ' +
70
- 'presigned POST (Cloudflare R2 does not). Set STORAGE_UPLOAD_TARGET=post for a store that does, ' +
71
- 'such as MinIO, or upload another way.',
71
+ 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=none, so this deployment takes no browser upload. Set ' +
72
+ 'STORAGE_UPLOAD_TARGET=post for a store that accepts a presigned POST (MinIO) or put for one that ' +
73
+ 'takes a presigned PUT instead (Cloudflare R2), or upload another way.',
72
74
  )
73
75
  },
74
76
  }
@@ -50,9 +50,12 @@ export const EXEMPT_PREFIXES: Readonly<Record<string, Exemption>> = {
50
50
  'webhooks/': {
51
51
  reason:
52
52
  'authenticated by a machine caller, not a user session — a shared webhook secret ' +
53
- '(withWebhookSecret) or the Mailgun inbound signature (withMailgunSignature) — so no ' +
54
- 'per-actor ability applies',
55
- mustMatch: { kind: 'wrapped-by', callees: ['withWebhookSecret', 'withMailgunSignature'] },
53
+ '(withWebhookSecret), the Mailgun inbound signature (withMailgunSignature) or a Standard Webhooks ' +
54
+ 'signature (withStandardWebhookSignature) — so no per-actor ability applies',
55
+ mustMatch: {
56
+ kind: 'wrapped-by',
57
+ callees: ['withWebhookSecret', 'withMailgunSignature', 'withStandardWebhookSignature'],
58
+ },
56
59
  },
57
60
  'simulator/': {
58
61
  reason: 'simulated-world surface, simulated-mode-gated (404 in real) — never a product mutation path',
@@ -96,7 +99,7 @@ export const EXEMPT_FILES: Readonly<Record<string, Exemption>> = {
96
99
  },
97
100
  'storage-upload/route.ts': {
98
101
  reason:
99
- 'simulated-mode-only (404 in real) multipart upload endpoint — the local twin of an S3 presigned POST, ' +
102
+ 'simulated-mode-only (404 in real) upload endpoint — the local twin of an S3 presigned POST (multipart) and of a presigned PUT, ' +
100
103
  'authenticated by the server-signed HMAC upload-target fields (like the webhook secret), NOT a user ' +
101
104
  'session; the upload TARGET was already authorized by the app route that minted it',
102
105
  mustMatch: SIMULATED_404,
@@ -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
+ }
@@ -11,7 +11,7 @@ import { chipStyle } from './people-app'
11
11
  * router- and transport-blind — and catalog-blind: WHICH counterparties exist is app vocabulary, so
12
12
  * their copy belongs in the app's catalog and arrives here as finished strings, exactly like
13
13
  * SimulatorExtraTab.label). The
14
- * real glue hands over a same-origin iframe src pointing at the actor's own page; the static twin
14
+ * app on the server host hands over a same-origin iframe src pointing at the actor's own page; the static twin
15
15
  * hands over an already-mounted ActorShell node running inline. A discriminated union keeps the two
16
16
  * shapes mutually exclusive rather than an always-both-optional prop bag.
17
17
  */
@@ -46,7 +46,10 @@ export function ErrorsApp({ runServerScenario }: { runServerScenario?: () => Pro
46
46
  variant="default"
47
47
  data-testid="throw-server-error"
48
48
  onClick={() => {
49
- runServerScenario().then(setResult)
49
+ // A server that could not answer leaves the last result showing.
50
+ runServerScenario()
51
+ .then(setResult)
52
+ .catch(() => undefined)
50
53
  }}
51
54
  >
52
55
  {t('throwServer')}
@@ -54,7 +54,7 @@ function statusColor(status: string): string {
54
54
 
55
55
  /**
56
56
  * The Mail tab's "compose inbound" affordance + inbound list: the world emails the app. Data
57
- * and callbacks only — the glue (simulator-glue.tsx) owns fetching and the POST, and the static-demo
57
+ * and callbacks only — the host (`./simulator-host`) owns fetching and the POST, and the static-demo
58
58
  * twin drives the same props over its in-memory intake. Native <select>s (not Mantine comboboxes) keep
59
59
  * the compose form trivially Playwright-selectable. The handler is a free-text field so an unknown slug
60
60
  * can be sent on purpose to demonstrate the 'unmatched' path.