115 lines
3.6 KiB
TypeScript
115 lines
3.6 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, type Account } from './stack'
|
|
import { currentCode } from './totp'
|
|
|
|
export interface Factor {
|
|
id: string
|
|
secret: string
|
|
}
|
|
|
|
export interface MfaResult {
|
|
status: number
|
|
body: Record<string, unknown>
|
|
}
|
|
|
|
export 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: await currentCode(factor.secret),
|
|
})
|
|
}
|
|
|
|
/** The HTTP status and GoTrue's error code of an answer: never a body, a token or a secret. */
|
|
export function refusal(result: {
|
|
status: number
|
|
body: Record<string, unknown>
|
|
}): string {
|
|
const code = result.body.error_code ?? result.body.code
|
|
return `HTTP ${result.status}${typeof code === 'string' ? ` ${code}` : ''}`
|
|
}
|
|
|
|
/** Enrols and verifies a TOTP factor from `token`, returning the new aal2 access token. */
|
|
export async function stepUp(token: string, name = 'device'): Promise<string> {
|
|
const enrol = await enrolTotp(token, name)
|
|
if (!enrol.factor) throw new Error(`enrol failed: ${refusal(enrol)}`)
|
|
const verified = await verifyTotp(token, enrol.factor)
|
|
const aal2 = verified.body.access_token as string
|
|
if (!aal2) throw new Error(`verify failed: ${refusal(verified)}`)
|
|
return aal2
|
|
}
|
|
|
|
/** A confirmed account signed in, with one verified factor and its aal2 token. */
|
|
export interface SteppedAccount extends Account {
|
|
aal2: string
|
|
}
|
|
|
|
export async function steppedUp(account: Account): Promise<SteppedAccount> {
|
|
return { ...account, aal2: await stepUp(account.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>
|
|
}
|