Files
KomediruzeckiandGitHub 76e1efded8 feat(auth): a password account confirms its email before it uses the app (#616)
A password account confirms its email before it signs in or uses the app.

- Create account ends on Check your inbox, which names the address, sends the link again and says
  where to open it. The screen is the same whatever the address.
- A password sign-in works once the address is confirmed, or in the browser that opened the
  account's own confirm link. Until then the right password is refused as a wrong one is, and the
  form offers Send the link again.
- A signed-in account whose address is not confirmed sees Confirm your email instead of the app.
  The Worker answers its sessions and API tokens 403 EMAIL_UNCONFIRMED everywhere but me, logout,
  the signed-in resend, the link's finish route, and the billing portal for an account that pays.
- POST /api/auth/verify-email/resend sends the link again while signed out, with limits and the
  captcha before any look-up. One budget of three confirm links an hour covers every way of
  asking for one.
- Sign-up answers first, then makes the account, its profile and its first link in one batch,
  tried twice. Signing up again for an address waiting for its link mails a fresh link.
- A sign-in code, a reset link and Google sign-in confirm the address. A passkey or two-factor
  does not.
- /api/v1 capabilities, reminders and sheet syncs leave out an account waiting for its link.
- The welcome and confirm mails say the link starts the account and where to sign in after
  opening it. No mail on the sign-up path has an em dash before the shared footer.

No migration.
2026-10-10 18:17:51 +02:00

88 lines
3.4 KiB
TypeScript

/**
* Direct access to the local D1 the e2e Worker serves from.
*
* `wrangler dev` and `wrangler d1 execute --local` share the same state directory, so specs can
* arrange fixture state the API deliberately refuses to expose — clearing rate-limit counters,
* resetting a fixture user's 2FA between runs, planting a login code whose raw value the spec
* knows. Same mechanism global.setup.ts uses; kept here so auth specs don't each grow a copy.
*/
import { expect } from '@playwright/test'
import { execFileSync } from 'node:child_process'
import { existsSync } from 'node:fs'
import { resolve } from 'node:path'
function wranglerBin(): { wrangler: string; workerDir: string } {
const workerDir = resolve(process.cwd(), '..', 'worker')
// eslint-disable-next-line security/detect-non-literal-fs-filename -- derived from cwd, not input
if (!existsSync(workerDir)) throw new Error(`worker/ not found next to ${process.cwd()}`)
// The worker's own wrangler, by path — not `npx wrangler`, which resolves off PATH.
return { wrangler: resolve(workerDir, 'node_modules', '.bin', 'wrangler'), workerDir }
}
const sleepSync = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
/**
* Specs run in parallel and the dev Worker holds the same file, so a concurrent statement can
* land on SQLITE_BUSY. That's contention, not failure — retry briefly before giving up.
*/
function execWithRetry(args: string[]): string {
const { wrangler, workerDir } = wranglerBin()
let lastErr: unknown
for (let attempt = 0; attempt < 10; attempt++) {
try {
return execFileSync(wrangler, args, { cwd: workerDir, stdio: 'pipe' }).toString()
} catch (err) {
lastErr = err
const text = String((err as { stderr?: Buffer; stdout?: Buffer }).stderr ?? '').concat(
String((err as { stdout?: Buffer }).stdout ?? '')
)
if (!text.includes('SQLITE_BUSY') && !text.includes('database is locked')) throw err
sleepSync(250 * (attempt + 1))
}
}
throw lastErr
}
export function sql(command: string): void {
execWithRetry(['d1', 'execute', 'finance-manager', '--local', '--command', command])
}
/** Run a SELECT and return its rows. */
export function sqlRows<T>(command: string): T[] {
const out = execWithRetry([
'd1',
'execute',
'finance-manager',
'--local',
'--json',
'--command',
command,
])
const parsed = JSON.parse(out) as { results: T[] }[]
return parsed[0]?.results ?? []
}
/**
* Wait until signing up `email` has made its account and its profile. The Worker answers a
* sign-up before it makes the account, so a spec that reads or changes the account waits here.
*/
export async function accountMade(email: string): Promise<void> {
const made = () =>
sqlRows<{ n: number }>(
`SELECT COUNT(*) AS n FROM profiles JOIN users ON users.id = profiles.user_id
WHERE users.email = '${email}'`
)[0]?.n ?? 0
await expect
.poll(made, { timeout: 15_000, message: `the account for ${email}` })
.toBeGreaterThan(0)
}
/**
* Confirm the address `email` signed up with, as opening its confirm link does. A password account
* signs in only once its address is confirmed, and no spec can read the mail with the link.
*/
export async function confirmAccount(email: string): Promise<void> {
await accountMade(email)
sql(`UPDATE users SET email_verified = 1 WHERE email = '${email}'`)
}