From 2dcc29750001373d96faa862a17ad6b68d5e98bc Mon Sep 17 00:00:00 2001 From: Miranda Limonczenko Date: Wed, 25 Nov 2026 11:52:47 -0800 Subject: [PATCH] feat(docs): add a multi-factor authentication guide eval --- evals/docs/build-docs-039-auth-mfa/EVAL.ts | 146 +++++ evals/docs/build-docs-039-auth-mfa/PROMPT.md | 42 ++ evals/docs/build-docs-039-auth-mfa/README.md | 100 +++ evals/docs/build-docs-039-auth-mfa/config.ts | 74 +++ .../local/supabase/config.toml | 165 +++++ .../migrations/20240101000000_init.sql | 30 + .../build-docs-039-auth-mfa/migrations.ts | 97 +++ evals/docs/build-docs-039-auth-mfa/probes.ts | 602 ++++++++++++++++++ 8 files changed, 1256 insertions(+) create mode 100644 evals/docs/build-docs-039-auth-mfa/EVAL.ts create mode 100644 evals/docs/build-docs-039-auth-mfa/PROMPT.md create mode 100644 evals/docs/build-docs-039-auth-mfa/README.md create mode 100644 evals/docs/build-docs-039-auth-mfa/config.ts create mode 100644 evals/docs/build-docs-039-auth-mfa/local/supabase/config.toml create mode 100644 evals/docs/build-docs-039-auth-mfa/local/supabase/migrations/20240101000000_init.sql create mode 100644 evals/docs/build-docs-039-auth-mfa/migrations.ts create mode 100644 evals/docs/build-docs-039-auth-mfa/probes.ts diff --git a/evals/docs/build-docs-039-auth-mfa/EVAL.ts b/evals/docs/build-docs-039-auth-mfa/EVAL.ts new file mode 100644 index 00000000..3161acd1 --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/EVAL.ts @@ -0,0 +1,146 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { restartStack } from '../lib/local-stack.js'; +import { turnCodesOn } from './config.js'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + CHECK, + checkCodesAllowed, + checkHalfway, + checkPlainReads, + checkPlainWrites, + checkSkippedReads, + checkSkippedWrites, + checkStackStarts, + checkStaleDevice, + checkTypedReads, + checkTypedWrites, + notRun, + probeCodes, + type Setup, + setupWorld, + signInWithCode, + type World, +} from './probes.js'; + +const GUIDE_PATH = /guides\/auth\/auth-mfa(?:\.md)?(?:[?#]|$)/; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const started = await restartStack(ctx); + const migrations = await applyPendingMigrations(ctx); + const codes = started.ok + ? await probeCodes(ctx) + : { ok: false as const, message: started.message }; + const ready = !started.ok + ? started + : codes.ok + ? codes + : await turnCodesOn(ctx); + const setup: Setup = ready.ok + ? await setupWorld(ctx) + : { ok: false, message: ready.message }; + const world = setup.ok ? setup.world : undefined; + const setupFailure = setup.ok ? '' : setup.message; + const probe = ( + name: string, + run: (world: World) => Promise + ): Promise => gated(world, setupFailure, name, run); + + const plainReads = await probe(CHECK.plainReads, (w) => checkPlainReads(w)); + const plainWrites = await probe(CHECK.plainWrites, (w) => + checkPlainWrites(ctx, w) + ); + const halfway = await probe(CHECK.halfway, (w) => checkHalfway(w)); + const skippedReads = await probe(CHECK.skippedReads, (w) => + checkSkippedReads(ctx, w) + ); + const staleDevice = await probe(CHECK.staleDevice, (w) => + checkStaleDevice(w) + ); + const typedSignIn = world + ? await signInWithCode(ctx, world) + : { ok: false as const, message: setupFailure }; + const typedReads = await probe(CHECK.typedReads, (w) => + checkTypedReads(typedSignIn, w) + ); + const typedWrites = await probe(CHECK.typedWrites, (w) => + checkTypedWrites(ctx, typedSignIn, w) + ); + const skippedWrites = await probe(CHECK.skippedWrites, (w) => + checkSkippedWrites(ctx, w) + ); + + const checks: CheckResult[] = [ + checkStackStarts(started), + checkMigrationsWereApplied(migrations), + started.ok + ? checkCodesAllowed(codes) + : notRun(CHECK.codesAllowed, started.message), + plainReads, + plainWrites, + halfway, + skippedReads, + skippedWrites, + staleDevice, + typedReads, + typedWrites, + checkGuideWasRead(ctx), + ]; + + return { passed: checks.every((check) => check.passed), checks }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + passed: false, + checks: [ + { + name: 'scorer evaluated who can open a journal', + passed: false, + notes: message, + }, + ], + }; + } +}; + +export default scorer; + +async function gated( + world: World | undefined, + setupFailure: string, + name: string, + run: (world: World) => Promise +): Promise { + if (!world) return notRun(name, setupFailure); + try { + return await run(world); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { name, passed: false, notes: message.slice(0, 300) }; + } +} + +function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult { + const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) => + call.pages?.some((page) => GUIDE_PATH.test(page.url)) + ); + const withContent = calls.filter((call) => call.hasContent); + return { + name: 'the agent read the multi-factor authentication guide the prompt referenced', + passed: withContent.length > 0, + notes: + withContent.length > 0 + ? withContent.map((call) => call.source).join(', ') + : calls.length > 0 + ? `reached the guide via ${calls.map((call) => call.source).join(', ')} but retrieved no page content` + : 'no docs call reached the guide', + }; +} diff --git a/evals/docs/build-docs-039-auth-mfa/PROMPT.md b/evals/docs/build-docs-039-auth-mfa/PROMPT.md new file mode 100644 index 00000000..0652390e --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/PROMPT.md @@ -0,0 +1,42 @@ +--- +stage: build +interface: cli +product: + - auth + - database +topic: + - rls + - security +services: + - gotrue + - kong + - postgrest +motivation: >- + An app that offers a second sign-in step has to lock data until people who + turned it on complete it, and keep working for everyone else. Customers end + up with rules that refuse every request, or that let a session that + skipped the code through. This checks that an agent reading the + multi-factor authentication guide locks a journal behind a code only for + the people who turned one on. The prompt omits the guide's vocabulary on + purpose, so read README.md before editing it. +--- + +Dayline is a journaling app, and some people want their journal behind a +second lock. Let people turn on a six-digit code from an authenticator app +like Google Authenticator. They switch it on by scanning a QR code and typing +the first code, so someone who gives up halfway has not switched it on. + +Once it is on, their entries and habits stay locked after they sign in with +their password, until they type a fresh code. If they were already signed in +on another device when they switched it on, that device is locked too until a +code is typed there. People who never switch it on keep using Dayline with +just their password, the same as today. + +Our front-end team builds the screens. Set up the rest in the local project +and make sure it works on the local database. + +Read the guide below before you start and rely on it for how to set this up, +rather than on what you already know. + +REFERENCE +https://supabase.com/docs/guides/auth/auth-mfa.md diff --git a/evals/docs/build-docs-039-auth-mfa/README.md b/evals/docs/build-docs-039-auth-mfa/README.md new file mode 100644 index 00000000..8741fb5f --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/README.md @@ -0,0 +1,100 @@ +# build-docs-039-auth-mfa + +## What this eval measures + +The subject is [Multi-Factor Authentication](https://supabase.com/docs/guides/auth/auth-mfa), not the agent. The prompt +is a product request plus the page's url, and the checks say whether an agent that read the page locks data behind a +second step only for the people who turned one on. + +One claim: once someone turns on an authenticator code, their rows open only after they type it, on every device, and +everyone without a code keeps working with a password. + +The eval expects a rule that answers every request. Signed-in users cannot read `auth.mfa_factors`, so the rule has to +learn whether someone has a code without reading that table as the user. A rule that tries fails every request with +`42501 permission denied for table mfa_factors`, and the controls catch it. + +## Do not reintroduce the vocabulary + +The prompt keeps "authenticator app", because a user has no other name for it. Keep all of these out of `PROMPT.md`: + +MFA, multi-factor, two-factor, 2FA, second factor, factor, TOTP, enroll, verify, challenge, AAL, aal1, aal2, assurance +level, JWT, claim, token, session, refresh, restrictive, permissive, policy, RLS, row level security, mfa_factors, +security definer, authenticated, config.toml, `[auth.mfa.totp]`, enroll_enabled, verify_enabled. + +## The seed carries the contract + +`local/supabase/migrations/20240101000000_init.sql` is a journal app with two tables. Three things in the seed are +load-bearing. + +- **Both tables already have a permissive rule for their owner.** A second permissive rule that asks for the code + changes nothing, because rules of that kind combine with OR. Only a rule required in addition, or a rewrite of the + existing ones, passes. +- **Two tables, not one.** Every probe reads and writes both, so a rule on one table does not pass. +- **`[auth.mfa.totp]` is off in `local/supabase/config.toml`**, as `supabase init` writes it. + +`enable_confirmations = false` lets the scorer sign people up without a mailbox. + +The prompt says which rule applies to people without a code: they keep working. It also says someone who gave up +halfway has not turned the code on, and that a device signed in before the code was turned on is locked too. Each of +those has its own check. + +## Codes are scored once, then turned on + +`the project lets people turn on an authenticator-app code` runs on the agent's own `config.toml`. The scorer signs up a +person, sets up a code and types it. That check reflects the pinned CLI's local default, which has codes off. Hosted +projects have them on. + +If the check fails, the scorer sets `enroll_enabled = true` and `verify_enabled = true` under `[auth.mfa.totp]` in the +workspace's `config.toml` and restarts the stack. Every other check then measures the agent's rules, not the switch. +The scorer restores nothing afterwards, so score once per stack. + +## Do not drop the positive controls + +The refusal checks pass for a project where nobody can read or change anything. The controls stop that: + +- `someone without a code reads their journal with a password` and `someone without a code adds, changes and removes + journal rows with a password` fail a rule that locks everyone, or one that blocks changes for everyone. +- `a person who typed their code reads their journal` and `a person who typed their code adds, changes and removes + journal rows` fail a rule that locks the code holder for good. +- `a device signed in before the code was turned on is locked once it is on` first reads the rows from that device + before the code is turned on. If that read fails, the check reports could-not-measure. + +The refusal checks count rows as the superuser. An insert must write nothing, and an update or delete must leave the +seeded row as it was. Any error is accepted as a refusal once the superuser read confirms that, so a trigger that raises +its own error passes. The skipped-code reads pass on an empty result or any error. + +Every person and row is made by the scorer after the agent's work, with names scoped to the run. The scorer types the +code itself, computed from the secret it gets back when it sets the code up. + +## Order of the scorer + +The scorer restarts the stack first, so Auth runs on the project's `config.toml` whether or not the agent restarted it. +Restarting needs the services in `services:`, so a harness that starts every service also passes. It then applies +pending migrations with `supabase migration up --local`, which writes to the database. Then it probes codes, and turns +them on and restarts if needed. + +When the scorer cannot set up a code even after turning codes on, every check about a code holder reports `not run` +with the reason. The skipped-code writes run last, because a write that gets through would change rows the other probes +read. + +## The guide has to actually be read + +`the agent read the multi-factor authentication guide the prompt referenced` requires a docs call that reached the page +with content. A read of the TOTP or phone page alone does not count. Read `docs.calls` before reading a score. + +## Checks expected to saturate + +The restart, the migration check, and the two skipped-code refusals. A rule that refuses every request passes both +refusals. The device signed in before carries the same token level as a fresh password sign-in, so it moves with the +skipped-code reads. Only a rule that reads whether someone has a code from the token, such as a claim added at sign-in, +separates the two. The signal is expected in the code check and the five controls. + +## What this eval does not score + +- **Screens and client code.** No client is seeded, so the scorer runs the sign-in and code steps itself. +- **Removing a code.** The prompt does not ask for it. +- **Phone codes.** The prompt asks for an authenticator app only. +- **Functions that bypass the rules.** A function that runs as its owner skips row rules. The seed has none, and the + prompt does not ask for one. +- **Anyone who is not signed in.** The seed grants them nothing. +- **How the agent applied its change.** Any route that leaves it applied passes. diff --git a/evals/docs/build-docs-039-auth-mfa/config.ts b/evals/docs/build-docs-039-auth-mfa/config.ts new file mode 100644 index 00000000..2ef92f3c --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/config.ts @@ -0,0 +1,74 @@ +import type { LocalStackEvalContext } from '@supabase-evals/core'; +import { readStack, restartStack, type Step } from '../lib/local-stack.js'; + +const CONFIG = 'supabase/config.toml'; +const SECTION = '[auth.mfa.totp]'; +const SWITCHES = ['enroll_enabled = true', 'verify_enabled = true']; + +type Exec = Pick; + +export async function turnCodesOn(ctx: Exec): Promise { + const read = await ctx.exec(`cat ${CONFIG}`); + if (read.exitCode !== 0) { + return { ok: false, message: `could not read ${CONFIG}` }; + } + const encoded = Buffer.from(withCodesOn(read.stdout ?? ''), 'utf8').toString( + 'base64' + ); + const written = await ctx.exec(`echo ${encoded} | base64 -d > ${CONFIG}`); + if (written.exitCode !== 0) { + return { ok: false, message: `could not write ${CONFIG}` }; + } + const restarted = await restartStack(ctx); + if (!restarted.ok) { + return { + ok: false, + message: `the stack did not restart with codes on: ${restarted.message}`, + }; + } + return waitForAuth(ctx); +} + +async function waitForAuth(ctx: Exec): Promise { + let last = ''; + for (let attempt = 0; attempt < 30; attempt += 1) { + try { + const stack = await readStack(ctx); + const response = await fetch(`${stack.apiUrl}/auth/v1/health`, { + headers: { apikey: stack.clientKey }, + }); + if (response.ok) return { ok: true, message: '' }; + last = `health returned ${response.status}`; + } catch (error) { + last = error instanceof Error ? error.message : String(error); + } + await new Promise((resolve) => { + setTimeout((): void => resolve(undefined), 2000); + }); + } + return { + ok: false, + message: `Auth did not answer after the restart: ${last.slice(0, 200)}`, + }; +} + +export function withCodesOn(toml: string): string { + const lines = toml.split('\n'); + const start = lines.findIndex((line) => line.trim() === SECTION); + if (start < 0) { + return `${toml.trimEnd()}\n\n${SECTION}\n${SWITCHES.join('\n')}\n`; + } + const next = lines.findIndex( + (line, index) => index > start && /^\s*\[/.test(line) + ); + const end = next < 0 ? lines.length : next; + const kept = lines + .slice(start + 1, end) + .filter((line) => !/^\s*(enroll_enabled|verify_enabled)\s*=/.test(line)); + return [ + ...lines.slice(0, start + 1), + ...SWITCHES, + ...kept, + ...lines.slice(end), + ].join('\n'); +} diff --git a/evals/docs/build-docs-039-auth-mfa/local/supabase/config.toml b/evals/docs/build-docs-039-auth-mfa/local/supabase/config.toml new file mode 100644 index 00000000..41cc2e2c --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-auth-mfa" + +[api] +enabled = true +port = 54321 +schemas = ["public", "graphql_public"] +extra_search_path = ["public", "extensions"] +max_rows = 1000 + +[api.tls] +enabled = false + +[db] +port = 54322 +shadow_port = 54320 +major_version = 17 + +[db.pooler] +enabled = false +port = 54329 +pool_mode = "transaction" +default_pool_size = 20 +max_client_conn = 100 + +[db.migrations] +enabled = true +schema_paths = [] + +[db.seed] +enabled = false + +[realtime] +enabled = true + +[studio] +enabled = true +port = 54323 +api_url = "http://127.0.0.1" +openai_api_key = "env(OPENAI_API_KEY)" + +[inbucket] +enabled = true +port = 54324 + +[storage] +enabled = true +file_size_limit = "50MiB" + +[storage.s3_protocol] +enabled = true + +[storage.analytics] +enabled = false +max_namespaces = 5 +max_tables = 10 +max_catalogs = 2 + +[storage.vector] +enabled = false +max_buckets = 10 +max_indexes = 5 + +[auth] +enabled = true +site_url = "http://127.0.0.1:3000" +additional_redirect_urls = ["https://127.0.0.1:3000"] +jwt_expiry = 3600 +enable_refresh_token_rotation = true +refresh_token_reuse_interval = 10 +enable_signup = true +enable_anonymous_sign_ins = false +enable_manual_linking = false +minimum_password_length = 6 +password_requirements = "" + +[auth.rate_limit] +email_sent = 2 +sms_sent = 30 +anonymous_users = 30 +token_refresh = 150 +sign_in_sign_ups = 30 +token_verifications = 30 +web3 = 30 + +[auth.email] +enable_signup = true +double_confirm_changes = true +enable_confirmations = false +secure_password_change = false +max_frequency = "1s" +otp_length = 6 +otp_expiry = 3600 + +[auth.sms] +enable_signup = false +enable_confirmations = false +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.sms.twilio] +enabled = false +account_sid = "" +message_service_sid = "" +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +[auth.mfa] +max_enrolled_factors = 10 + +[auth.mfa.totp] +enroll_enabled = false +verify_enabled = false + +[auth.mfa.phone] +enroll_enabled = false +verify_enabled = false +otp_length = 6 +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.external.apple] +enabled = false +client_id = "" +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +redirect_uri = "" +url = "" +skip_nonce_check = false +email_optional = false + +[auth.web3.solana] +enabled = false + +[auth.third_party.firebase] +enabled = false + +[auth.third_party.auth0] +enabled = false + +[auth.third_party.aws_cognito] +enabled = false + +[auth.third_party.clerk] +enabled = false + +[auth.oauth_server] +enabled = false +authorization_url_path = "/oauth/consent" +allow_dynamic_registration = false + +[edge_runtime] +enabled = true +policy = "per_worker" +inspector_port = 8083 +deno_version = 2 + +[analytics] +enabled = true +port = 54327 +backend = "postgres" + +[experimental] +orioledb_version = "" +s3_host = "env(S3_HOST)" +s3_region = "env(S3_REGION)" +s3_access_key = "env(S3_ACCESS_KEY)" +s3_secret_key = "env(S3_SECRET_KEY)" diff --git a/evals/docs/build-docs-039-auth-mfa/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-039-auth-mfa/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..914ffd10 --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,30 @@ +create table public.entries ( + id bigint generated always as identity primary key, + user_id uuid not null default auth.uid() references auth.users on delete cascade, + body text not null, + created_at timestamptz not null default now() +); + +create table public.habits ( + id bigint generated always as identity primary key, + user_id uuid not null default auth.uid() references auth.users on delete cascade, + name text not null +); + +alter table public.entries enable row level security; +alter table public.habits enable row level security; + +grant select, insert, update, delete on table public.entries to authenticated; +grant select, insert, update, delete on table public.habits to authenticated; + +create policy "People keep their own entries" + on public.entries for all + to authenticated + using ((select auth.uid()) = user_id) + with check ((select auth.uid()) = user_id); + +create policy "People keep their own habits" + on public.habits for all + to authenticated + using ((select auth.uid()) = user_id) + with check ((select auth.uid()) = user_id); diff --git a/evals/docs/build-docs-039-auth-mfa/migrations.ts b/evals/docs/build-docs-039-auth-mfa/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/migrations.ts @@ -0,0 +1,97 @@ +import { readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; + +export type MigrationState = { + pending: string[]; + applyFailed?: string; +}; + +export async function applyPendingMigrations( + ctx: LocalStackEvalContext +): Promise { + try { + return await apply(ctx); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { pending: ['unknown'], applyFailed: message.slice(0, 300) }; + } +} + +async function apply(ctx: LocalStackEvalContext): Promise { + const pending = await pendingVersions(ctx); + + if (pending.length === 0) { + return { pending }; + } + + const applied = await ctx.exec('supabase migration up --local', { + timeoutMs: 300_000, + }); + if (applied.exitCode !== 0) { + return { + pending, + applyFailed: firstError( + `${applied.stderr ?? ''}\n${applied.stdout ?? ''}` + ), + }; + } + return { pending }; +} + +export function checkMigrationsWereApplied(state: MigrationState): CheckResult { + return { + name: 'the agent applied the migrations it wrote', + passed: state.pending.length === 0, + notes: + state.pending.length === 0 + ? 'nothing pending' + : state.applyFailed + ? `pending: ${state.pending.join(', ')}; the scorer could not apply them: ${state.applyFailed}` + : `pending: ${state.pending.join(', ')}; the scorer applied them so the rest of the checks could run`, + }; +} + +async function pendingVersions(ctx: LocalStackEvalContext): Promise { + const onDisk = migrationVersionsOnDisk(ctx.hostWorkspace); + if (onDisk.length === 0) { + return []; + } + + const { rows: history } = await ctx.query( + "SELECT to_regclass('supabase_migrations.schema_migrations') IS NOT NULL AS present;" + ); + if (history[0]?.present !== true) { + return onDisk; + } + + const { rows } = await ctx.query( + 'SELECT version FROM supabase_migrations.schema_migrations;' + ); + const applied = new Set(rows.map((row) => String(row.version))); + return onDisk.filter((version) => !applied.has(version)); +} + +function migrationVersionsOnDisk(hostWorkspace: string): string[] { + let entries: string[]; + try { + entries = readdirSync(join(hostWorkspace, 'supabase', 'migrations')); + } catch { + return []; + } + return entries + .map((entry) => /^(\d+)(?:_.*)?\.sql$/.exec(entry)?.[1]) + .filter((version): version is string => version !== undefined) + .sort(); +} + +function firstError(output: string): string { + const lines = output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + const named = lines.find((line) => + /^(ERROR|FATAL|DETAIL|HINT)\b/i.test(line) + ); + return (named ?? lines[0] ?? 'no output').slice(0, 300); +} diff --git a/evals/docs/build-docs-039-auth-mfa/probes.ts b/evals/docs/build-docs-039-auth-mfa/probes.ts new file mode 100644 index 00000000..18a36b6b --- /dev/null +++ b/evals/docs/build-docs-039-auth-mfa/probes.ts @@ -0,0 +1,602 @@ +import { createHmac, randomUUID } from 'node:crypto'; +import type { + CheckResult, + LocalStackEvalContext, + SupabaseClient, +} from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; +import type { Step } from '../lib/local-stack.js'; + +export const CHECK = { + stackStarts: 'the local stack restarts on the project settings', + codesAllowed: 'the project lets people turn on an authenticator-app code', + plainReads: 'someone without a code reads their journal with a password', + plainWrites: + 'someone without a code adds, changes and removes journal rows with a password', + halfway: + 'someone who gave up setting up a code reads their journal with a password', + skippedReads: + 'a person with a code who has not typed it cannot read their journal', + skippedWrites: + 'a person with a code who has not typed it cannot add, change or remove anything', + typedReads: 'a person who typed their code reads their journal', + typedWrites: + 'a person who typed their code adds, changes and removes journal rows', + staleDevice: + 'a device signed in before the code was turned on is locked once it is on', +} as const; + +const PASSWORD = 'Dayline-pass-9'; +const STEP_SECONDS = 30; +const TABLES = [ + { table: 'entries', column: 'body' }, + { table: 'habits', column: 'name' }, +] as const; + +type Ctx = Pick; +type Person = { client: SupabaseClient; id: string; email: string }; +type Outcome = ({ ok: true } & T) | { ok: false; message: string }; +type ApiError = { code?: string; message: string }; +type ReadError = { table: string; code: string; message: string }; + +export type Signed = Outcome<{ person: Person }>; + +export type World = { + marker: string; + plain: Person; + halfway: Signed; + enrolled: Outcome<{ + person: Person; + factorId: string; + secret: string; + earlierDevice: SupabaseClient; + earlierDeviceRead: string[]; + }>; +}; + +export type Setup = { ok: true; world: World } | { ok: false; message: string }; + +export function notRun(name: string, reason: string): CheckResult { + return { name, passed: false, notes: `not run: ${reason}` }; +} + +export function checkStackStarts(started: Step): CheckResult { + return { + name: CHECK.stackStarts, + passed: started.ok, + notes: started.ok ? 'supabase start exited 0' : started.message, + }; +} + +export async function probeCodes(ctx: Ctx): Promise> { + const made = await signUp( + ctx, + `dayline-${randomUUID().slice(0, 8)}-probe@example.test` + ); + if (!made.ok) return made; + const { data, error } = await made.person.client.auth.mfa.enroll({ + factorType: 'totp', + }); + if (error || !data) { + return { + ok: false, + message: `could not start setting up a code: ${error?.message ?? 'no factor returned'}`, + }; + } + return typeCode(made.person.client, data.id, data.totp.secret); +} + +export function checkCodesAllowed(codes: Outcome): CheckResult { + return { + name: CHECK.codesAllowed, + passed: codes.ok, + notes: codes.ok + ? 'on the project settings, a person set up a code and typed it' + : `${codes.message}; the scorer turned codes on to run the other checks`, + }; +} + +export async function setupWorld(ctx: Ctx): Promise { + const marker = `dayline-${randomUUID().slice(0, 8)}`; + + const plain = await signUp(ctx, `${marker}-plain@example.test`); + if (!plain.ok) return plain; + const plainRows = await seedRows(ctx, plain.person.id, `${marker}-plain`); + if (!plainRows.ok) return plainRows; + + return { + ok: true, + world: { + marker, + plain: plain.person, + halfway: await setupHalfway(ctx, marker), + enrolled: await setupEnrolled(ctx, marker), + }, + }; +} + +async function setupHalfway(ctx: Ctx, marker: string): Promise { + const made = await signUp(ctx, `${marker}-halfway@example.test`); + if (!made.ok) return made; + const seeded = await seedRows(ctx, made.person.id, `${marker}-halfway`); + if (!seeded.ok) return seeded; + const { error } = await made.person.client.auth.mfa.enroll({ + factorType: 'totp', + }); + if (error) { + return { + ok: false, + message: `could not start setting up a code: ${error.message}`, + }; + } + return { ok: true, person: made.person }; +} + +async function setupEnrolled( + ctx: Ctx, + marker: string +): Promise { + const made = await signUp(ctx, `${marker}-coded@example.test`); + if (!made.ok) return made; + const { person } = made; + const seeded = await seedRows(ctx, person.id, `${marker}-coded`); + if (!seeded.ok) return seeded; + + const earlier = await signIn(ctx, person.email); + if (!earlier.ok) return earlier; + const earlierRead = await readMarkers(earlier.client, `${marker}-coded`); + + const { data, error } = await person.client.auth.mfa.enroll({ + factorType: 'totp', + }); + if (error || !data) { + return { + ok: false, + message: `could not start setting up a code: ${error?.message ?? 'no factor returned'}`, + }; + } + const secret = data.totp.secret; + const verified = await typeCode(person.client, data.id, secret); + if (!verified.ok) return verified; + + const { rows } = await ctx.query( + `select status::text as status from auth.mfa_factors where id = '${data.id}'` + ); + if (rows[0]?.status !== 'verified') { + return { + ok: false, + message: `the code was accepted but the factor is ${String(rows[0]?.status ?? 'missing')}`, + }; + } + const level = await levelOf(person.client); + if (level.current !== 'aal2') { + return { + ok: false, + message: `typing the first code left the session at ${level.current}`, + }; + } + + return { + ok: true, + person, + factorId: data.id, + secret, + earlierDevice: earlier.client, + earlierDeviceRead: earlierRead.found, + }; +} + +export async function checkPlainReads(world: World): Promise { + return readsOwn( + CHECK.plainReads, + world.plain.client, + `${world.marker}-plain` + ); +} + +export async function checkPlainWrites( + ctx: Ctx, + world: World +): Promise { + return writesOwn( + ctx, + CHECK.plainWrites, + world.plain, + `${world.marker}-plain-new` + ); +} + +export async function checkHalfway(world: World): Promise { + if (!world.halfway.ok) return notRun(CHECK.halfway, world.halfway.message); + return readsOwn( + CHECK.halfway, + world.halfway.person.client, + `${world.marker}-halfway` + ); +} + +export async function checkSkippedReads( + ctx: Ctx, + world: World +): Promise { + const { enrolled } = world; + if (!enrolled.ok) return notRun(CHECK.skippedReads, enrolled.message); + const skipped = await signIn(ctx, enrolled.person.email); + if (!skipped.ok) { + return { name: CHECK.skippedReads, passed: false, notes: skipped.message }; + } + const level = await levelOf(skipped.client); + if (level.current !== 'aal1' || level.next !== 'aal2') { + return { + name: CHECK.skippedReads, + passed: false, + notes: `could not measure: signing in with a password gave ${level.current}, next ${level.next}`, + }; + } + return readsNothing( + CHECK.skippedReads, + skipped.client, + `${world.marker}-coded` + ); +} + +export async function checkStaleDevice(world: World): Promise { + const { enrolled } = world; + if (!enrolled.ok) return notRun(CHECK.staleDevice, enrolled.message); + const before = enrolled.earlierDeviceRead; + if (before.length < TABLES.length) { + return { + name: CHECK.staleDevice, + passed: false, + notes: `could not measure: before the code was turned on, the device got back ${before.length > 0 ? `only ${before.join(', ')}` : 'nothing'}`, + }; + } + return readsNothing( + CHECK.staleDevice, + enrolled.earlierDevice, + `${world.marker}-coded` + ); +} + +export async function signInWithCode(ctx: Ctx, world: World): Promise { + const { enrolled } = world; + if (!enrolled.ok) return { ok: false, message: enrolled.message }; + const signedIn = await signIn(ctx, enrolled.person.email); + if (!signedIn.ok) return signedIn; + const verified = await typeCode( + signedIn.client, + enrolled.factorId, + enrolled.secret + ); + if (!verified.ok) return verified; + const level = await levelOf(signedIn.client); + if (level.current !== 'aal2') { + return { + ok: false, + message: `typing the code at sign-in left the session at ${level.current}`, + }; + } + return { + ok: true, + person: { ...enrolled.person, client: signedIn.client }, + }; +} + +export async function checkTypedReads( + typedSignIn: Signed, + world: World +): Promise { + if (!typedSignIn.ok) return notRun(CHECK.typedReads, typedSignIn.message); + return readsOwn( + CHECK.typedReads, + typedSignIn.person.client, + `${world.marker}-coded` + ); +} + +export async function checkTypedWrites( + ctx: Ctx, + typedSignIn: Signed, + world: World +): Promise { + if (!typedSignIn.ok) return notRun(CHECK.typedWrites, typedSignIn.message); + return writesOwn( + ctx, + CHECK.typedWrites, + typedSignIn.person, + `${world.marker}-coded-new` + ); +} + +export async function checkSkippedWrites( + ctx: Ctx, + world: World +): Promise { + const { enrolled } = world; + if (!enrolled.ok) return notRun(CHECK.skippedWrites, enrolled.message); + const skipped = await signIn(ctx, enrolled.person.email); + if (!skipped.ok) { + return { name: CHECK.skippedWrites, passed: false, notes: skipped.message }; + } + const { id } = enrolled.person; + const seeded = `${world.marker}-coded`; + const added = `${world.marker}-skipped`; + const changed = `${world.marker}-changed`; + const problems: string[] = []; + const refusals: string[] = []; + + for (const { table, column } of TABLES) { + const { error: insertError } = await skipped.client + .from(table) + .insert({ user_id: id, [column]: added }); + if ((await countWhere(ctx, table, column, added)) > 0) { + problems.push(`added to ${table}`); + } else if (insertError?.code) { + refusals.push(`${table} insert ${insertError.code}`); + } + + await skipped.client + .from(table) + .update({ [column]: changed }) + .eq(column, seeded); + if ((await countWhere(ctx, table, column, changed)) > 0) { + problems.push(`changed a row in ${table}`); + continue; + } + + await skipped.client.from(table).delete().eq(column, seeded); + if ((await countWhere(ctx, table, column, seeded)) === 0) { + problems.push(`removed a row from ${table}`); + } + } + + return { + name: CHECK.skippedWrites, + passed: problems.length === 0, + notes: + problems.length > 0 + ? problems.join('; ') + : `entries and habits are unchanged${refusals.length > 0 ? ` (${refusals.join(', ')})` : ''}`, + }; +} + +async function readsOwn( + name: string, + client: SupabaseClient, + value: string +): Promise { + const read = await readMarkers(client, value); + const missing = TABLES.map(({ table }) => table).filter( + (table) => !read.found.includes(table) + ); + return { + name, + passed: missing.length === 0, + notes: + missing.length === 0 + ? 'got their entry and habit back' + : `no row back from ${missing.join(', ')}${read.errors.length > 0 ? `: ${describe(read.errors)}` : ''}`, + }; +} + +async function readsNothing( + name: string, + client: SupabaseClient, + value: string +): Promise { + const read = await readMarkers(client, value); + if (read.found.length > 0) { + return { + name, + passed: false, + notes: `read their rows from ${read.found.join(', ')}`, + }; + } + return { + name, + passed: true, + notes: + read.errors.length > 0 + ? `refused: ${describe(read.errors)}` + : 'entries and habits came back empty', + }; +} + +async function readMarkers( + client: SupabaseClient, + value: string +): Promise<{ found: string[]; errors: ReadError[] }> { + const found: string[] = []; + const errors: ReadError[] = []; + for (const { table, column } of TABLES) { + const { data, error } = await client + .from(table) + .select(column) + .eq(column, value); + if (error) { + errors.push({ table, code: error.code ?? '', message: error.message }); + } else if ((data ?? []).length > 0) { + found.push(table); + } + } + return { found, errors }; +} + +function describe(errors: ReadError[]): string { + return errors + .map((error) => `${error.table}: ${error.code} ${error.message}`.trim()) + .join('; '); +} + +async function writesOwn( + ctx: Ctx, + name: string, + person: Person, + value: string +): Promise { + const problems: string[] = []; + const changed = `${value}-changed`; + for (const { table, column } of TABLES) { + const { error: addError } = await person.client + .from(table) + .insert({ user_id: person.id, [column]: value }); + if ((await countWhere(ctx, table, column, value, person.id)) !== 1) { + problems.push(`could not add to ${table}${said(addError)}`); + continue; + } + const { error: changeError } = await person.client + .from(table) + .update({ [column]: changed }) + .eq(column, value); + if ((await countWhere(ctx, table, column, changed, person.id)) !== 1) { + problems.push(`could not change a row in ${table}${said(changeError)}`); + continue; + } + const { error: removeError } = await person.client + .from(table) + .delete() + .eq(column, changed); + if ((await countWhere(ctx, table, column, changed, person.id)) !== 0) { + problems.push(`could not remove a row from ${table}${said(removeError)}`); + } + } + return { + name, + passed: problems.length === 0, + notes: + problems.length === 0 + ? 'added, changed and removed a row in entries and habits' + : problems.join('; '), + }; +} + +function said(error: ApiError | null): string { + return error ? ` (${error.code ?? ''} ${error.message})` : ''; +} + +async function signUp(ctx: Ctx, email: string): Promise { + const client = await ctx.getClient(); + const { data, error } = await client.auth.signUp({ + email, + password: PASSWORD, + }); + if (error || !data.user || !data.session) { + return { + ok: false, + message: `could not sign up ${email}: ${error?.message ?? 'no session'}`, + }; + } + return { ok: true, person: { client, id: data.user.id, email } }; +} + +async function signIn( + ctx: Ctx, + email: string +): Promise> { + const client = await ctx.getClient(); + const { data, error } = await client.auth.signInWithPassword({ + email, + password: PASSWORD, + }); + if (error || !data.session) { + return { + ok: false, + message: `could not sign in ${email}: ${error?.message ?? 'no session'}`, + }; + } + return { ok: true, client }; +} + +async function seedRows( + ctx: Ctx, + userId: string, + value: string +): Promise> { + const result = await execSql( + ctx, + `insert into public.entries (user_id, body) values ('${userId}', '${value}'); + insert into public.habits (user_id, name) values ('${userId}', '${value}');` + ); + return result.ok + ? { ok: true } + : { ok: false, message: `could not add rows: ${result.message}` }; +} + +async function countWhere( + ctx: Ctx, + table: string, + column: string, + value: string, + userId?: string +): Promise { + const owner = userId ? ` and user_id = '${userId}'` : ''; + const { rows } = await ctx.query( + `select count(*)::int as count from public.${table} where ${column} = '${value}'${owner}` + ); + return Number(rows[0]?.count ?? 0); +} + +async function levelOf( + client: SupabaseClient +): Promise<{ current: string; next: string }> { + const { data } = await client.auth.mfa.getAuthenticatorAssuranceLevel(); + return { + current: String(data?.currentLevel ?? 'none'), + next: String(data?.nextLevel ?? 'none'), + }; +} + +async function typeCode( + client: SupabaseClient, + factorId: string, + secret: string +): Promise> { + let last = ''; + for (let attempt = 0; attempt < 2; attempt += 1) { + if (attempt > 0) await waitForNextStep(); + const { error } = await client.auth.mfa.challengeAndVerify({ + factorId, + code: totp(secret), + }); + if (!error) return { ok: true }; + last = error.message; + } + return { ok: false, message: `the code was refused: ${last}` }; +} + +function waitForNextStep(): Promise { + const intoStep = (Date.now() / 1000) % STEP_SECONDS; + const wait = (STEP_SECONDS - intoStep + 1) * 1000; + return new Promise((resolve) => { + setTimeout((): void => resolve(), wait); + }); +} + +function totp(secret: string): string { + const counter = Math.floor(Date.now() / 1000 / STEP_SECONDS); + const message = Buffer.alloc(8); + message.writeBigUInt64BE(BigInt(counter)); + const digest = createHmac('sha1', base32(secret)).update(message).digest(); + const offset = (digest.at(-1) ?? 0) & 0x0f; + const value = digest.readUInt32BE(offset) & 0x7fffffff; + return String(value % 1_000_000).padStart(6, '0'); +} + +function base32(input: string): Buffer { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + const clean = input.replace(/=+$/, '').toUpperCase(); + let bits = 0; + let value = 0; + const bytes: number[] = []; + for (const char of clean) { + const index = alphabet.indexOf(char); + if (index < 0) continue; + value = (value << 5) | index; + bits += 5; + if (bits >= 8) { + bytes.push((value >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + return Buffer.from(bytes); +}