diff --git a/evals/docs/build-docs-042-realtime-broadcast/EVAL.ts b/evals/docs/build-docs-042-realtime-broadcast/EVAL.ts new file mode 100644 index 00000000..b96b73f7 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/EVAL.ts @@ -0,0 +1,73 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + checkCannotForge, + checkInstalled, + checkLoads, + checkMemberSees, + checkNeverSees, + probeRooms, +} from './probes.js'; + +const GUIDE_PATH = 'guides/realtime/broadcast'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const migrations = await applyPendingMigrations(ctx); + const outcome = await probeRooms(ctx); + + const checks: CheckResult[] = [ + checkMigrationsWereApplied(migrations), + checkInstalled(outcome), + checkLoads(outcome), + checkMemberSees(outcome, 'mobile'), + checkMemberSees(outcome, 'inbox'), + checkMemberSees(outcome, 'web'), + checkNeverSees(outcome, 'outsider'), + checkNeverSees(outcome, 'visitor'), + checkCannotForge(outcome), + 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 sees new room messages', + 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 Broadcast 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-042-realtime-broadcast/PROMPT.md b/evals/docs/build-docs-042-realtime-broadcast/PROMPT.md new file mode 100644 index 00000000..36924ea9 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/PROMPT.md @@ -0,0 +1,38 @@ +--- +stage: build +interface: cli +product: + - realtime + - database +topic: + - security + - sdk +services: + - gotrue + - kong + - postgrest + - realtime +motivation: >- + A chat room needs each new message pushed to the people in the room, and + only to them. Customers and agents send from the database to a client that + never receives it, or open the room to every signed-in user so that it does. + This checks that an agent reading the Broadcast guide gets a new message to + the room's members as it lands and to nobody outside the room. The prompt + omits the guide's vocabulary on purpose, so read README.md before editing it. +--- + +Burrow is our team chat. Right now people only see new messages in a room when +they reload. I want a new message to show up for everyone in the room the +moment it's saved, whether it came from the web app, the mobile app or the +support inbox. ROOMS.md says where the web app's part goes. + +Rooms are members only. Nobody outside a room should ever see its messages or +be able to slip a message into it, even someone who skips our app and talks to +Supabase directly. Set that up in the local project and make sure it works on +the local stack. + +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/realtime/broadcast.md diff --git a/evals/docs/build-docs-042-realtime-broadcast/README.md b/evals/docs/build-docs-042-realtime-broadcast/README.md new file mode 100644 index 00000000..d6e76570 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/README.md @@ -0,0 +1,94 @@ +# build-docs-042-realtime-broadcast + +## What this eval measures + +The subject is [Broadcast](https://supabase.com/docs/guides/realtime/broadcast), 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 gets a new room message to the right +people. + +One claim: a message saved to a room reaches the room's members live, and nobody outside the room can receive it or slip +one in. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +realtime, broadcast, channel, private, topic, subscribe, websocket, socket, RLS, row level security, policy, +`realtime.messages`, `realtime.topic()`, extension, authorization, trigger, `realtime.send`, `broadcast_changes`, +`setAuth`, JWT, token, publication, Postgres Changes, presence, ack, self, REST, httpSend. + +"Live", "members only" and "talks to Supabase directly" stay, because that is how the team would say it. `public` is +the schema name the seed already shows, so it is not stripped. + +## The seed carries the contract + +- `local/ROOMS.md` fixes `watchRoom(supabase, roomId, onMessage)` in `src/live.js`, and says messages arrive from three + places. Two of them write straight to `public.messages`, so sending from the poster's browser does not reach anyone. +- `public.messages`, `public.room_members` and the helper `public.is_room_member` already keep non-members out of a + room's rows. The eval measures the live path, not the table's access rules. +- `local/package.json` and `local/package-lock.json` pin `@supabase/supabase-js`. + +## Scoring needs the npm registry + +The scorer runs `npm ci` in the workspace so the agent's `src/live.js` can import its dependencies. It installs its own +pinned `@supabase/supabase-js` into a directory outside the workspace, so the clients it builds do not depend on what +the agent did to `package.json`. Both need network access to the npm registry. A failed install fails the eval. Read it +as a lost run, unless the note shows `npm ci` failed on a lockfile the agent changed. + +## Do not drop the positive controls + +The outsider, visitor and forgery checks pass for a project with no live path at all. The three member checks are what +make them mean something. The outsider and visitor checks also fail as could-not-measure when `watchRoom` joined nothing +on the client it was given, because then there is no topic to try directly. The forgery check fails as could-not-measure +in that case too, and when the scorer's own message on its control topic never arrives. + +## How the checks read the end state + +- A member, a poster and a person from another room are created per run, with rooms named for the run. The member + watches through the agent's `watchRoom`. +- Three messages go to the room, each with a run-scoped body: the poster inserts one through the API like the mobile app, + the superuser inserts one with no signed-in user like the support inbox, and the poster calls `postMessage` from + `src/messages.js` like the web app. Each member check needs that body at the callback within 10 seconds. The note + names the route that delivered it, `broadcast` or `postgres_changes`, so a baseline can be read by route. +- The outsider and a visitor with no session watch three ways: through `watchRoom`, and directly on every topic the + member's client joined, once as a members-only join and once as an open one. Any of the three bodies arriving fails + the check. +- The forgery check has the outsider insert a whole row into the room's messages. A refusal counts only when the + superuser then finds no such row. It also copies what the member's client received, swaps in a new body, and sends it + as the outsider on each topic, both joins, over the socket and the HTTP endpoint. An HTTP send is listed as tried only + when the request got a response. A stored row, or either body at the member's callback, fails the check. +- The shape of what the callback gets is not scored. Only that it carries the body. +- Before any of this, the scorer sends a members-only test message from the database to its own control topic, and + listens there with the service role key, which no rule on `realtime.messages` can refuse. If it never arrives, every + probe fails as could-not-measure. Either the stack is not delivering, or the agent's migration broke sending from the + database. The forgery check's control is a message the scorer sends on the same topic. +- The local stack allows open joins unless the project turns them off, as hosted projects do with "Allow public + access". An open join to the room's topic is attempted on purpose. A project that turns public channels off is + accepted: the scorer's own control does not depend on public channels, and a refused open join or send counts as no + leak and no forgery. + +## Order of the scorer + +The scorer applies pending migrations with `supabase migration up --local` first, which writes to the database, so score +once per stack. It installs, then one script runs the probes in order: load, the database test message, setup, watching, +posting, then forging. A failed step marks every later probe as not run with its note. The script stops itself after 200 +seconds, above the sum of its own waits. + +## The guide has to actually be read + +`the agent read the Broadcast 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 migration, install and load checks, and the visitor check. The signal is expected in the member checks and the +outsider check. + +## What this eval does not score + +- **Which mechanism carries the message.** Any route that delivers to members and nobody else passes, including changes + read from the table instead of sent. The member checks name the route. +- **What the callback receives.** Only that it carries the message body. +- **Removing someone from a room.** Access is checked when the room is opened, and the prompt does not ask about leaving. +- **Typing indicators, presence and replay.** The prompt asks only for new messages. +- **Hosted projects.** The "Allow public access" setting and billing are out of reach locally. diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/.gitignore b/evals/docs/build-docs-042-realtime-broadcast/local/.gitignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/ROOMS.md b/evals/docs/build-docs-042-realtime-broadcast/local/ROOMS.md new file mode 100644 index 00000000..4f96be5e --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/ROOMS.md @@ -0,0 +1,32 @@ +# Rooms + +Burrow is a team chat. A room's messages are for the people in that room and nobody else. `room_members` says who is +in which room, and the database already keeps everyone else out of a room's messages. + +## Where messages come from + +New messages land in `public.messages` from three places: + +- The web app, through `postMessage` in `src/messages.js`. +- The mobile app, which inserts into `messages` through the API as the signed-in person. +- The support inbox, a server job that inserts customer replies straight into `messages`. + +## Showing new messages in the web app + +The room screen calls `watchRoom` from `src/live.js` when it opens: + +```js +import { watchRoom } from './live.js' + +const stop = await watchRoom(supabase, roomId, (message) => { + appendToThread(message) +}) +``` + +- `supabase` is the app's client, already signed in as the person looking at the room. +- `roomId` is `rooms.id`. +- The callback gets each new message in that room as a `messages` row: `id`, `room_id`, `author_id`, `body`, + `created_at`. +- `watchRoom` returns, or resolves to, a function that stops watching. + +The room screen closes with `stop()`. diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/package-lock.json b/evals/docs/build-docs-042-realtime-broadcast/local/package-lock.json new file mode 100644 index 00000000..e5505bcb --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/package-lock.json @@ -0,0 +1,120 @@ +{ + "name": "burrow", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "burrow", + "dependencies": { + "@supabase/supabase-js": "2.118.0" + } + }, + "node_modules/@supabase/auth-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.118.0.tgz", + "integrity": "sha512-xWfPXyhS2KDSfAneMtI6p/tBnbdiz/5vaRKXEqUfzfC9WCniKr2Ds5o5G7RIGig0bom4z6wUY9zaV07WDVTfnQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.118.0.tgz", + "integrity": "sha512-4ofletPa/noKAU6KHeqsd3FztGzRPUEJRey1MKY0o+PIHaVePqRPShIXtl37gcVyIWaFM+zNg6r9zh0uUSFOSA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/phoenix": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.5.tgz", + "integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==", + "license": "MIT" + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.118.0.tgz", + "integrity": "sha512-JXy+37KPApHsyotaQACovv/Jy9E22rfiWLRuT+2UjoEAcAIelDFIrsF/FY47Dy19mO7lI0Tq+zDCX8oJ2Ozfiw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.118.0.tgz", + "integrity": "sha512-pzCIEWjqD5/xqEZQerpt+q9rsgYkcrkgCJgf0W2ULqC4fYUeB/p9CFa3t9vn+IVh6dMN9r4ZCE262lZvUC+Bfw==", + "license": "MIT", + "dependencies": { + "@supabase/phoenix": "0.4.5", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.118.0.tgz", + "integrity": "sha512-5MNkKt2Moy7Jud/sPX7/28BwdDxZMCVHGJT00b8op3KRa9LKSjOAYU5IcfGWIstaasAqY8GkbA6oI3IRDgB1YQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.118.0", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.118.0.tgz", + "integrity": "sha512-FxI8UXMVC2UG7IkeiI8fuQZqq2oI3JeSuN8MPIC2RLVaoEAxKS0nqE6kii9Ewpq8f9gNPM6git1Y8f0vN/QLFw==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.118.0", + "@supabase/functions-js": "2.118.0", + "@supabase/postgrest-js": "2.118.0", + "@supabase/realtime-js": "2.118.0", + "@supabase/storage-js": "2.118.0" + }, + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + } + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + } + } +} diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/package.json b/evals/docs/build-docs-042-realtime-broadcast/local/package.json new file mode 100644 index 00000000..a7d19b12 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/package.json @@ -0,0 +1,8 @@ +{ + "name": "burrow", + "private": true, + "type": "module", + "dependencies": { + "@supabase/supabase-js": "2.118.0" + } +} diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/src/messages.js b/evals/docs/build-docs-042-realtime-broadcast/local/src/messages.js new file mode 100644 index 00000000..bb41bcdc --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/src/messages.js @@ -0,0 +1,20 @@ +export async function postMessage(supabase, roomId, body) { + const { data, error } = await supabase + .from('messages') + .insert({ room_id: roomId, body }) + .select('id, room_id, author_id, body, created_at') + .single(); + if (error) throw error; + return data; +} + +export async function recentMessages(supabase, roomId, limit = 50) { + const { data, error } = await supabase + .from('messages') + .select('id, room_id, author_id, body, created_at') + .eq('room_id', roomId) + .order('created_at', { ascending: false }) + .limit(limit); + if (error) throw error; + return data.reverse(); +} diff --git a/evals/docs/build-docs-042-realtime-broadcast/local/supabase/config.toml b/evals/docs/build-docs-042-realtime-broadcast/local/supabase/config.toml new file mode 100644 index 00000000..4a7916b9 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-realtime-broadcast" + +[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-042-realtime-broadcast/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-042-realtime-broadcast/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..4bd6dff5 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,65 @@ +create table rooms ( + id bigint primary key generated always as identity, + name text not null +); + +create table room_members ( + room_id bigint not null references rooms on delete cascade, + user_id uuid not null references auth.users on delete cascade, + primary key (room_id, user_id) +); + +create table messages ( + id bigint primary key generated always as identity, + room_id bigint not null references rooms on delete cascade, + author_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 index messages_room_id_created_at_idx on messages (room_id, created_at); + +create function public.is_room_member(room bigint) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 + from public.room_members + where room_id = room + and user_id = (select auth.uid()) + ); +$$; + +revoke execute on function public.is_room_member(bigint) from public, anon; +grant execute on function public.is_room_member(bigint) to authenticated; + +alter table rooms enable row level security; +alter table room_members enable row level security; +alter table messages enable row level security; + +grant select on table rooms to authenticated; +grant select on table room_members to authenticated; +grant select, insert on table messages to authenticated; + +create policy "members see their rooms" +on rooms for select to authenticated +using ((select public.is_room_member(id))); + +create policy "members see who else is in their rooms" +on room_members for select to authenticated +using ((select public.is_room_member(room_id))); + +create policy "members read their rooms" +on messages for select to authenticated +using ((select public.is_room_member(room_id))); + +create policy "members post in their rooms as themselves" +on messages for insert to authenticated +with check ( + (select auth.uid()) = author_id + and (select public.is_room_member(room_id)) +); diff --git a/evals/docs/build-docs-042-realtime-broadcast/migrations.ts b/evals/docs/build-docs-042-realtime-broadcast/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/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-042-realtime-broadcast/probe-script.ts b/evals/docs/build-docs-042-realtime-broadcast/probe-script.ts new file mode 100644 index 00000000..7a0b28d7 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/probe-script.ts @@ -0,0 +1,337 @@ +export const STAGES = [ + 'load', + 'ready', + 'setup', + 'watch', + 'post', + 'forge', + 'done', +] as const; + +export type Stage = (typeof STAGES)[number]; + +export const SOURCES = ['mobile', 'inbox', 'web'] as const; + +export type Source = (typeof SOURCES)[number]; + +export const DELIVERY_WINDOW_SECONDS = 10; + +export const PROBE_TIMEOUT_SECONDS = 200; + +const FORGED_ROW_ID = 2147483000; + +export const PROBE_SCRIPT = ` +import { execFileSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +import { createClient } from '@supabase/supabase-js'; + +const env = process.env; +const runId = env.EVAL_RUN_ID; +const workspace = env.EVAL_WORKSPACE; +const windowMs = ${DELIVERY_WINDOW_SECONDS * 1000}; +const markers = { + mobile: 'mobile-' + runId, + inbox: 'inbox-' + runId, + web: 'web-' + runId, +}; +const forgedBroadcast = 'forged-' + runId; +const forgedRow = 'forged-row-' + runId; +const controlTopic = 'eval-control-' + runId; +const options = { auth: { persistSession: false, autoRefreshToken: false } }; +const sleep = (ms) => new Promise((resolve) => setTimeout(() => resolve(), ms)); +const text = (value) => { + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +}; +const short = (error) => String(error?.message ?? error).slice(0, 200); +const result = { + stage: 'load', + note: '', + topics: [], + joins: { outsider: [], visitor: [] }, + delivered: {}, + leaks: { outsider: [], visitor: [] }, + controlDelivered: false, + forgery: { tried: [], rowStored: false, rowNote: '', seen: [] }, +}; +const finish = () => { + console.log(JSON.stringify(result)); + process.exit(0); +}; +setTimeout(() => { + result.note = 'the probe ran out of time'; + finish(); +}, ${PROBE_TIMEOUT_SECONDS * 1000}); + +function psql(sql) { + return execFileSync('psql', [env.EVAL_DB_URL, '-q', '-t', '-A', '-v', 'ON_ERROR_STOP=1', '-c', sql], { + stdio: 'pipe', + }).toString(); +} +const literal = (value) => "'" + String(value).replaceAll("'", "''") + "'"; + +let live; +try { + live = await import(pathToFileURL(workspace + '/src/live.js').href); +} catch (error) { + result.note = 'src/live.js did not load: ' + short(error); + finish(); +} +if (typeof live.watchRoom !== 'function') { + result.note = 'src/live.js exports no watchRoom function'; + finish(); +} + +result.stage = 'ready'; +const admin = createClient(env.EVAL_API_URL, env.EVAL_ADMIN_KEY, options); +const visitorClient = () => createClient(env.EVAL_API_URL, env.EVAL_CLIENT_KEY, options); +const tokenClient = (token) => + createClient(env.EVAL_API_URL, env.EVAL_CLIENT_KEY, { ...options, accessToken: async () => token }); + +async function settle(clients) { + const end = Date.now() + 10000; + while (Date.now() < end) { + const joining = clients.some((c) => c.getChannels().some((ch) => ch.state === 'joining')); + if (!joining) break; + await sleep(200); + } + await sleep(500); +} + +const serviceClient = () => createClient(env.EVAL_API_URL, env.EVAL_ADMIN_KEY, options); +const controller = serviceClient(); +const controlMessages = []; +controller + .channel(controlTopic, { config: { private: true } }) + .on('broadcast', { event: '*' }, (message) => controlMessages.push(text(message))) + .subscribe(); +await settle([controller]); +const readyEnd = Date.now() + 40000; +let readyError = ''; +while (controlMessages.length === 0 && Date.now() < readyEnd) { + try { + psql("select realtime.send(jsonb_build_object('ping', true), 'ping', " + literal(controlTopic) + ', true);'); + } catch (error) { + readyError = short(error.stderr ? error.stderr.toString() : error); + } + for (let i = 0; i < 10 && controlMessages.length === 0; i++) await sleep(150); +} +if (controlMessages.length === 0) { + result.note = 'a test message sent from the database never arrived' + (readyError ? ': ' + readyError : ''); + finish(); +} + +result.stage = 'setup'; +async function person(tag) { + const email = tag + '-' + runId + '@example.test'; + const password = 'Burrow-' + runId + '-9'; + const made = await admin.auth.admin.createUser({ email, password, email_confirm: true }); + if (made.error) throw new Error('could not create the ' + tag + ': ' + short(made.error)); + const client = visitorClient(); + const { data, error } = await client.auth.signInWithPassword({ email, password }); + if (error || !data.session) throw new Error('the ' + tag + ' could not sign in: ' + short(error)); + return { id: made.data.user.id, client, token: data.session.access_token }; +} + +let roomId; +let member; +let poster; +let outsider; +try { + const rooms = await admin + .from('rooms') + .insert([{ name: 'eval-' + runId + '-a' }, { name: 'eval-' + runId + '-b' }]) + .select('id, name'); + if (rooms.error) throw new Error('could not add rooms: ' + short(rooms.error)); + roomId = rooms.data.find((room) => room.name.endsWith('-a')).id; + const otherRoomId = rooms.data.find((room) => room.name.endsWith('-b')).id; + member = await person('member'); + poster = await person('poster'); + outsider = await person('outsider'); + const joined = await admin.from('room_members').insert([ + { room_id: roomId, user_id: member.id }, + { room_id: roomId, user_id: poster.id }, + { room_id: otherRoomId, user_id: outsider.id }, + ]); + if (joined.error) throw new Error('could not add room members: ' + short(joined.error)); +} catch (error) { + result.note = short(error); + finish(); +} + +result.stage = 'watch'; +const describe = (client, how) => + client.getChannels().map((ch) => how + ' ' + ch.subTopic + (ch.private ? ' private ' : ' public ') + ch.state); +const seen = { member: [], outsider: [], visitor: [] }; +const watchers = { member: member.client, outsider: outsider.client, visitor: visitorClient() }; +const watchErrors = {}; +await Promise.all( + Object.entries(watchers).map(async ([who, client]) => { + try { + await Promise.race([ + live.watchRoom(client, roomId, (message) => seen[who].push(text(message))), + sleep(10000).then(() => { + throw new Error('watchRoom did not resolve within 10 seconds'); + }), + ]); + } catch (error) { + watchErrors[who] = 'watchRoom threw: ' + short(error); + } + }) +); +await settle(Object.values(watchers)); + +const memberChannels = member.client.getChannels(); +result.topics = memberChannels.map((ch) => ch.subTopic + (ch.private ? ' private' : ' public')); +const tapped = []; +for (const ch of memberChannels) { + ch.on('broadcast', { event: '*' }, (message) => tapped.push(message)); +} +const memberListensToChanges = memberChannels.some((ch) => (ch.bindings?.postgres_changes ?? []).length > 0); + +const listeners = []; +for (const ch of memberChannels) { + for (const isPrivate of [true, false]) { + for (const [who, client] of [ + ['outsider', tokenClient(outsider.token)], + ['visitor', visitorClient()], + ]) { + client + .channel(ch.subTopic, { config: { private: isPrivate } }) + .on('broadcast', { event: '*' }, (message) => seen[who].push(text(message))) + .subscribe(); + listeners.push([who, client]); + } + } +} +await settle(listeners.map(([, client]) => client)); +for (const who of ['outsider', 'visitor']) { + if (watchErrors[who]) result.joins[who].push(watchErrors[who]); + result.joins[who].push(...describe(watchers[who], 'watchRoom')); +} +for (const [who, client] of listeners) result.joins[who].push(...describe(client, 'direct')); + +result.stage = 'post'; +const routeOf = (marker) => { + if (tapped.some((message) => text(message).includes(marker))) return 'broadcast'; + if (memberListensToChanges) return 'postgres_changes'; + return 'another route'; +}; +async function waitFor(marker) { + const end = Date.now() + windowMs; + while (Date.now() < end && !seen.member.some((message) => message.includes(marker))) await sleep(200); +} +const senders = { + mobile: async () => { + const { error } = await poster.client.from('messages').insert({ room_id: roomId, body: markers.mobile }); + if (error) throw new Error(short(error)); + }, + inbox: async () => { + psql( + 'insert into public.messages (room_id, author_id, body) values (' + + roomId + ', ' + literal(poster.id) + ', ' + literal(markers.inbox) + ');' + ); + }, + web: async () => { + const messages = await import(pathToFileURL(workspace + '/src/messages.js').href); + await messages.postMessage(poster.client, roomId, markers.web); + }, +}; +await sleep(4000); +for (const [source, send] of Object.entries(senders)) { + let error = ''; + try { + await send(); + } catch (failure) { + error = short(failure.stderr ? failure.stderr.toString() : failure); + } + await waitFor(markers[source]); + const got = seen.member.find((message) => message.includes(markers[source])); + result.delivered[source] = { + error, + seen: got ? got.slice(0, 300) : '', + route: got ? routeOf(markers[source]) : '', + }; +} +await sleep(2000); +for (const who of ['outsider', 'visitor']) { + result.leaks[who] = seen[who] + .filter((message) => Object.values(markers).some((marker) => message.includes(marker))) + .map((message) => message.slice(0, 300)); +} + +result.stage = 'forge'; +const tried = result.forgery.tried; +const inserted = await outsider.client + .from('messages') + .insert({ room_id: roomId, author_id: outsider.id, body: forgedRow }); +try { + const stored = Number(psql('select count(*) from public.messages where body = ' + literal(forgedRow) + ';').trim()); + result.forgery.rowStored = stored > 0; + result.forgery.rowNote = stored > 0 + ? 'the outsider stored a message in the room' + : 'the outsider insert was refused: ' + (inserted.error ? inserted.error.code + ' ' + inserted.error.message : 'no error, but no row'); + tried.push('table insert: ' + (stored > 0 ? 'stored' : 'refused')); +} catch (error) { + result.forgery.rowNote = 'could not count the forged row: ' + short(error); +} + +const templates = tapped + .filter((message) => Object.values(markers).some((marker) => text(message).includes(marker))) + .slice(0, 1) + .map((message) => { + let payload = text(message.payload); + for (const marker of Object.values(markers)) payload = payload.replaceAll(marker, forgedBroadcast); + return { event: message.event, payload: JSON.parse(payload) }; + }); +if (templates.length === 0) { + const row = { id: ${FORGED_ROW_ID}, room_id: roomId, author_id: poster.id, body: forgedBroadcast, created_at: new Date().toISOString() }; + for (const event of ['message', 'new_message', 'INSERT']) { + templates.push({ event, payload: row }); + templates.push({ event, payload: { record: row } }); + } +} + +const controlSender = serviceClient(); +const controlChannel = controlSender.channel(controlTopic, { config: { private: true } }); +controlChannel.subscribe(); +const forgers = []; +for (const ch of memberChannels) { + for (const isPrivate of [true, false]) { + const client = tokenClient(outsider.token); + forgers.push({ client, channel: client.channel(ch.subTopic, { config: { private: isPrivate } }) }); + } +} +for (const forger of forgers) forger.channel.subscribe(); +await settle([controlSender, ...forgers.map((forger) => forger.client)]); +await controlChannel.send({ type: 'broadcast', event: 'ping', payload: { forgedBroadcast } }); +const forgeEnd = Date.now() + 15000; +for (const { channel } of forgers) { + const label = channel.subTopic + (channel.private ? ' private' : ' public'); + tried.push(label + ' join ' + channel.state); + for (const template of templates) { + if (Date.now() > forgeEnd) break; + if (channel.state === 'joined') { + const sent = await channel.send({ type: 'broadcast', event: template.event, payload: template.payload }); + tried.push(label + ' socket ' + template.event + ': ' + sent); + } + try { + await channel.httpSend(template.event, template.payload, { timeout: 3000 }); + tried.push(label + ' http ' + template.event + ': accepted'); + } catch (error) { + const message = short(error); + if (!/fetch failed|abort|timed? ?out/i.test(message)) tried.push(label + ' http ' + template.event + ': ' + message); + } + } +} +await sleep(4000); +result.controlDelivered = controlMessages.some((message) => message.includes(forgedBroadcast)); +result.forgery.seen = seen.member + .filter((message) => message.includes(forgedBroadcast) || message.includes(forgedRow)) + .map((message) => message.slice(0, 300)); +result.stage = 'done'; +finish(); +`; diff --git a/evals/docs/build-docs-042-realtime-broadcast/probes.ts b/evals/docs/build-docs-042-realtime-broadcast/probes.ts new file mode 100644 index 00000000..98e34ba4 --- /dev/null +++ b/evals/docs/build-docs-042-realtime-broadcast/probes.ts @@ -0,0 +1,258 @@ +import { randomUUID } from 'node:crypto'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; +import { errorLine, messageOf, readStack } from '../lib/local-stack.js'; +import { + DELIVERY_WINDOW_SECONDS, + PROBE_SCRIPT, + PROBE_TIMEOUT_SECONDS, + STAGES, + type Source, + type Stage, +} from './probe-script.js'; + +const PROBE_CLIENT_VERSION = '2.118.0'; + +export const CHECK = { + installed: "the scorer installed the app's locked dependencies", + loads: 'the room screen can load watchRoom from src/live.js', + mobile: + 'a room member sees a message from the mobile app as soon as it is saved', + inbox: + 'a room member sees a message from the support inbox as soon as it is saved', + web: 'a room member sees a message posted from the web app as soon as it is saved', + outsider: + "a signed-in person from another room never sees the room's messages", + visitor: "a visitor who is not signed in never sees the room's messages", + forged: 'a person from another room cannot slip a message into the room', +} as const; + +type Exec = Pick; +type Who = 'member' | 'outsider' | 'visitor'; +type Bystander = Exclude; + +type Delivery = { error: string; seen: string; route: string }; + +export type Probe = { + stage: Stage; + note: string; + topics: string[]; + joins: Record; + delivered: Partial>; + leaks: Record; + controlDelivered: boolean; + forgery: { + tried: string[]; + rowStored: boolean; + rowNote: string; + seen: string[]; + }; +}; + +export type Outcome = + | { probe: Probe } + | { failure: string; installed: boolean }; + +export async function probeRooms(ctx: Exec): Promise { + const runId = randomUUID().slice(0, 8); + const probeDir = `/tmp/broadcast-eval-${runId}`; + const installed = await install(ctx, probeDir); + if (installed) return { installed: false, failure: installed }; + try { + const stack = await readStack(ctx); + const probe = await runProbe(ctx, probeDir, { + EVAL_API_URL: stack.apiUrl, + EVAL_ADMIN_KEY: stack.adminKey, + EVAL_CLIENT_KEY: stack.clientKey, + EVAL_DB_URL: await readDbUrl(ctx), + EVAL_RUN_ID: runId, + }); + return { probe }; + } catch (error) { + return { installed: true, failure: messageOf(error) }; + } +} + +async function install(ctx: Exec, probeDir: string): Promise { + const app = await ctx.exec('npm ci --no-audit --no-fund --silent', { + timeoutMs: 300_000, + }); + if (app.exitCode !== 0) { + return `npm ci in the workspace failed: ${errorLine(`${app.stderr ?? ''}\n${app.stdout ?? ''}`)}`; + } + const own = await ctx.exec( + `mkdir -p ${probeDir} && cd ${probeDir} && npm init -y >/dev/null && npm install --no-audit --no-fund --silent @supabase/supabase-js@${PROBE_CLIENT_VERSION}`, + { timeoutMs: 300_000 } + ); + if (own.exitCode !== 0) { + return `installing the scorer's own client failed: ${errorLine(`${own.stderr ?? ''}\n${own.stdout ?? ''}`)}`; + } + return ''; +} + +async function readDbUrl(ctx: Exec): Promise { + const result = await ctx.exec('supabase status -o json 2>/dev/null'); + const out = result.stdout ?? ''; + const parsed = JSON.parse( + out.slice(out.indexOf('{'), out.lastIndexOf('}') + 1) + ); + if (!parsed.DB_URL) throw new Error('supabase status reported no DB_URL'); + return parsed.DB_URL; +} + +async function runProbe( + ctx: Exec, + probeDir: string, + env: Record +): Promise { + const vars = Object.entries(env) + .map(([name, value]) => `${name}='${value}'`) + .join(' '); + const encoded = Buffer.from(PROBE_SCRIPT, 'utf8').toString('base64'); + const result = await ctx.exec( + `echo ${encoded} | base64 -d > ${probeDir}/probe.mjs && ${vars} EVAL_WORKSPACE="$PWD" node ${probeDir}/probe.mjs`, + { timeoutMs: (PROBE_TIMEOUT_SECONDS + 40) * 1000 } + ); + const line = (result.stdout ?? '').trim().split('\n').at(-1) ?? ''; + if (line.startsWith('{')) return JSON.parse(line) as Probe; + throw new Error(errorLine(`${result.stderr}\n${result.stdout}`)); +} + +function reached(outcome: Outcome, stage: Stage): outcome is { probe: Probe } { + return ( + 'probe' in outcome && + STAGES.indexOf(outcome.probe.stage) > STAGES.indexOf(stage) + ); +} + +function notRun(outcome: Outcome, name: string): CheckResult { + const reason = + 'failure' in outcome + ? outcome.failure + : outcome.probe.note || `the probe stopped at ${outcome.probe.stage}`; + return { name, passed: false, notes: `not run: ${reason}` }; +} + +export function checkInstalled(outcome: Outcome): CheckResult { + const failed = 'failure' in outcome && !outcome.installed; + return { + name: CHECK.installed, + passed: !failed, + notes: failed + ? `${outcome.failure}. Scoring needs the npm registry, so read this as a lost run unless the agent changed the lockfile` + : 'npm ci in the workspace and the pinned scorer client both installed', + }; +} + +export function checkLoads(outcome: Outcome): CheckResult { + if ('failure' in outcome) return notRun(outcome, CHECK.loads); + const loaded = outcome.probe.stage !== 'load'; + return { + name: CHECK.loads, + passed: loaded, + notes: loaded ? 'watchRoom is a function' : outcome.probe.note, + }; +} + +export function checkMemberSees(outcome: Outcome, source: Source): CheckResult { + const name = CHECK[source]; + if (!reached(outcome, 'post')) return notRun(outcome, name); + const delivery = outcome.probe.delivered[source]; + if (!delivery) { + return { name, passed: false, notes: 'the scorer never sent this message' }; + } + const sent = delivery.error + ? ` The send itself failed: ${delivery.error}.` + : ''; + return { + name, + passed: delivery.seen !== '', + notes: + delivery.seen !== '' + ? `delivered by ${delivery.route}: ${delivery.seen}` + : `nothing carrying the message reached the callback within ${DELIVERY_WINDOW_SECONDS} seconds.${sent} The member's channels: ${listed(outcome.probe.topics)}`, + }; +} + +export function checkNeverSees(outcome: Outcome, who: Bystander): CheckResult { + const name = CHECK[who]; + if (!reached(outcome, 'post')) return notRun(outcome, name); + const { probe } = outcome; + const tried = listed(probe.joins[who]); + if (probe.leaks[who].length > 0) { + return { + name, + passed: false, + notes: `got ${probe.leaks[who][0]}. Tried: ${tried}`, + }; + } + if (probe.topics.length === 0) { + return { + name, + passed: false, + notes: `could not measure: watchRoom joined nothing on the client it was given, so there was no topic to try directly. Tried: ${tried}`, + }; + } + return { + name, + passed: true, + notes: `nothing carrying a room message arrived. Tried: ${tried}.${publicRefused(probe.joins[who])}`, + }; +} + +export function checkCannotForge(outcome: Outcome): CheckResult { + if (!reached(outcome, 'forge')) return notRun(outcome, CHECK.forged); + const { probe } = outcome; + const { forgery } = probe; + const tried = listed(forgery.tried); + if (forgery.rowStored || forgery.seen.length > 0) { + return { + name: CHECK.forged, + passed: false, + notes: [ + forgery.rowStored ? forgery.rowNote : '', + forgery.seen.length > 0 + ? `the member's callback got ${forgery.seen[0]}` + : '', + `Tried: ${tried}`, + ] + .filter((part) => part !== '') + .join('. '), + }; + } + const unmeasured = [ + probe.topics.length === 0 + ? 'watchRoom joined nothing on the client it was given, so there was no topic to send on' + : '', + probe.controlDelivered + ? '' + : "the scorer's own message on its private control topic never arrived", + forgery.rowNote.startsWith('could not') ? forgery.rowNote : '', + ].filter((part) => part !== ''); + if (unmeasured.length > 0) { + return { + name: CHECK.forged, + passed: false, + notes: `could not measure: ${unmeasured.join('; ')}. Tried: ${tried}`, + }; + } + return { + name: CHECK.forged, + passed: true, + notes: `${forgery.rowNote}. The member's callback got none of the forged messages. Tried: ${tried}.${publicRefused(forgery.tried)}`, + }; +} + +const PUBLIC_REFUSED = + ' Public joins that never reached joined were refused, which counts as no leak and no forgery.'; + +function publicRefused(lines: string[]): string { + return lines.some((line) => + / public (join )?(joining|errored|closed)$/.test(line) + ) + ? PUBLIC_REFUSED + : ''; +} + +function listed(lines: string[]): string { + return lines.length > 0 ? lines.join('; ').slice(0, 600) : 'none'; +}