@sssb/kit 0.6.1 → 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 +1 -1
- package/package.json +1 -1
- package/src/adapters/real/clerk-authorized-parties.ts +54 -0
- package/src/adapters/real/clerk-proxy.ts +9 -1
- package/src/adapters/real/database-transport.ts +17 -0
- package/src/adapters/real/db-data-api.ts +5 -2
- package/src/adapters/real/index.ts +17 -1
- package/src/adapters/real/migrate-handler.ts +4 -0
- package/src/adapters/real/rds-data-dialect.ts +75 -15
- package/src/adapters/real/rds-data-resume.ts +197 -0
- package/src/adapters/real/sign-in-form.tsx +206 -23
- package/src/components/auth/initials.ts +20 -0
- package/src/components/auth/preview-row.tsx +8 -2
- package/src/components/auth/second-factor-step.tsx +254 -0
- package/src/components/auth/user-menu.tsx +11 -3
- package/src/i18n/messages/en.json +20 -1
- package/src/i18n/messages/es.json +20 -1
- package/src/ports/errors.ts +28 -0
package/dist/release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"commit":"
|
|
1
|
+
{"commit":"80b2e6707b2431643c0b903a30a2d888ee697327"}
|
package/package.json
CHANGED
|
@@ -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
|
|
52
|
+
{ ...(jwtKey && { jwtKey }), ...(authorizedParties && { authorizedParties }) },
|
|
45
53
|
)
|
|
46
54
|
return async (request, event) => {
|
|
47
55
|
const authorization = request.headers.get('authorization')
|
|
@@ -32,3 +32,20 @@ export function databaseTransport(): DatabaseTransport {
|
|
|
32
32
|
}
|
|
33
33
|
return value as DatabaseTransport
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* DATABASE_RESUME_BUDGET_MS, optional and read on `data-api` only: how long a call waits for a paused cluster to
|
|
38
|
+
* resume (docs/runbooks/data-api.md, step 6). Undefined when unset or empty, so that the dialect's default holds. At
|
|
39
|
+
* most 15 minutes, far past any server's timeout, so that a wrong unit fails at boot.
|
|
40
|
+
*/
|
|
41
|
+
export function databaseResumeBudgetMs(): number | undefined {
|
|
42
|
+
const value = process.env['DATABASE_RESUME_BUDGET_MS']
|
|
43
|
+
if (!value) return undefined
|
|
44
|
+
const ms = /^\d+$/.test(value) ? Number(value) : NaN
|
|
45
|
+
if (!(ms <= 900_000)) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`DATABASE_RESUME_BUDGET_MS must be a whole number of milliseconds from 0 to 900000 (got "${value}")`,
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
return ms
|
|
51
|
+
}
|
|
@@ -18,6 +18,8 @@ export interface DataApiDbConfig {
|
|
|
18
18
|
client?: RdsDataClientLike
|
|
19
19
|
/** How long inferred parameter types are trusted; the dialect's `TYPE_CACHE_TTL_MS` when omitted. */
|
|
20
20
|
typeCacheTtlMs?: number
|
|
21
|
+
/** How long a call waits for a paused cluster to resume; the dialect's `RESUME_BUDGET_MS` when omitted. */
|
|
22
|
+
resumeBudgetMs?: number | undefined
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
/**
|
|
@@ -29,8 +31,8 @@ export interface DataApiDbConfig {
|
|
|
29
31
|
* deployment never loads the RDS Data SDK; ./index.test.ts proves it.
|
|
30
32
|
*
|
|
31
33
|
* `maxAttempts: 1` turns the SDK's automatic retries off, on AWS's own advice: a statement whose call
|
|
32
|
-
* timed out may still have finished, and retrying it can write twice.
|
|
33
|
-
*
|
|
34
|
+
* timed out may still have finished, and retrying it can write twice. What is safe to
|
|
35
|
+
* send again while a paused Serverless v2 resumes, the dialect sends again itself.
|
|
34
36
|
*/
|
|
35
37
|
export function createRealDataApiDb(config: DataApiDbConfig): DbPort {
|
|
36
38
|
const client =
|
|
@@ -42,6 +44,7 @@ export function createRealDataApiDb(config: DataApiDbConfig): DbPort {
|
|
|
42
44
|
secretArn: config.secretArn,
|
|
43
45
|
database: config.database,
|
|
44
46
|
typeCacheTtlMs: config.typeCacheTtlMs,
|
|
47
|
+
resumeBudgetMs: config.resumeBudgetMs,
|
|
45
48
|
})
|
|
46
49
|
const db = new Kysely<DB>({ dialect })
|
|
47
50
|
return {
|
|
@@ -12,7 +12,8 @@ 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 {
|
|
15
|
+
import { clerkAuthorizedParties } from './clerk-authorized-parties'
|
|
16
|
+
import { DATABASE_ENV, databaseResumeBudgetMs, databaseTransport } from './database-transport'
|
|
16
17
|
import { noAnalytics } from './no-analytics'
|
|
17
18
|
import { optionalPortsEnv, portChoice } from './optional-ports'
|
|
18
19
|
import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
|
|
@@ -74,6 +75,13 @@ export function assertRealEnv(): void {
|
|
|
74
75
|
throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
|
|
75
76
|
}
|
|
76
77
|
}
|
|
78
|
+
if (transport === 'data-api') {
|
|
79
|
+
try {
|
|
80
|
+
databaseResumeBudgetMs()
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw new CutoverPendingError(['data-api'], (error as Error).message)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
77
85
|
// The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
|
|
78
86
|
// org source that would hand everyone the staff org's manage-all.
|
|
79
87
|
let problem: string | null
|
|
@@ -83,6 +91,13 @@ export function assertRealEnv(): void {
|
|
|
83
91
|
problem = (error as Error).message
|
|
84
92
|
}
|
|
85
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
|
+
}
|
|
86
101
|
}
|
|
87
102
|
|
|
88
103
|
/**
|
|
@@ -126,6 +141,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
126
141
|
secretArn: need('DATABASE_SECRET_ARN'),
|
|
127
142
|
database: need('DATABASE_NAME'),
|
|
128
143
|
region: need('AWS_REGION'),
|
|
144
|
+
resumeBudgetMs: databaseResumeBudgetMs(),
|
|
129
145
|
})
|
|
130
146
|
: (await import('./db')).createRealDb(need('DATABASE_URL'))
|
|
131
147
|
// Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
|
|
@@ -2,6 +2,9 @@ import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-sec
|
|
|
2
2
|
import { databaseTransport } from './database-transport'
|
|
3
3
|
import { createRealDb } from './db'
|
|
4
4
|
|
|
5
|
+
/** How long the migrator waits for a paused cluster: no user is waiting, and its Lambda has five minutes (SssbApp). */
|
|
6
|
+
const MIGRATOR_RESUME_BUDGET_MS = 120_000
|
|
7
|
+
|
|
5
8
|
/**
|
|
6
9
|
* Migrator Lambda handler (ADR-0001): runs the same migration registry the app, unit tests, and
|
|
7
10
|
* contract tests use. Invoked by the CD pipeline before each release shifts traffic.
|
|
@@ -36,6 +39,7 @@ export async function handler(): Promise<{ ok: true }> {
|
|
|
36
39
|
resourceArn: DATABASE_CLUSTER_ARN,
|
|
37
40
|
secretArn: DATABASE_SECRET_ARN,
|
|
38
41
|
database: DATABASE_NAME,
|
|
42
|
+
resumeBudgetMs: MIGRATOR_RESUME_BUDGET_MS,
|
|
39
43
|
})
|
|
40
44
|
await db.migrateToLatest()
|
|
41
45
|
return { ok: true }
|
|
@@ -40,6 +40,8 @@ import {
|
|
|
40
40
|
toSqlParameter,
|
|
41
41
|
unsupportedStatement,
|
|
42
42
|
} from './rds-data-codec'
|
|
43
|
+
import { DatabaseUnavailableError } from '../../ports/errors'
|
|
44
|
+
import { RESUME_BUDGET_MS, ResumeWait, unavailable, unavailableReason, wasCancelledUnrun } from './rds-data-resume'
|
|
43
45
|
|
|
44
46
|
/** The four calls this dialect makes. `RDSDataClient` satisfies it, and so does the test emulator. */
|
|
45
47
|
export type RdsDataCommand =
|
|
@@ -59,6 +61,11 @@ export interface RdsDataDialectConfig {
|
|
|
59
61
|
database: string
|
|
60
62
|
/** How long a SQL shape's inferred parameter types are trusted; `TYPE_CACHE_TTL_MS` when omitted. */
|
|
61
63
|
typeCacheTtlMs?: number | undefined
|
|
64
|
+
/**
|
|
65
|
+
* How long one call waits for a paused cluster to resume, in milliseconds, counted from its first refusal or its
|
|
66
|
+
* first wait; `RESUME_BUDGET_MS` when omitted, and 0 to fail at once. It bounds the wait, not the calls themselves.
|
|
67
|
+
*/
|
|
68
|
+
resumeBudgetMs?: number | undefined
|
|
62
69
|
}
|
|
63
70
|
|
|
64
71
|
/**
|
|
@@ -266,21 +273,21 @@ const TYPE_CACHE_LIMIT = 2000
|
|
|
266
273
|
*/
|
|
267
274
|
const TYPE_CACHE_TTL_MS = 5 * 60 * 1000
|
|
268
275
|
|
|
269
|
-
/**
|
|
270
|
-
* A paused Aurora Serverless v2 (min capacity 0, as SSSB's non-production stack runs) answers the first
|
|
271
|
-
* call with DatabaseResumingException: the request was cancelled, not run, so retrying it is safe. Every
|
|
272
|
-
* other failure is NOT retried — the SDK's own retries are off (`maxAttempts: 1` in ./db-data-api.ts) because AWS
|
|
273
|
-
* warns that a retried statement whose first attempt actually finished can write twice.
|
|
274
|
-
*/
|
|
275
|
-
const RESUME_DELAYS_MS = [1000, 2000, 4000, 8000]
|
|
276
|
-
|
|
277
276
|
class RdsDataDriver implements Driver {
|
|
278
277
|
readonly #types = new Map<string, { readonly types: readonly string[]; readonly at: number }>()
|
|
279
278
|
|
|
279
|
+
/** Transactions in which a statement has run, so their sessions have existed. */
|
|
280
|
+
readonly #usedTransactions = new Set<string>()
|
|
281
|
+
readonly #resume: ResumeWait
|
|
282
|
+
|
|
280
283
|
private readonly config: RdsDataDialectConfig
|
|
281
284
|
|
|
282
285
|
constructor(config: RdsDataDialectConfig) {
|
|
283
286
|
this.config = config
|
|
287
|
+
const { client, resourceArn, secretArn, database } = config
|
|
288
|
+
this.#resume = new ResumeWait(() =>
|
|
289
|
+
client.send(new ExecuteStatementCommand({ resourceArn, secretArn, database, sql: 'SELECT 1' })),
|
|
290
|
+
)
|
|
284
291
|
}
|
|
285
292
|
|
|
286
293
|
async init(): Promise<void> {}
|
|
@@ -367,8 +374,10 @@ class RdsDataDriver implements Driver {
|
|
|
367
374
|
} catch (error) {
|
|
368
375
|
// Already gone means already rolled back: the Data API rolls a transaction back itself when it
|
|
369
376
|
// idles for three minutes or reaches an hour, and a failed commit ends it too. Rethrowing would
|
|
370
|
-
// only replace the error that made Kysely roll back with one that says nothing about it.
|
|
377
|
+
// only replace the error that made Kysely roll back with one that says nothing about it. A cluster that
|
|
378
|
+
// answers that it is resuming was paused, and a paused one has no open transaction.
|
|
371
379
|
if (isTransactionGone(error)) return
|
|
380
|
+
if (error instanceof DatabaseUnavailableError && error.reason === 'resuming') return
|
|
372
381
|
throw error
|
|
373
382
|
}
|
|
374
383
|
}
|
|
@@ -514,20 +523,67 @@ class RdsDataDriver implements Driver {
|
|
|
514
523
|
)) as ExecuteStatementCommandOutput
|
|
515
524
|
}
|
|
516
525
|
|
|
526
|
+
/**
|
|
527
|
+
* Sends a command, waiting out a cluster that is resuming (SSSB's non-production stack pauses: min capacity 0). A
|
|
528
|
+
* call outside a transaction that has not been sent yet waits first if a resume is known to be under way. What may
|
|
529
|
+
* be sent again is `mayResend`'s to say; nothing else is, here or in the SDK (`maxAttempts: 1` in ./db-data-api.ts): AWS
|
|
530
|
+
* warns that a retried statement whose first attempt actually finished can write twice.
|
|
531
|
+
*/
|
|
517
532
|
private async call(command: RdsDataCommand): Promise<unknown> {
|
|
518
|
-
|
|
533
|
+
let deadline: number | undefined
|
|
534
|
+
const wait = (error?: unknown): Promise<void> => {
|
|
535
|
+
deadline ??= Date.now() + (this.config.resumeBudgetMs ?? RESUME_BUDGET_MS)
|
|
536
|
+
return this.#resume.join(deadline, error)
|
|
537
|
+
}
|
|
538
|
+
const opensWork = transactionIdOf(command) === undefined
|
|
539
|
+
for (;;) {
|
|
540
|
+
while (opensWork && this.#resume.resuming) await wait()
|
|
519
541
|
try {
|
|
520
|
-
return await this.
|
|
542
|
+
return await this.send(command)
|
|
521
543
|
} catch (error) {
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
await new Promise((resolve) => setTimeout(resolve, RESUME_DELAYS_MS[attempt]))
|
|
544
|
+
if (this.mayResend(command, error)) {
|
|
545
|
+
await wait(error)
|
|
525
546
|
continue
|
|
526
547
|
}
|
|
527
|
-
|
|
548
|
+
const reason = unavailableReason(error)
|
|
549
|
+
throw reason ? unavailable(reason, error) : normalizeDatabaseError(error)
|
|
528
550
|
}
|
|
529
551
|
}
|
|
530
552
|
}
|
|
553
|
+
|
|
554
|
+
private async send(command: RdsDataCommand): Promise<unknown> {
|
|
555
|
+
const transactionId = transactionIdOf(command)
|
|
556
|
+
const runsStatement = command instanceof ExecuteStatementCommand
|
|
557
|
+
try {
|
|
558
|
+
const answer = await this.config.client.send(command)
|
|
559
|
+
if (transactionId && runsStatement) this.#usedTransactions.add(transactionId)
|
|
560
|
+
return answer
|
|
561
|
+
} finally {
|
|
562
|
+
if (transactionId && !runsStatement) this.#usedTransactions.delete(transactionId)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Whether sending `command` again can't repeat anything.
|
|
568
|
+
*
|
|
569
|
+
* - A BeginTransaction runs no statement: at worst the failed attempt left an empty transaction, which the Data API
|
|
570
|
+
* rolls back after three idle minutes. So it is sent again after any answer that the database is resuming, and
|
|
571
|
+
* after a throttle, which an adopter's log shows while a cluster resumes (docs/decision-log.md, 2026-11-24).
|
|
572
|
+
* - A statement only after `DatabaseResumingException` itself, which AWS documents as cancelled. AWS's Data API
|
|
573
|
+
* pages do not say that a throttled statement did not run, so a throttled one is not sent again.
|
|
574
|
+
* - In a transaction, only until a statement has succeeded in it. After that the session existed, and a pause has
|
|
575
|
+
* ended it and the work in it: there is no transaction left to go on with.
|
|
576
|
+
* - A commit or a rollback, never.
|
|
577
|
+
*/
|
|
578
|
+
private mayResend(command: RdsDataCommand, error: unknown): boolean {
|
|
579
|
+
if (command instanceof BeginTransactionCommand) {
|
|
580
|
+
const reason = unavailableReason(error)
|
|
581
|
+
return reason === 'resuming' || reason === 'throttled'
|
|
582
|
+
}
|
|
583
|
+
if (!(command instanceof ExecuteStatementCommand) || !wasCancelledUnrun(error)) return false
|
|
584
|
+
const { transactionId } = command.input
|
|
585
|
+
return transactionId === undefined || !this.#usedTransactions.has(transactionId)
|
|
586
|
+
}
|
|
531
587
|
}
|
|
532
588
|
|
|
533
589
|
class RdsDataConnection implements DatabaseConnection {
|
|
@@ -582,6 +638,10 @@ function isTransactionGone(error: unknown): boolean {
|
|
|
582
638
|
return error.name === 'TransactionNotFoundException' || /transaction\b.*\bnot found/i.test(error.message)
|
|
583
639
|
}
|
|
584
640
|
|
|
641
|
+
function transactionIdOf(command: RdsDataCommand): string | undefined {
|
|
642
|
+
return 'transactionId' in command.input ? command.input.transactionId : undefined
|
|
643
|
+
}
|
|
644
|
+
|
|
585
645
|
function quoteIdent(name: string): string {
|
|
586
646
|
return `"${name.replace(/"/g, '""')}"`
|
|
587
647
|
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { DatabaseUnavailableError, type DatabaseUnavailableReason } from '../../ports/errors'
|
|
2
|
+
import { normalizeDatabaseError, RdsDataDatabaseError } from './rds-data-codec'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What the Data API's "the database can't serve this now" errors are, and the one wait a process makes while a paused
|
|
6
|
+
* cluster resumes. No AWS SDK at run time: errors are read by name. Which command may be sent again is
|
|
7
|
+
* ./rds-data-dialect.ts's to say (`mayResend`).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How long one call waits for a resuming cluster before it fails: 18 seconds, inside SssbApp's 30 s server timeout.
|
|
12
|
+
* AWS puts a typical resume at about 15 s, and measured ones took 12 to 14 s. The measured cold request took 26 s; a
|
|
13
|
+
* 12 to 14 s resume was then seen at 15, so about 11 s went elsewhere (the failed calls themselves, a fresh database's
|
|
14
|
+
* first queries): 18 leaves 12. A resume after more than 24 hours paused can take 30 s or longer (AWS's auto-pause
|
|
15
|
+
* page), which no budget inside 30 s covers. docs/runbooks/data-api.md says how to change it.
|
|
16
|
+
*/
|
|
17
|
+
export const RESUME_BUDGET_MS = 18_000
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The waits between probes, the last one repeating. One second from the seventh second on: no measured resume was
|
|
21
|
+
* shorter, and a longer step there is what made a resume at 12 s unseen until 15.
|
|
22
|
+
*/
|
|
23
|
+
const PROBE_DELAYS_MS = [1000, 2000, 4000, 1000] as const
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* How long one probe holds up the next. The SDK's client has no request timeout, so without this a probe on a dead
|
|
27
|
+
* connection (a Lambda frozen with one in flight) would hold every call that joined, with the database up.
|
|
28
|
+
*/
|
|
29
|
+
const PROBE_TIMEOUT_MS = 2000
|
|
30
|
+
|
|
31
|
+
/** The Data API's exceptions that mean the database can't serve the call now, by name. */
|
|
32
|
+
const REASONS: Readonly<Record<string, DatabaseUnavailableReason>> = {
|
|
33
|
+
DatabaseResumingException: 'resuming',
|
|
34
|
+
ThrottlingException: 'throttled',
|
|
35
|
+
StatementTimeoutException: 'timed-out',
|
|
36
|
+
DatabaseUnavailableException: 'unavailable',
|
|
37
|
+
ServiceUnavailableError: 'unavailable',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Why the database can't serve a call, read from the error or the first error in its cause chain that says; undefined
|
|
42
|
+
* when the failure is something else. An error recognised as being about the SQL ends the search, so
|
|
43
|
+
* that neither its text, which can quote a row, nor anything under it makes it look like a paused database.
|
|
44
|
+
*/
|
|
45
|
+
export function unavailableReason(error: unknown): DatabaseUnavailableReason | undefined {
|
|
46
|
+
const seen = new Set<unknown>()
|
|
47
|
+
for (let link = error; link instanceof Error && !seen.has(link); link = link.cause) {
|
|
48
|
+
seen.add(link)
|
|
49
|
+
const reason = Object.hasOwn(REASONS, link.name) ? REASONS[link.name] : undefined
|
|
50
|
+
if (reason) return reason
|
|
51
|
+
// "This exception is deprecated" (the API reference); taken as a resume when it says "is resuming",
|
|
52
|
+
// which no AWS page confirms or denies. One recognised as a SQL error is not read: its text can quote a row.
|
|
53
|
+
if (link.name === 'BadRequestException') {
|
|
54
|
+
const aboutSql = /\bERROR:/.test(link.message) || isSqlError(link)
|
|
55
|
+
return !aboutSql && /\bis resuming\b/i.test(link.message) ? 'resuming' : undefined
|
|
56
|
+
}
|
|
57
|
+
if (link.name === 'DatabaseErrorException') return undefined
|
|
58
|
+
}
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isSqlError(error: Error): boolean {
|
|
63
|
+
const normalized = normalizeDatabaseError(error)
|
|
64
|
+
return normalized instanceof RdsDataDatabaseError && normalized.code !== undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The one failure AWS documents as cancelled. The error itself, never a cause: a wrapper may be a later failure. */
|
|
68
|
+
export function wasCancelledUnrun(error: unknown): boolean {
|
|
69
|
+
return error instanceof Error && error.name === 'DatabaseResumingException'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The error an app sees. `cause` is AWS's own error. */
|
|
73
|
+
export function unavailable(reason: DatabaseUnavailableReason, error: unknown): DatabaseUnavailableError {
|
|
74
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
75
|
+
return new DatabaseUnavailableError(reason, `RDS Data API: the database is not available (${reason}): ${detail}`, {
|
|
76
|
+
cause: error,
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface Wake {
|
|
81
|
+
readonly ended: Promise<void>
|
|
82
|
+
readonly end: () => void
|
|
83
|
+
waiters: number
|
|
84
|
+
lastError: unknown
|
|
85
|
+
/** The database has said it is resuming, where a wait may also have been started by a throttle. */
|
|
86
|
+
resuming: boolean
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* One wait for a resuming cluster, for the driver that makes it (the db port builds one per process). The first call
|
|
91
|
+
* that finds it resuming starts a poll of `probe`; every call that joins before the poll ends waits on the same one, each
|
|
92
|
+
* for no longer than its own deadline. The poll ends when the probe answers or fails for another reason (the joined
|
|
93
|
+
* calls then go and get their own answers), or when nobody waits for it any more. A probe that does not answer holds up
|
|
94
|
+
* the next for `PROBE_TIMEOUT_MS`. A poll that has ended, and one nobody waits on, is never joined.
|
|
95
|
+
*/
|
|
96
|
+
export class ResumeWait {
|
|
97
|
+
#current: Wake | undefined
|
|
98
|
+
|
|
99
|
+
/** Must be safe to run any number of times: it is repeated after failures of every kind. */
|
|
100
|
+
private readonly probe: () => Promise<unknown>
|
|
101
|
+
|
|
102
|
+
constructor(probe: () => Promise<unknown>) {
|
|
103
|
+
this.probe = probe
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A wait is under way for a database that said it is resuming: a call not sent yet would only be refused. */
|
|
107
|
+
get resuming(): boolean {
|
|
108
|
+
return this.#current?.resuming === true
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Waits until the database answers; throws DatabaseUnavailableError at `deadline` (a `Date.now()` time). */
|
|
112
|
+
async join(deadline: number, error?: unknown): Promise<void> {
|
|
113
|
+
const remaining = deadline - Date.now()
|
|
114
|
+
if (remaining <= 0) throw this.#expired(error ?? this.#current?.lastError)
|
|
115
|
+
const wake = this.#current ?? this.#start()
|
|
116
|
+
if (error !== undefined) this.#saw(wake, error)
|
|
117
|
+
wake.waiters += 1
|
|
118
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
119
|
+
try {
|
|
120
|
+
const expired = await Promise.race([
|
|
121
|
+
wake.ended.then(() => false),
|
|
122
|
+
new Promise<boolean>((resolve) => {
|
|
123
|
+
timer = setTimeout(() => resolve(true), remaining)
|
|
124
|
+
}),
|
|
125
|
+
])
|
|
126
|
+
if (expired) throw this.#expired(wake.lastError)
|
|
127
|
+
} finally {
|
|
128
|
+
clearTimeout(timer)
|
|
129
|
+
wake.waiters -= 1
|
|
130
|
+
if (wake.waiters === 0) this.#forget(wake)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#expired(error: unknown): DatabaseUnavailableError {
|
|
135
|
+
return unavailable(unavailableReason(error) ?? 'resuming', error)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#saw(wake: Wake, error: unknown): void {
|
|
139
|
+
wake.lastError = error
|
|
140
|
+
if (unavailableReason(error) === 'resuming') wake.resuming = true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#forget(wake: Wake): void {
|
|
144
|
+
if (this.#current === wake) this.#current = undefined
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
#finish(wake: Wake): void {
|
|
148
|
+
this.#forget(wake)
|
|
149
|
+
wake.end()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
#start(): Wake {
|
|
153
|
+
let end: () => void = () => {}
|
|
154
|
+
const ended = new Promise<void>((resolve) => {
|
|
155
|
+
end = resolve
|
|
156
|
+
})
|
|
157
|
+
const wake: Wake = { ended, end, waiters: 0, lastError: undefined, resuming: false }
|
|
158
|
+
this.#current = wake
|
|
159
|
+
void this.#poll(wake).finally(() => this.#finish(wake))
|
|
160
|
+
return wake
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Ends when the database answers, or fails a probe for another reason, or nobody waits any more. */
|
|
164
|
+
async #poll(wake: Wake): Promise<void> {
|
|
165
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
166
|
+
await sleep(PROBE_DELAYS_MS[Math.min(attempt, PROBE_DELAYS_MS.length - 1)])
|
|
167
|
+
if (wake.waiters === 0) return
|
|
168
|
+
let over = false
|
|
169
|
+
let inTurn = true
|
|
170
|
+
// Ends the wait also when this probe outlasted its turn and a later one is in flight.
|
|
171
|
+
const finish = (): void => {
|
|
172
|
+
over = true
|
|
173
|
+
this.#finish(wake)
|
|
174
|
+
}
|
|
175
|
+
const probed = Promise.resolve()
|
|
176
|
+
.then(() => this.probe())
|
|
177
|
+
.then(finish, (error: unknown) => {
|
|
178
|
+
if (!unavailableReason(error)) finish()
|
|
179
|
+
else if (inTurn) this.#saw(wake, error)
|
|
180
|
+
})
|
|
181
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
182
|
+
await Promise.race([
|
|
183
|
+
probed,
|
|
184
|
+
new Promise((resolve) => {
|
|
185
|
+
timer = setTimeout(resolve, PROBE_TIMEOUT_MS)
|
|
186
|
+
}),
|
|
187
|
+
])
|
|
188
|
+
clearTimeout(timer)
|
|
189
|
+
inTurn = false
|
|
190
|
+
if (over) return
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function sleep(ms: number | undefined): Promise<void> {
|
|
196
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
197
|
+
}
|
|
@@ -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 {
|
|
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
|
-
*
|
|
13
|
-
*
|
|
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
|
|
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
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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={
|
|
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,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The letters an avatar shows for a person (or an org): the first letters of the first and last words
|
|
3
|
+
* of `name` that start with a letter (Unicode `\p{L}`), uppercased. One such word gives one letter.
|
|
4
|
+
* Punctuation or digits that open a word never count, so `Ana (Bea) Cruz` is `AC`, not `A(`, which
|
|
5
|
+
* is what Mantine's own `name` prop would show.
|
|
6
|
+
*
|
|
7
|
+
* With no such word the first letter (or digit) of `fallback`, the email where a caller has one, is
|
|
8
|
+
* used; with neither, the result is empty and the `Avatar` draws its placeholder icon.
|
|
9
|
+
*/
|
|
10
|
+
export function avatarInitials(name: string, fallback = ''): string {
|
|
11
|
+
const letterWords = name.split(/\s+/).filter((word) => /^\p{L}/u.test(word))
|
|
12
|
+
if (letterWords.length > 0) {
|
|
13
|
+
const first = letterWords[0]!
|
|
14
|
+
const last = letterWords[letterWords.length - 1]!
|
|
15
|
+
// `Array.from` takes a code point, so a letter outside the BMP is not split in half.
|
|
16
|
+
return (Array.from(first)[0]! + (letterWords.length > 1 ? Array.from(last)[0]! : '')).toUpperCase()
|
|
17
|
+
}
|
|
18
|
+
const lead = fallback.match(/[\p{L}\p{N}]/u)?.[0]
|
|
19
|
+
return lead ? lead.toUpperCase() : ''
|
|
20
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { Avatar, Group, Stack, Text } from '@mantine/core'
|
|
4
4
|
import type { ReactNode } from 'react'
|
|
5
|
+
import { avatarInitials } from './initials'
|
|
5
6
|
|
|
6
7
|
// Avatars are a dark filled neutral (white initials on near-black): the hash-colored
|
|
7
8
|
// `color="initials"` variants — and even Mantine's default gray placeholder — land at ~3.7–4.4:1 for
|
|
@@ -15,6 +16,7 @@ import type { ReactNode } from 'react'
|
|
|
15
16
|
*/
|
|
16
17
|
export function PreviewRow({
|
|
17
18
|
name,
|
|
19
|
+
fallback,
|
|
18
20
|
title,
|
|
19
21
|
subtitle,
|
|
20
22
|
badge,
|
|
@@ -23,6 +25,9 @@ export function PreviewRow({
|
|
|
23
25
|
}: {
|
|
24
26
|
/** Seeds the initials avatar (org name or person name). */
|
|
25
27
|
name: string
|
|
28
|
+
/** Where the initials come from when `name` has no word that starts with a letter (a person's email).
|
|
29
|
+
* The title when omitted. */
|
|
30
|
+
fallback?: string
|
|
26
31
|
title: string
|
|
27
32
|
subtitle?: ReactNode
|
|
28
33
|
badge?: ReactNode
|
|
@@ -34,7 +39,6 @@ export function PreviewRow({
|
|
|
34
39
|
return (
|
|
35
40
|
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
|
36
41
|
<Avatar
|
|
37
|
-
name={name}
|
|
38
42
|
radius={rounded ? 'xl' : 'sm'}
|
|
39
43
|
size={dim}
|
|
40
44
|
// Decorative: the title beside it already says the name, so assistive tech skips the
|
|
@@ -43,7 +47,9 @@ export function PreviewRow({
|
|
|
43
47
|
styles={{
|
|
44
48
|
placeholder: { color: '#fff', background: 'var(--mantine-color-dark-6)' },
|
|
45
49
|
}}
|
|
46
|
-
|
|
50
|
+
>
|
|
51
|
+
{avatarInitials(name, fallback ?? title)}
|
|
52
|
+
</Avatar>
|
|
47
53
|
<Stack gap={2} style={{ minWidth: 0 }}>
|
|
48
54
|
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
|
49
55
|
{/* Explicit dark color: inside Mantine's Menu.Label (user menu header) an
|
|
@@ -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
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { Avatar, Menu, UnstyledButton, VisuallyHidden } from '@mantine/core'
|
|
4
4
|
import { useTranslations } from 'next-intl'
|
|
5
5
|
import { SignOutIcon, UserIcon } from './auth-icons'
|
|
6
|
+
import { avatarInitials } from './initials'
|
|
6
7
|
import { PreviewRow } from './preview-row'
|
|
7
8
|
|
|
8
9
|
export interface MenuUser {
|
|
@@ -38,16 +39,23 @@ export function UserMenu({
|
|
|
38
39
|
<UnstyledButton data-testid="user-menu">
|
|
39
40
|
<VisuallyHidden>{t('userMenuLabel', { name: user.name.trim() || user.email })}</VisuallyHidden>
|
|
40
41
|
<Avatar
|
|
41
|
-
name={user.name}
|
|
42
42
|
aria-hidden
|
|
43
43
|
radius="xl"
|
|
44
44
|
styles={{ placeholder: { color: '#fff', background: 'var(--mantine-color-dark-6)' } }}
|
|
45
|
-
|
|
45
|
+
>
|
|
46
|
+
{avatarInitials(user.name, user.email)}
|
|
47
|
+
</Avatar>
|
|
46
48
|
</UnstyledButton>
|
|
47
49
|
</Menu.Target>
|
|
48
50
|
<Menu.Dropdown>
|
|
49
51
|
<Menu.Label>
|
|
50
|
-
<PreviewRow
|
|
52
|
+
<PreviewRow
|
|
53
|
+
name={user.name}
|
|
54
|
+
fallback={user.email}
|
|
55
|
+
title={user.name}
|
|
56
|
+
subtitle={user.email}
|
|
57
|
+
rounded
|
|
58
|
+
/>
|
|
51
59
|
</Menu.Label>
|
|
52
60
|
<Menu.Divider />
|
|
53
61
|
{onProfile ? (
|
|
@@ -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
|
-
"
|
|
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
|
-
"
|
|
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",
|
package/src/ports/errors.ts
CHANGED
|
@@ -34,6 +34,34 @@ export class PreconditionFailedError extends Error {
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Why the database can't serve a call now. `resuming`: a paused cluster is starting. `throttled`: it refused the call
|
|
39
|
+
* for load, as it may while a cluster resumes. `timed-out`: a statement ran past the transport's limit. `unavailable`:
|
|
40
|
+
* the writer or the database service is not available.
|
|
41
|
+
*/
|
|
42
|
+
export type DatabaseUnavailableReason = 'resuming' | 'throttled' | 'timed-out' | 'unavailable'
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Thrown when the database can't serve a call now and may soon: a paused cluster that outlasted the transport's wait,
|
|
46
|
+
* a throttled or timed-out call, a writer or a database service that is not available. On the RDS Data API a few
|
|
47
|
+
* answers that the database is resuming throw it at once, as `resuming`, without a wait: to a commit, whose outcome is
|
|
48
|
+
* then unknown, so never assume that it failed; to a statement after another has succeeded in its transaction; and to
|
|
49
|
+
* a statement as a `BadRequestException`. Route glue answers a 503 with `Retry-After: retryAfterSeconds`. It does not
|
|
50
|
+
* say the work did not happen: treat a throttled or timed-out statement or commit as if it may have run. So a caller
|
|
51
|
+
* repeats a read by itself, and a write only when a person, or an idempotent request, asks for it again. `cause` is
|
|
52
|
+
* the vendor's error. Raised by the RDS Data API transport; `pg` has no equivalent today.
|
|
53
|
+
*/
|
|
54
|
+
export class DatabaseUnavailableError extends Error {
|
|
55
|
+
readonly reason: DatabaseUnavailableReason
|
|
56
|
+
readonly retryAfterSeconds = 5
|
|
57
|
+
|
|
58
|
+
constructor(reason: DatabaseUnavailableReason, message = 'database unavailable', options?: { cause?: unknown }) {
|
|
59
|
+
super(message, options)
|
|
60
|
+
this.name = 'DatabaseUnavailableError'
|
|
61
|
+
this.reason = reason
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
37
65
|
/** Thrown by real adapters when their cutover items are unfilled (fail-fast for dev:real). */
|
|
38
66
|
export class CutoverPendingError extends Error {
|
|
39
67
|
readonly cutoverItems: string[]
|