diff --git a/evals/docs/build-docs-041-send-email-hook/EVAL.ts b/evals/docs/build-docs-041-send-email-hook/EVAL.ts new file mode 100644 index 00000000..90b8c1af --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/EVAL.ts @@ -0,0 +1,75 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { restartStack } from '../lib/local-stack.js'; +import { checkSealed, sealedNotRun } from './access.js'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + checkConfirms, + checkQueued, + checkReset, + checkStackStarts, + probeEmails, +} from './probes.js'; + +const GUIDE_PATH = 'guides/auth/auth-hooks/send-email-hook'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const started = await restartStack(ctx); + const migrations = await applyPendingMigrations(ctx); + const probe = await probeEmails(ctx, started); + const sealed = probe.stack + ? await checkSealed(ctx, probe.stack, probe.requests?.userId ?? '') + : sealedNotRun(probe.message); + + const checks: CheckResult[] = [ + checkStackStarts(started), + checkMigrationsWereApplied(migrations), + checkQueued(probe), + checkConfirms(probe), + checkReset(probe), + sealed, + 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 how Auth emails reach the outbox', + passed: false, + notes: message, + }, + ], + }; + } +}; + +export default scorer; + +function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult { + const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) => + call.pages?.some((page) => page.url.includes(GUIDE_PATH)) + ); + const withContent = calls.filter((call) => call.hasContent); + return { + name: 'the agent read the send email hook 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-041-send-email-hook/PROMPT.md b/evals/docs/build-docs-041-send-email-hook/PROMPT.md new file mode 100644 index 00000000..f79943a7 --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/PROMPT.md @@ -0,0 +1,43 @@ +--- +stage: build +interface: cli +product: + - auth + - database +topic: + - security + - sql +services: + - gotrue + - kong + - postgrest +motivation: >- + Customers who send Auth emails through their own mail service report sign-up + failing with a 500 once it is switched on, and emails whose button does not + work or opens the wrong page. This checks that an agent reading the Send + Email Hook guide hands the sign-up and password reset emails to the team's + own outbox, with buttons that confirm the person and open the page the app + asked for, and that people using the app cannot read the outbox or queue + mail through it. The prompt omits the guide's vocabulary on purpose, so read + README.md before editing it. +--- + +Every email Kestrel Books sends goes through our outbox, and MAIL.md says how it +works. The emails people get when they sign up or forget their password don't. +Supabase sends those itself, and our mail worker never sees them. + +Make the local project put those emails in the outbox instead, finished and +ready to send. The sign-up email needs a button that confirms the person. The +password reset email needs a button that takes them, signed in, to the page the +app asks for so they can pick a new password. src/account.ts is how the app +asks for both. + +The outbox holds links that sign people in, so nobody using the app should be +able to read it or put an email in it. Make sure it all works on the local +project. + +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-hooks/send-email-hook.md diff --git a/evals/docs/build-docs-041-send-email-hook/README.md b/evals/docs/build-docs-041-send-email-hook/README.md new file mode 100644 index 00000000..c3f338ab --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/README.md @@ -0,0 +1,104 @@ +# build-docs-041-send-email-hook + +## What this eval measures + +The subject is [Send Email Hook](https://supabase.com/docs/guides/auth/auth-hooks/send-email-hook), 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 hands Auth's +emails to the team's own mail queue. + +One claim: Auth puts the sign-up and password reset emails in the team's outbox as finished emails, their buttons work, +and only Auth can put mail there. + +`build-docs-021-email-templates` also follows a sign-up button, but there Auth sends the email itself and the agent +changes its wording. Here Auth sends nothing. The agent writes the code that builds the email and its link from what +Auth hands over, and lets Auth's database role write to a table it does not own. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +hook, auth hook, send email hook, Postgres function, database function, HTTP endpoint, Edge Function, webhook, +`config.toml`, `[auth.hook.send_email]`, `pg-functions`, `uri`, `secrets`, `supabase_auth_admin`, grant, revoke, +execute, permission, privilege, role, anon, authenticated, security definer, RLS, row level security, policy, token, +`token_hash`, `email_action_type`, `redirect_to`, `site_url`, verify, confirmation url, SMTP, email provider, template, +payload, event. + +"Outbox", "button" and "the page the app asks for" stay, because that's how the team would say it. + +## The seed carries the contract + +- `local/MAIL.md` and the init migration fix the outbox: `public.outbox` with `to_email`, `subject` and `html`. The + worker sends a row as it is, so the row has to carry a working link. The scorer reads the outbox, so the end state is + observable without a mail provider. +- The outbox has row level security on, no policies, and no grants to `anon` or `authenticated`. Row level security on + the table is a seed choice. It matches what the Table Editor and the Security Advisor default to for a table in + `public`. A hook that writes to such a table needs a rule that lets Auth's database role write to it. Reading is + closed by the seed, so the access check measures what the agent opens up. +- `local/src/account.ts` asks for the reset with `redirectTo` set to `/account/new-password`. That page is where the + reset button has to land. `config.toml` allows `http://127.0.0.1:3000/**` as a redirect. +- `config.toml` is the `supabase init` default with `enable_confirmations = true`, as on a hosted project, so sign-up + sends an email. That setting is pre-solved here. `email_sent` is 100. +- `services` leaves out Mailpit and the edge runtime. With Mailpit off, an email Auth still tries to send itself fails + the request. The queue is in the database, so the edge runtime is not needed, and an HTTP endpoint is not scored. + +## Do not drop the positive controls + +The access check passes for a project that built nothing. The three checks before it make it mean something, because +they need a row that Auth wrote. The sign-up and reset addresses are scoped to the run, so a fixed address in the +project matches nothing. + +## How the checks read the end state + +- The scorer waits for Auth's health endpoint, signs up a new person through the API, and asks for a password reset for + a second, confirmed person. It reads the outbox rows addressed to each and the token hashes Auth stored for each. +- A button is any link in the row's `html` that points at Auth's verify endpoint with a token, or carries the stored + token hash under any query parameter, or has a `token_hash` parameter. Every such link is followed, and the button + works if any one does. A link is followed only on `127.0.0.1` or `localhost`. +- A token hash link is redeemed the way an app route would. The scorer tries the link's `type`, then `email`, then + `recovery`, so a link with no `type` passes. +- The reset button passes when Auth redirects to the `/account/new-password` path with a session. A token hash link + passes when Auth returns a session and the link, or one of its parameters, names that path. A query on the page is + ignored. +- The access check runs as `anon` and as `authenticated` in a transaction it rolls back. It proves four things: + - No table or view in the exposed schemas shows them a row the scorer put in the outbox. + - A direct insert into the outbox adds no row. + - Calling each function in the exposed schemas that takes one `json` or `jsonb` argument, with an event shaped like + Auth's, adds no row. A call that raises any error and leaves the outbox unchanged passes, so a guard on the caller + passes. + - They can run no function in the exposed schemas that runs as its owner and whose body names the outbox. + + A read that fails with an error other than `42501` fails the check as could not tell. + +## What the access check does not catch + +- A function that writes to another table that a job later copies into the outbox. +- A function that runs as its owner and builds the outbox's name at runtime. +- A function that runs as the caller, takes other arguments, and writes through a rule the agent added for app users + that a plain insert does not satisfy. +- Schemas outside the exposed list in `config.toml`. + +## Order of the scorer + +The scorer restarts the stack first, because Auth reads its settings when its container starts. The harness adds the +eval's service excludes to `start`. It then applies pending migrations with `supabase migration up --local`, which +writes to the database, so score once per stack. The access check runs last. + +## The guide has to actually be read + +`the agent read the send email hook guide the prompt referenced` requires a docs call that reached the page with +content. Read `docs.calls` before reading a score. + +## Checks expected to saturate + +The stack check and the migration check. The access check saturates unless the agent writes a function that runs as +its owner and leaves it open to app users. The signal is expected in the sign-up row, which needs Auth's role let into +the outbox, and in the two button checks. + +## What this eval does not score + +- **The other emails.** Only sign-up and password reset are probed. Magic link, invite, email change and the + notifications are not. +- **An HTTP endpoint.** The edge runtime is not started, so signature checks and secret formats are not scored. +- **The email's wording.** Only the address and the links are read. +- **What a failing send does.** The prompt does not say whether a failed queue write should block sign-up. +- **Hosted projects.** The dashboard settings need a hosted project. diff --git a/evals/docs/build-docs-041-send-email-hook/access.ts b/evals/docs/build-docs-041-send-email-hook/access.ts new file mode 100644 index 00000000..a50f72e4 --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/access.ts @@ -0,0 +1,270 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; +import type { Stack } from '../lib/local-stack.js'; +import { sqlLiteral } from './probes.js'; + +export const SEALED = + 'app users cannot reach outbox rows through exposed tables, views, the email event or owner-rights functions naming the outbox'; + +const APP_ROLES = ['anon', 'authenticated'] as const; + +export function sealedNotRun(message: string): CheckResult { + return { name: SEALED, passed: false, notes: `not run: ${message}` }; +} + +export async function checkSealed( + ctx: Pick, + stack: Stack, + userId: string +): Promise { + const run = randomUUID().slice(0, 8); + const marker = `outbox-marker-${run}@example.test`; + const outsider = `outsider-${run}@example.test`; + const subject = userId || randomUUID(); + const result = await execSql( + ctx, + accessScan({ + schemas: exposedSchemas(ctx.hostWorkspace), + marker, + outsider, + userId: subject, + event: hookEvent(subject, outsider, `${stack.apiUrl}/auth/v1`), + }), + { tuplesOnly: true } + ); + if (!result.ok) { + return { + name: SEALED, + passed: false, + notes: `the scan failed: ${result.message}`, + }; + } + const lines = result.stdout.split('\n').map((line) => line.trim()); + const listed = (prefix: string) => + (lines.find((line) => line.startsWith(prefix))?.slice(prefix.length) ?? '') + .split('|') + .filter((entry) => entry.length > 0); + const hits = listed('HITS:'); + const unclear = listed('UNCLEAR:'); + const refused = listed('REFUSED:'); + if (hits.length > 0) { + return { name: SEALED, passed: false, notes: hits.join('; ') }; + } + if (unclear.length > 0) { + return { + name: SEALED, + passed: false, + notes: `could not tell, a read failed for a reason other than missing permission: ${unclear.join('; ')}`, + }; + } + return { + name: SEALED, + passed: true, + notes: [ + 'anon and authenticated read no outbox row, insert none, add none through a function that takes the email event, and can run no owner-rights function that names the outbox', + refused.length > 0 + ? `calls that raised an error and left the outbox unchanged: ${refused.join('; ')}` + : '', + ] + .filter((part) => part.length > 0) + .join('; '), + }; +} + +function exposedSchemas(workspace: string): string[] { + try { + const config = readFileSync( + join(workspace, 'supabase', 'config.toml'), + 'utf8' + ); + const listed = /^schemas\s*=\s*\[([^\]]*)\]/m.exec(config)?.[1] ?? ''; + const schemas = [...listed.matchAll(/"([^"]+)"/g)] + .map((match) => match[1]) + .filter((name): name is string => Boolean(name)); + return schemas.length > 0 + ? [...new Set([...schemas, 'public'])] + : ['public', 'graphql_public']; + } catch { + return ['public', 'graphql_public']; + } +} + +function hookEvent(userId: string, email: string, authUrl: string) { + const now = new Date().toISOString(); + return { + user: { + id: userId, + aud: 'authenticated', + role: 'authenticated', + email, + phone: '', + app_metadata: { provider: 'email', providers: ['email'] }, + user_metadata: { + email, + email_verified: false, + phone_verified: false, + sub: userId, + }, + identities: [], + created_at: now, + updated_at: now, + is_anonymous: false, + }, + email_data: { + token: '482913', + token_hash: randomUUID().replaceAll('-', '').repeat(2).slice(0, 56), + redirect_to: 'http://127.0.0.1:3000', + email_action_type: 'signup', + site_url: authUrl, + token_new: '', + token_hash_new: '', + old_email: '', + old_phone: '', + provider: '', + factor_type: '', + }, + }; +} + +function accessScan(input: { + schemas: string[]; + marker: string; + outsider: string; + userId: string; + event: object; +}): string { + const schemas = `array[${input.schemas.map((schema) => sqlLiteral(schema)).join(', ')}]::text[]`; + const claims = (role: (typeof APP_ROLES)[number]) => + sqlLiteral( + JSON.stringify( + role === 'anon' ? { role } : { sub: input.userId, role, aud: role } + ) + ); + return ` + begin; + insert into public.outbox (to_email, subject, html) + values (${sqlLiteral(input.marker)}, 'Outbox probe', '

Outbox probe

'); + do $$ + declare + schemas text[] := ${schemas}; + app_roles text[] := array[${APP_ROLES.map((role) => sqlLiteral(role)).join(', ')}]; + claims jsonb := jsonb_build_object('anon', ${claims('anon')}::jsonb, 'authenticated', ${claims('authenticated')}::jsonb); + event text := ${sqlLiteral(JSON.stringify(input.event))}; + pattern text := ${sqlLiteral(`%${input.marker}%`)}; + app_role text; + target record; + before bigint; + after bigint; + seen boolean; + hits text[] := '{}'; + unclear text[] := '{}'; + refused text[] := '{}'; + begin + foreach app_role in array app_roles loop + for target in + select n.nspname, p.proname, pg_get_function_identity_arguments(p.oid) as args + from pg_proc p + join pg_namespace n on n.oid = p.pronamespace + where n.nspname = any(schemas) + and p.prosecdef + and p.prosrc ilike '%outbox%' + and has_schema_privilege(app_role, n.oid, 'usage') + and has_function_privilege(app_role, p.oid, 'execute') + and not exists ( + select 1 from pg_depend d + where d.classid = 'pg_proc'::regclass and d.objid = p.oid and d.deptype = 'e' + ) + loop + hits := hits || format('%s can run %I.%I(%s), which runs as its owner and names the outbox', app_role, target.nspname, target.proname, target.args); + end loop; + + for target in + select n.nspname, p.proname, format_type(p.proargtypes[0], null) as argtype + from pg_proc p + join pg_namespace n on n.oid = p.pronamespace + where n.nspname = any(schemas) + and p.prokind = 'f' + and p.pronargs = 1 + and p.proargtypes[0] in ('jsonb'::regtype, 'json'::regtype) + and not exists ( + select 1 from pg_depend d + where d.classid = 'pg_proc'::regclass and d.objid = p.oid and d.deptype = 'e' + ) + loop + select count(*) into before from public.outbox; + begin + execute format('set local role %I', app_role); + perform set_config('request.jwt.claims', (claims ->> app_role), true); + execute format('select %I.%I($1::%s)', target.nspname, target.proname, target.argtype) using event; + execute 'reset role'; + exception when others then + if sqlstate <> '42501' then + refused := refused || format('%s calling %I.%I: %s %s', app_role, target.nspname, target.proname, sqlstate, left(sqlerrm, 120)); + end if; + end; + select count(*) into after from public.outbox; + if after > before then + hits := hits || format('%s gets an email into the outbox by calling %I.%I', app_role, target.nspname, target.proname); + end if; + end loop; + + for target in + select n.nspname, c.relname + from pg_class c + join pg_namespace n on n.oid = c.relnamespace + where c.relkind in ('r', 'p', 'v', 'm', 'f') + and n.nspname = any(schemas) + and not exists ( + select 1 from pg_depend d + where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e' + ) + loop + seen := false; + begin + execute format('set local role %I', app_role); + perform set_config('request.jwt.claims', (claims ->> app_role), true); + execute format('select exists (select 1 from %I.%I t where t::text like %L)', target.nspname, target.relname, pattern) + into seen; + execute 'reset role'; + exception when others then + seen := false; + if sqlstate <> '42501' then + unclear := unclear || format('%s reading %I.%I: %s %s', app_role, target.nspname, target.relname, sqlstate, left(sqlerrm, 120)); + end if; + end; + if seen then + hits := hits || format('%s reads outbox rows from %I.%I', app_role, target.nspname, target.relname); + end if; + end loop; + + select count(*) into before from public.outbox; + begin + execute format('set local role %I', app_role); + perform set_config('request.jwt.claims', (claims ->> app_role), true); + insert into public.outbox (to_email, subject, html) + values (${sqlLiteral(input.outsider)}, 'Outbox probe', '

Outbox probe

'); + execute 'reset role'; + exception when others then + if sqlstate <> '42501' then + refused := refused || format('%s inserting into public.outbox: %s %s', app_role, sqlstate, left(sqlerrm, 120)); + end if; + end; + select count(*) into after from public.outbox; + if after > before then + hits := hits || format('%s inserts into public.outbox', app_role); + end if; + end loop; + + perform set_config('eval.hits', array_to_string(hits, '|'), true); + perform set_config('eval.unclear', array_to_string(unclear, '|'), true); + perform set_config('eval.refused', array_to_string(refused, '|'), true); + end $$; + select 'HITS:' || current_setting('eval.hits', true); + select 'UNCLEAR:' || current_setting('eval.unclear', true); + select 'REFUSED:' || current_setting('eval.refused', true); + rollback; + `; +} diff --git a/evals/docs/build-docs-041-send-email-hook/local/MAIL.md b/evals/docs/build-docs-041-send-email-hook/local/MAIL.md new file mode 100644 index 00000000..d9aee5ab --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/local/MAIL.md @@ -0,0 +1,16 @@ +# Outgoing mail + +Every email Kestrel Books sends goes through the outbox, the `public.outbox` +table. The mail worker picks up each row where `sent_at` is empty, sends it, and +fills in `sent_at`. + +The worker sends exactly what the row says: + +- `to_email` is the address it goes to. +- `subject` is the subject line. +- `html` is the whole body of the email. + +The worker knows nothing about accounts or why an email exists, so a row has to +be the finished email, buttons and all. + +The worker connects to the database as `postgres`. diff --git a/evals/docs/build-docs-041-send-email-hook/local/src/account.ts b/evals/docs/build-docs-041-send-email-hook/local/src/account.ts new file mode 100644 index 00000000..a23ba8a9 --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/local/src/account.ts @@ -0,0 +1,11 @@ +import { supabase } from './supabase'; + +export async function signUp(email: string, password: string) { + return supabase.auth.signUp({ email, password }); +} + +export async function forgotPassword(email: string) { + return supabase.auth.resetPasswordForEmail(email, { + redirectTo: 'http://127.0.0.1:3000/account/new-password', + }); +} diff --git a/evals/docs/build-docs-041-send-email-hook/local/src/supabase.ts b/evals/docs/build-docs-041-send-email-hook/local/src/supabase.ts new file mode 100644 index 00000000..fe7f20fd --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/local/src/supabase.ts @@ -0,0 +1,6 @@ +import { createClient } from '@supabase/supabase-js'; + +export const supabase = createClient( + import.meta.env.VITE_SUPABASE_URL, + import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY +); diff --git a/evals/docs/build-docs-041-send-email-hook/local/supabase/config.toml b/evals/docs/build-docs-041-send-email-hook/local/supabase/config.toml new file mode 100644 index 00000000..49b951ab --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-send-email-hook" + +[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 = ["http://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 = 100 +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 = true +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-041-send-email-hook/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-041-send-email-hook/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..837613a0 --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,12 @@ +create table public.outbox ( + id bigint generated always as identity primary key, + to_email text not null, + subject text not null, + html text not null, + created_at timestamptz not null default now(), + sent_at timestamptz +); + +alter table public.outbox enable row level security; + +revoke all on table public.outbox from anon, authenticated; diff --git a/evals/docs/build-docs-041-send-email-hook/migrations.ts b/evals/docs/build-docs-041-send-email-hook/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/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-041-send-email-hook/probes.ts b/evals/docs/build-docs-041-send-email-hook/probes.ts new file mode 100644 index 00000000..14cd0dcd --- /dev/null +++ b/evals/docs/build-docs-041-send-email-hook/probes.ts @@ -0,0 +1,468 @@ +import { randomUUID } from 'node:crypto'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; +import { + messageOf, + readStack, + runScript, + type Stack, + type Step, +} from '../lib/local-stack.js'; + +type Ctx = Pick; + +export const CHECK = { + starts: 'the local stack starts with the project settings', + queued: 'signing up puts the sign-up email in the outbox', + confirms: "the sign-up email's button confirms the person", + reset: + "the password reset email's button opens the new-password page signed in", +} as const; + +export const NEW_PASSWORD_PAGE = 'http://127.0.0.1:3000/account/new-password'; +const LOCAL_HOSTS = ['127.0.0.1', 'localhost']; + +type Mail = { to_email: string; subject: string; html: string }; + +type Link = { kind: 'verify link' | 'token hash'; href: string; hash: string }; + +type Followed = Link & { + status: number; + location: string; + session: boolean; + error: string; +}; + +type Requests = { + signUpStatus: number; + signUpError: string; + userId: string; + resetStatus: number; + resetError: string; +}; + +export type Probe = Step & { + stack: Stack | null; + signUpEmail: string; + resetEmail: string; + requests: Requests | null; + signUpMails: Mail[]; + resetMails: Mail[]; + outboxError: string; + signUpLinks: Followed[]; + resetLinks: Followed[]; + confirmed: boolean | null; +}; + +const REQUESTS = ` +const api = process.env.P_API; +const client = process.env.P_CLIENT; +const admin = process.env.P_ADMIN; +const password = 'Kestrel-' + process.env.P_RUN + '-9'; +const asClient = { apikey: client, 'Content-Type': 'application/json' }; +const asAdmin = { apikey: admin, Authorization: 'Bearer ' + admin, 'Content-Type': 'application/json' }; +const describe = (body) => String(body.msg || body.message || body.error_description || body.error || JSON.stringify(body)).slice(0, 200); +const healthy = () => fetch(api + '/auth/v1/health', { headers: { apikey: client } }).then((res) => res.ok).catch(() => false); +const until = Date.now() + 60000; +while (Date.now() < until && !(await healthy())) { + await new Promise((resolve) => setTimeout(() => resolve(), 1000)); +} +const out = { signUpStatus: 0, signUpError: '', userId: '', resetStatus: 0, resetError: '' }; +const signUp = await fetch(api + '/auth/v1/signup', { + method: 'POST', + headers: asClient, + body: JSON.stringify({ email: process.env.P_SIGNUP, password }), +}); +const signedUp = await signUp.json().catch(() => ({})); +out.signUpStatus = signUp.status; +out.userId = signedUp.id || (signedUp.user && signedUp.user.id) || ''; +if (!signUp.ok) out.signUpError = describe(signedUp); +const made = await fetch(api + '/auth/v1/admin/users', { + method: 'POST', + headers: asAdmin, + body: JSON.stringify({ email: process.env.P_RESET, password, email_confirm: true }), +}); +if (made.ok) { + const reset = await fetch(api + '/auth/v1/recover?redirect_to=' + encodeURIComponent(process.env.P_PAGE), { + method: 'POST', + headers: asClient, + body: JSON.stringify({ email: process.env.P_RESET }), + }); + out.resetStatus = reset.status; + if (!reset.ok) out.resetError = describe(await reset.json().catch(() => ({}))); +} else { + out.resetError = 'the scorer could not create the person: ' + describe(await made.json().catch(() => ({}))); +} +console.log(JSON.stringify(out)); +`; + +const FOLLOW = ` +const api = process.env.P_API; +const client = process.env.P_CLIENT; +const out = { status: 0, location: '', session: false, error: '' }; +try { + if (process.env.P_KIND === 'verify link') { + const res = await fetch(process.env.P_HREF, { redirect: 'manual' }); + out.status = res.status; + out.location = res.headers.get('location') || ''; + } else { + const types = [...new Set([process.env.P_TYPE, 'email', 'recovery'].filter((type) => type))]; + for (const type of types) { + const res = await fetch(api + '/auth/v1/verify', { + method: 'POST', + headers: { apikey: client, 'Content-Type': 'application/json' }, + body: JSON.stringify({ type, token_hash: process.env.P_HASH }), + }); + out.status = res.status; + const body = await res.json().catch(() => ({})); + if (typeof body.access_token === 'string') { + out.session = true; + break; + } + } + } +} catch (error) { + out.error = String(error && error.cause ? error.cause.message || error.cause : error).slice(0, 200); +} +console.log(JSON.stringify(out)); +`; + +export async function probeEmails(ctx: Ctx, started: Step): Promise { + const run = randomUUID().slice(0, 8); + const notRun: Probe = { + ok: false, + message: '', + stack: null, + signUpEmail: `reader-${run}@example.test`, + resetEmail: `forgot-${run}@example.test`, + requests: null, + signUpMails: [], + resetMails: [], + outboxError: '', + signUpLinks: [], + resetLinks: [], + confirmed: null, + }; + if (!started.ok) return { ...notRun, message: started.message }; + try { + const stack = await readStack(ctx); + const requests = (await runScript(ctx, REQUESTS, { + P_API: stack.apiUrl, + P_CLIENT: stack.clientKey, + P_ADMIN: stack.adminKey, + P_RUN: run, + P_SIGNUP: notRun.signUpEmail, + P_RESET: notRun.resetEmail, + P_PAGE: NEW_PASSWORD_PAGE, + })) as Requests; + const signUpMails = await readOutbox(ctx, notRun.signUpEmail); + const resetMails = await readOutbox(ctx, notRun.resetEmail); + const signUpHashes = await tokenHashes(ctx, notRun.signUpEmail); + const resetHashes = await tokenHashes(ctx, notRun.resetEmail); + const signUpLinks = await followEvery( + ctx, + stack, + linksIn(mailsOf(signUpMails), signUpHashes), + () => false + ); + const resetLinks = await followEvery( + ctx, + stack, + linksIn(mailsOf(resetMails), resetHashes), + (followed) => resetProblem(followed) === undefined + ); + return { + ...notRun, + ok: true, + stack, + requests, + signUpMails: mailsOf(signUpMails), + resetMails: mailsOf(resetMails), + outboxError: errorOf(signUpMails) || errorOf(resetMails), + signUpLinks, + resetLinks, + confirmed: await isConfirmed(ctx, notRun.signUpEmail), + }; + } catch (error) { + return { ...notRun, message: messageOf(error) }; + } +} + +type OutboxRead = Mail[] | { error: string }; + +function mailsOf(read: OutboxRead): Mail[] { + return 'error' in read ? [] : read; +} + +function errorOf(read: OutboxRead): string { + return 'error' in read ? read.error : ''; +} + +async function readOutbox(ctx: Ctx, address: string): Promise { + try { + const { rows } = await ctx.query( + `select to_email, subject, html from public.outbox where to_email ilike ${sqlLiteral(`%${address}%`)} order by id` + ); + return rows.map((row) => ({ + to_email: String(row.to_email ?? ''), + subject: String(row.subject ?? ''), + html: String(row.html ?? ''), + })); + } catch (error) { + return { error: messageOf(error) }; + } +} + +async function tokenHashes(ctx: Ctx, address: string): Promise { + const email = sqlLiteral(address); + try { + const { rows } = await ctx.query( + `select token_hash as hash from auth.one_time_tokens where relates_to = ${email} + union + select confirmation_token from auth.users where email = ${email} + union + select recovery_token from auth.users where email = ${email}` + ); + return rows + .map((row) => String(row.hash ?? '').replace(/^pkce_/, '')) + .filter((hash) => hash.length >= 16); + } catch { + return []; + } +} + +function linksIn(mails: Mail[], hashes: string[]): Link[] { + const hrefs = mails.flatMap((mail) => + [ + ...mail.html.matchAll(/href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+))/gi), + ].map((match) => decode(match[1] ?? match[2] ?? match[3] ?? '').trim()) + ); + return [...new Set(hrefs)] + .filter((href) => URL.canParse(href)) + .flatMap((href): Link[] => { + const url = new URL(href); + const token = url.searchParams.get('token'); + if (url.pathname.endsWith('/verify') && token) { + return [{ kind: 'verify link', href, hash: token }]; + } + const values = [...url.searchParams.values()].map((value) => + value.replace(/^pkce_/, '') + ); + const hash = + values.find((value) => hashes.includes(value)) ?? + url.searchParams.get('token_hash'); + return hash ? [{ kind: 'token hash', href, hash }] : []; + }); +} + +function decode(value: string): string { + return value + .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code))) + .replace(/&#x([0-9a-f]+);/gi, (_, code) => + String.fromCharCode(Number.parseInt(code, 16)) + ) + .replace(/&/g, '&'); +} + +async function followEvery( + ctx: Ctx, + stack: Stack, + links: Link[], + enough: (followed: Followed) => boolean +): Promise { + const followed: Followed[] = []; + for (const link of links) { + const result = await follow(ctx, stack, link); + followed.push(result); + if (enough(result)) break; + } + return followed; +} + +async function follow(ctx: Ctx, stack: Stack, link: Link): Promise { + const host = new URL(link.href).hostname; + if (!LOCAL_HOSTS.includes(host)) { + return unfollowed( + link, + `the link points at ${host}, which is not the local project` + ); + } + try { + const result = (await runScript(ctx, FOLLOW, { + P_API: stack.apiUrl, + P_CLIENT: stack.clientKey, + P_HREF: link.href, + P_KIND: link.kind, + P_HASH: link.hash, + P_TYPE: new URL(link.href).searchParams.get('type') ?? '', + })) as Omit; + return { ...link, ...result }; + } catch (error) { + return unfollowed(link, messageOf(error)); + } +} + +function unfollowed(link: Link, error: string): Followed { + return { ...link, status: 0, location: '', session: false, error }; +} + +async function isConfirmed(ctx: Ctx, address: string): Promise { + try { + const { rows } = await ctx.query( + `select (email_confirmed_at is not null) as confirmed from auth.users where email = ${sqlLiteral(address)}` + ); + return rows.length > 0 ? Boolean(rows[0]?.confirmed) : null; + } catch { + return null; + } +} + +export function checkStackStarts(started: Step): CheckResult { + return { + name: CHECK.starts, + passed: started.ok, + notes: started.ok ? 'supabase start exited 0' : started.message, + }; +} + +export function checkQueued(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.queued, probe.message); + const requests = probe.requests; + const mail = probe.signUpMails[0]; + if (mail) { + return { + name: CHECK.queued, + passed: true, + notes: `"${mail.subject}" to ${mail.to_email}`, + }; + } + return { + name: CHECK.queued, + passed: false, + notes: [ + 'no outbox row for the new person', + `sign-up returned ${requests?.signUpStatus ?? 0}${requests?.signUpError ? `: ${requests.signUpError}` : ''}`, + probe.outboxError + ? `reading the outbox failed: ${probe.outboxError}` + : '', + ] + .filter((part) => part.length > 0) + .join('; '), + }; +} + +export function checkConfirms(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.confirms, probe.message); + if (probe.signUpMails.length === 0) { + return { + name: CHECK.confirms, + passed: false, + notes: 'no sign-up email in the outbox to read', + }; + } + if (probe.signUpLinks.length === 0) { + return { + name: CHECK.confirms, + passed: false, + notes: noLink(probe.signUpMails), + }; + } + const worked = probe.confirmed === true; + const tried = probe.signUpLinks + .map( + (link) => + `${link.kind} ${clip(link.href)} (${link.error || `status ${link.status}`})` + ) + .join('; '); + return { + name: CHECK.confirms, + passed: worked, + notes: worked + ? `followed every link in the email, the person is confirmed: ${tried}` + : `followed every link in the email, the person is ${probe.confirmed === null ? 'missing' : 'not confirmed'}: ${tried}`, + }; +} + +export function checkReset(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.reset, probe.message); + const requests = probe.requests; + if (probe.resetMails.length === 0) { + return { + name: CHECK.reset, + passed: false, + notes: `no password reset email in the outbox; the request returned ${requests?.resetStatus ?? 0}${requests?.resetError ? `: ${requests.resetError}` : ''}`, + }; + } + if (probe.resetLinks.length === 0) { + return { + name: CHECK.reset, + passed: false, + notes: noLink(probe.resetMails), + }; + } + const working = probe.resetLinks.find( + (link) => resetProblem(link) === undefined + ); + return { + name: CHECK.reset, + passed: working !== undefined, + notes: working + ? `the ${working.kind} ${clip(working.href)} opens ${NEW_PASSWORD_PAGE} signed in` + : probe.resetLinks + .map((link) => resetProblem(link)) + .filter((problem) => problem !== undefined) + .join('; '), + }; +} + +function resetProblem(link: Followed): string | undefined { + if (link.error) return `following ${clip(link.href)} failed: ${link.error}`; + if (link.kind === 'verify link') { + if (!URL.canParse(link.location)) { + return `Auth answered ${link.status} with no redirect for ${clip(link.href)}`; + } + const landed = new URL(link.location); + if (!landed.hash.includes('access_token=')) { + return `the person lands on ${clip(link.location)} without being signed in`; + } + return landsOnPage(landed.href) + ? undefined + : `the person lands signed in on ${pageOf(landed)}, not ${NEW_PASSWORD_PAGE}`; + } + if (!link.session) { + return `Auth refused the token hash in ${clip(link.href)} (status ${link.status})`; + } + const url = new URL(link.href); + return landsOnPage(url.href) || + [...url.searchParams.values()].some((value) => landsOnPage(value)) + ? undefined + : `the link signs the person in but names no way to ${NEW_PASSWORD_PAGE}: ${clip(link.href)}`; +} + +function landsOnPage(candidate: string): boolean { + const page = new URL(NEW_PASSWORD_PAGE); + if (!candidate.startsWith('/') && !URL.canParse(candidate)) return false; + return pageOf(new URL(candidate, page.origin)) === pageOf(page); +} + +function pageOf(url: URL): string { + return `${url.origin}${url.pathname.replace(/\/+$/, '')}`; +} + +function noLink(mails: Mail[]): string { + const preview = mails + .map((mail) => mail.html.replace(/\s+/g, ' ').slice(0, 160)) + .join(' | '); + return `the email has no link to Auth's verify endpoint and no link carrying the token hash: ${preview}`; +} + +function clip(text: string): string { + return text.slice(0, 200); +} + +function blocked(name: string, message: string): CheckResult { + return { name, passed: false, notes: `not run: ${message}` }; +} + +export function sqlLiteral(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +}