Files
faunosteo/packages/supabase/tests/sandbox/mfa.ts
T
bchanot 77e5fa4cf5 feat(supabase): V1-2.1 M4/M5 secure sheet access and review workflow
M4 20261028100000_sheet_access_hardening + M5 20261028110000_sheet_review_workflow
(applied together; no unprotected window). Implements contract §5-§14.

- Catalogue rights table + owner RPCs; has_mfa / has_aal2_session (live
  auth.sessions check); grant_active vs caller_has split; catalogue reader
  predicate; can_edit_sheet on the sheet_editor capability (F14).
- AR-1 B: aal2 required on every platform role change, target verified factor,
  race-free last-owner guard (F18/F19); service_role loses table privileges on
  the catalogue + profiles/profile_roles and EXECUTE on the role RPCs (F12/F17).
- Reviewed lifecycle: version provenance + review columns, content/freeze/
  author triggers, rounds/comments/acknowledgments, save/submit/withdraw/
  comment/acknowledge/decide, atomic publish_sheet_version(review_id) on the
  stored verdict, deprecate/archive/restore, species RPCs, equine working copy,
  uploads with the storage check (F7) + editor INSERT policy + 2 MiB bucket.
  F1-F3,F5,F6,F8,F9,F13,F15,F16 closed. Verdict is a fixture until M6 (V1-2.3).
- O22: SQL business mirror removed, declared status check kept; pgTAP 011 and
  the Rust generator's SQL parts deleted, ledger retargeted.
- Access layer sheets.ts (closed SheetFailure kinds); old client publish gate
  deleted; types regenerated; upload tool reads via get_sheet_asset_state.

Tested on the throwaway sandbox only; DEV untouched. pgTAP 850 (real stack) /
122 (PGlite) green; real-GoTrue AR-1 B + F18 race green; fresh install and
M3->M5 upgrade green; V1-1 regression green; rust:check, typecheck, lint,
build, types drift clean. BDR-084, LRN-095.
2026-10-28 15:52:49 +01:00

104 lines
3.0 KiB
TypeScript

/**
* GoTrue MFA calls of the sandbox (real GoTrue v2.197.0): enrol a TOTP factor,
* challenge and verify it to reach `aal2`, remove it. Every call carries the
* user's own access token, as the browser does. TOTP secrets and tokens stay
* in memory and are never printed.
*/
import { stack } from './stack'
import { msToNextStep, totpCode } from './totp'
export interface Factor {
id: string
secret: string
}
export interface MfaResult {
status: number
body: Record<string, unknown>
}
async function authRequest(
method: string,
path: string,
token: string,
body?: unknown,
): Promise<MfaResult> {
const res = await fetch(stack.authUrl + path, {
method,
headers: {
apikey: stack.anonKey,
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await res.text()
let parsed: Record<string, unknown> = {}
try {
parsed = JSON.parse(text) as Record<string, unknown>
} catch {
// not JSON: keep an empty body
}
return { status: res.status, body: parsed }
}
/** POST /factors: a new unverified TOTP factor (the secret is shown once). */
export async function enrolTotp(
token: string,
name: string,
): Promise<{ status: number; factor: Factor | null; body: MfaResult['body'] }> {
const res = await authRequest('POST', '/factors', token, {
factor_type: 'totp',
friendly_name: name,
})
const totp = res.body.totp as { secret?: string } | undefined
const factor =
res.status === 200 && typeof res.body.id === 'string' && totp?.secret
? { id: res.body.id, secret: totp.secret }
: null
return { status: res.status, factor, body: res.body }
}
/** Challenge then verify with the current code; resolves with the new session (aal2 on success). */
export async function verifyTotp(
token: string,
factor: Factor,
): Promise<MfaResult> {
const challenge = await authRequest(
'POST',
`/factors/${factor.id}/challenge`,
token,
{},
)
if (challenge.status !== 200) return challenge
return authRequest('POST', `/factors/${factor.id}/verify`, token, {
challenge_id: challenge.body.id,
code: totpCode(factor.secret),
})
}
/**
* Verify with a code of a step not used before for this factor: GoTrue refuses
* a code it already accepted, so a second verification waits for the next step.
*/
export async function verifyTotpFreshStep(
token: string,
factor: Factor,
): Promise<MfaResult> {
await new Promise((resolve) => setTimeout(resolve, msToNextStep() + 200))
return verifyTotp(token, factor)
}
export function unenrol(token: string, factorId: string): Promise<MfaResult> {
return authRequest('DELETE', `/factors/${factorId}`, token)
}
/** The claims of an access token (payload only; the signature is not checked here). */
export function claimsOf(token: string): Record<string, unknown> {
const payload = token.split('.')[1] ?? ''
return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as Record<
string,
unknown
>
}