From 981be24e545e7194ae9d998954b36879f9a81fbc Mon Sep 17 00:00:00 2001 From: Vadym Musiienko Date: Wed, 2 Dec 2026 19:51:37 -0800 Subject: [PATCH 1/3] Switch to new Supabase API keys --- .github/workflows/frontend.yml | 10 +- ML/documentation/operations.md | 2 +- README.md | 8 +- frontend/README.md | 2 +- frontend/documentation/CODEBASE_ONBOARDING.md | 6 +- frontend/documentation/SUPABASE.md | 22 +-- frontend/jest.config.js | 2 + frontend/package.json | 1 + frontend/src/app/contact/page.tsx | 8 +- frontend/src/lib/server/edgeFunctions.ts | 2 +- frontend/src/utils/supabase.ts | 8 +- frontend/supabase/config.toml | 18 ++- .../supabase/functions/_shared/auth.test.ts | 140 ++++++++++++++++++ frontend/supabase/functions/_shared/auth.ts | 51 ++++++- .../supabase/functions/delays-sweep/index.ts | 6 +- .../functions/delays-sweep/processUpdate.ts | 6 +- .../send-algorithm-match-email/index.ts | 6 +- .../send-all-match-emails-batch/index.ts | 6 +- .../send-flight-submission-email/index.ts | 6 +- .../send-unmatched-emails-batch/index.ts | 11 +- start.sh | 16 +- 21 files changed, 266 insertions(+), 71 deletions(-) create mode 100644 frontend/supabase/functions/_shared/auth.test.ts diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml index 3202900..833480e 100644 --- a/.github/workflows/frontend.yml +++ b/.github/workflows/frontend.yml @@ -101,6 +101,14 @@ jobs: - name: Run tests run: pnpm test:ci --passWithNoTests + - name: Install Deno + uses: denoland/setup-deno@v2 + with: + deno-version: v2.x + + - name: Run edge function tests + run: pnpm test:edge + database-compatibility: name: Database Contract (Static) runs-on: ubuntu-latest @@ -156,4 +164,4 @@ jobs: run: pnpm build env: NEXT_PUBLIC_SUPABASE_URL: https://ci-build.supabase.co - NEXT_PUBLIC_SUPABASE_ANON_KEY: ci-build-placeholder + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY: ci-build-placeholder diff --git a/ML/documentation/operations.md b/ML/documentation/operations.md index bbd62b1..5ad177f 100644 --- a/ML/documentation/operations.md +++ b/ML/documentation/operations.md @@ -27,7 +27,7 @@ Create `.env` at the repo root: ```bash SUPABASE_URL=https://your-project.supabase.co -SUPABASE_SECRET_KEY=your_service_role_or_secret_key +SUPABASE_SECRET_KEY=your_secret_key ``` `main.py` loads `.env` via `python-dotenv` when you run from `Algorithm/`. diff --git a/README.md b/README.md index 42aa412..7f22e85 100644 --- a/README.md +++ b/README.md @@ -52,8 +52,8 @@ Both files are gitignored. Get the values from the Supabase dashboard (**Project ```bash NEXT_PUBLIC_SUPABASE_URL=https://.supabase.co -NEXT_PUBLIC_SUPABASE_ANON_KEY= -SUPABASE_SECRET_KEY= # server only, never NEXT_PUBLIC_ +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= +SUPABASE_SECRET_KEY= # server only, never NEXT_PUBLIC_ # Your own Google OAuth client for local sign-in (step 5) SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID= @@ -66,11 +66,11 @@ NEXT_PUBLIC_ENABLE_MATCH_REQUESTS=false ```bash SUPABASE_URL=https://.supabase.co -SUPABASE_SECRET_KEY= +SUPABASE_SECRET_KEY= ``` > [!CAUTION] -> The service role key bypasses all database security. Never commit it or paste it into chats or issues. +> The secret key bypasses all database security. Never commit it or paste it into chats or issues. ### 4. Pull the database schema diff --git a/frontend/README.md b/frontend/README.md index fd4c8f1..a7103c9 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -18,7 +18,7 @@ Next.js app for managing pickup workflows, matching requests, and admin operatio 2. Create `.env.local`: ```bash NEXT_PUBLIC_SUPABASE_URL=your_supabase_url - NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key + NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your_supabase_publishable_key ``` 3. Run locally: ```bash diff --git a/frontend/documentation/CODEBASE_ONBOARDING.md b/frontend/documentation/CODEBASE_ONBOARDING.md index 3c97da0..d4e0722 100644 --- a/frontend/documentation/CODEBASE_ONBOARDING.md +++ b/frontend/documentation/CODEBASE_ONBOARDING.md @@ -5,7 +5,7 @@ Quick path from clone to a safe first change. ## Prerequisites - Node 20+, **pnpm** 9.15+ (`corepack use pnpm@9.15.2`) -- Supabase project access (URL, anon key, service role secret) +- Supabase project access (URL, publishable key, secret key) - Google OAuth configured in Supabase (for local sign-in) - Netlify access if you need to check production env vars or deploy settings @@ -19,8 +19,8 @@ Create `.env.local` (minimum): ```bash NEXT_PUBLIC_SUPABASE_URL=https://.supabase.co -NEXT_PUBLIC_SUPABASE_ANON_KEY= -SUPABASE_SECRET_KEY= # server only; never expose +NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= +SUPABASE_SECRET_KEY= # server only; never expose ``` Optional: diff --git a/frontend/documentation/SUPABASE.md b/frontend/documentation/SUPABASE.md index 49b4f25..0b6c5ac 100644 --- a/frontend/documentation/SUPABASE.md +++ b/frontend/documentation/SUPABASE.md @@ -16,11 +16,13 @@ Source of truth: [`supabase/functions/`](../supabase/functions). Change them her | `send-algorithm-match-email` | `on_algorithm_match_created` / `is_verified_match_trigger` triggers (both **disabled** in production) | Per-rider match email | | `delays-sweep` | `delays-sweep-20` cron job | Polls AirLabs and emails a ride group when a member's flight is delayed or cancelled | -**Auth:** every function requires the **service role key** as `Authorization: Bearer ` ([`_shared/auth.ts`](../supabase/functions/_shared/auth.ts)) and returns 401 otherwise. The anon key is public, so it must never be enough to send email. Callers: +**Auth:** every function requires one of the project's **secret API keys** (`sb_secret_...`), sent as `Authorization: Bearer ` or in the `apikey` header ([`_shared/auth.ts`](../supabase/functions/_shared/auth.ts)), and returns 401 otherwise. Supabase injects the current secret keys into every function as `SUPABASE_SECRET_KEYS`, so creating or deleting a key in the dashboard needs no redeploy. The functions also use that key for their own database access (the key named `default`, otherwise the first one). The publishable key is public, so it must never be enough to send email, and the legacy `service_role` JWT is never accepted. Callers: - Admin API routes check the admin role, then call the function through `relayEdgeFunction` (`src/lib/server/edgeFunctions.ts`) with `SUPABASE_SECRET_KEY`. -- Triggers send `app.secrets.edge_auth`, which must be `Bearer `. -- The cron job must send the same header. `delays-sweep` has `verify_jwt = false` at the gateway (`config.toml`), so the in-code check is its only protection. +- Triggers send `app.secrets.edge_auth`, which must be `Bearer `. +- The cron job must send the same header. + +Secret keys are not JWTs, so every function has `verify_jwt = false` at the gateway (`config.toml`); the in-code check is their only protection. **Custom emails** are plain text: HTML is escaped and line breaks are kept. Placeholders such as `{{name}}` are filled in per recipient (the composer in the admin dashboard lists them). @@ -34,7 +36,7 @@ Email **content rules** (variants: subsidized × direction) are described in [BA pnpm exec supabase functions deploy --project-ref ``` -Deploying `delays-sweep` picks up `verify_jwt = false` from `config.toml`. +Deploys pick up `verify_jwt = false` from `config.toml`. ## Postgres RPCs used by the app @@ -126,10 +128,10 @@ If production already has equivalent definitions, diff before applying to avoid ## Environment variables (Supabase-related) -| Variable | Exposure | Use | -| ------------------------------- | --------------- | ---------------------------------------------------------------- | -| `NEXT_PUBLIC_SUPABASE_URL` | Public | Client + server | -| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Public | Client + server session; edge invoke from admin routes | -| `SUPABASE_SECRET_KEY` | **Server only** | Service role client for admin commands and selected student APIs | +| Variable | Exposure | Use | +| -------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------- | +| `NEXT_PUBLIC_SUPABASE_URL` | Public | Client + server | +| `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY` | Public | Client + server session (`sb_publishable_...`) | +| `SUPABASE_SECRET_KEY` | **Server only** | Secret key (`sb_secret_...`) for admin commands, selected student APIs and edge function calls | -Never prefix the service role key with `NEXT_PUBLIC_`. +Never prefix the secret key with `NEXT_PUBLIC_`. diff --git a/frontend/jest.config.js b/frontend/jest.config.js index e2854cc..b4316f6 100644 --- a/frontend/jest.config.js +++ b/frontend/jest.config.js @@ -12,6 +12,8 @@ const customJestConfig = { '^@/(.*)$': '/src/$1', }, testEnvironment: 'jsdom', + // Edge functions run on Deno and are tested with `pnpm test:edge`. + testPathIgnorePatterns: ['/supabase/functions/'], transform: { '^.+\\.(t|j)sx?$': '@swc/jest', }, diff --git a/frontend/package.json b/frontend/package.json index 7aa04ad..7f40d32 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -26,6 +26,7 @@ "prepare": "cd .. && husky install frontend/.husky || true", "test": "jest", "test:ci": "jest --ci", + "test:edge": "deno test --allow-env supabase/functions", "test:database-contract": "jest --ci --runInBand src/lib/server/databaseContract.test.ts", "audit:security": "pnpm audit --audit-level high", "analyze": "ANALYZE=true pnpm build", diff --git a/frontend/src/app/contact/page.tsx b/frontend/src/app/contact/page.tsx index 58f4694..1a68af6 100644 --- a/frontend/src/app/contact/page.tsx +++ b/frontend/src/app/contact/page.tsx @@ -55,18 +55,14 @@ export default function Contact() {

Email support

-

- For general questions: -

+

For general questions:

{SUPPORT_EMAIL} -

- For technical questions: -

+

For technical questions:

{ if (typeof window === 'undefined') { return browserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, ) } if (!browserClientSingleton) { browserClientSingleton = browserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, ) } return browserClientSingleton @@ -29,7 +29,7 @@ export const createServerClient = ( ) => serverClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, { cookies: { getAll() { @@ -54,7 +54,7 @@ export const createMiddlewareClient = (request: NextRequest) => { const supabase = serverClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, - process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, { cookies: { getAll() { diff --git a/frontend/supabase/config.toml b/frontend/supabase/config.toml index 012e61d..7ab76b3 100644 --- a/frontend/supabase/config.toml +++ b/frontend/supabase/config.toml @@ -432,8 +432,20 @@ enabled = true # JSON string passed through to pg-delta SQL formatting. # format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}" -# Edge functions (source in supabase/functions). All of them require the service role key in -# code (see _shared/auth.ts). delays-sweep is called by cron, so the gateway JWT check is off for -# it, matching production. +# Edge functions (source in supabase/functions). All of them require one of the project's secret +# API keys (sb_secret_...) in code, see _shared/auth.ts. Those keys are not JWTs, so the gateway JWT +# check has to be off for every function; the in-code check is what protects them. [functions.delays-sweep] verify_jwt = false + +[functions.send-algorithm-match-email] +verify_jwt = false + +[functions.send-all-match-emails-batch] +verify_jwt = false + +[functions.send-flight-submission-email] +verify_jwt = false + +[functions.send-unmatched-emails-batch] +verify_jwt = false diff --git a/frontend/supabase/functions/_shared/auth.test.ts b/frontend/supabase/functions/_shared/auth.test.ts new file mode 100644 index 0000000..1597bc7 --- /dev/null +++ b/frontend/supabase/functions/_shared/auth.test.ts @@ -0,0 +1,140 @@ +// Run with: deno test supabase/functions/_shared/auth.test.ts --allow-env +import { + assertEquals, + assertThrows, +} from 'https://deno.land/std@0.224.0/assert/mod.ts' +import { adminKey, requireSecretKey } from './auth.ts' + +const SECRET = 'sb_secret_current' +const OTHER_SECRET = 'sb_secret_second' +const LEGACY_SERVICE_ROLE = 'eyJhbGciOiJIUzI1NiJ9.legacy.service_role' + +function withEnv(env: Record, run: () => void) { + const saved = Object.fromEntries( + Object.keys(env).map((name) => [name, Deno.env.get(name)]), + ) + const apply = (values: Record) => { + for (const [name, value] of Object.entries(values)) { + if (value === undefined) Deno.env.delete(name) + else Deno.env.set(name, value) + } + } + apply(env) + try { + run() + } finally { + apply(saved) + } +} + +const projectKeys = { + SUPABASE_SECRET_KEYS: JSON.stringify({ + default: SECRET, + second: OTHER_SECRET, + }), + SUPABASE_SERVICE_ROLE_KEY: LEGACY_SERVICE_ROLE, +} + +function request(headers: Record) { + return new Request('http://localhost/functions/v1/test', { + method: 'POST', + headers, + }) +} + +Deno.test('accepts a secret key sent as a bearer token', () => { + withEnv(projectKeys, () => { + assertEquals( + requireSecretKey(request({ Authorization: `Bearer ${SECRET}` })), + null, + ) + }) +}) + +Deno.test('accepts a secret key sent in the apikey header', () => { + withEnv(projectKeys, () => { + assertEquals(requireSecretKey(request({ apikey: OTHER_SECRET })), null) + }) +}) + +Deno.test('rejects the legacy service role key', () => { + withEnv(projectKeys, () => { + const response = requireSecretKey( + request({ + Authorization: `Bearer ${LEGACY_SERVICE_ROLE}`, + apikey: LEGACY_SERVICE_ROLE, + }), + ) + assertEquals(response?.status, 401) + }) +}) + +Deno.test('rejects the publishable key and missing credentials', () => { + withEnv(projectKeys, () => { + assertEquals( + requireSecretKey(request({ apikey: 'sb_publishable_public' }))?.status, + 401, + ) + assertEquals(requireSecretKey(request({}))?.status, 401) + }) +}) + +Deno.test('rejects everything when no secret keys are configured', () => { + withEnv( + { + SUPABASE_SECRET_KEYS: undefined, + SUPABASE_SERVICE_ROLE_KEY: LEGACY_SERVICE_ROLE, + }, + () => { + const response = requireSecretKey( + request({ Authorization: `Bearer ${LEGACY_SERVICE_ROLE}` }), + ) + assertEquals(response?.status, 401) + }, + ) +}) + +Deno.test('keeps the CORS headers on the 401 response', () => { + withEnv(projectKeys, () => { + const response = requireSecretKey(request({}), { + 'Access-Control-Allow-Origin': '*', + }) + assertEquals(response?.headers.get('Access-Control-Allow-Origin'), '*') + }) +}) + +Deno.test('adminKey prefers the key named default', () => { + withEnv(projectKeys, () => assertEquals(adminKey(), SECRET)) +}) + +Deno.test( + 'adminKey falls back to the first key when none is named default', + () => { + withEnv( + { SUPABASE_SECRET_KEYS: JSON.stringify({ ops: OTHER_SECRET }) }, + () => assertEquals(adminKey(), OTHER_SECRET), + ) + }, +) + +Deno.test('adminKey throws instead of falling back to the legacy key', () => { + withEnv( + { + SUPABASE_SECRET_KEYS: undefined, + SUPABASE_SERVICE_ROLE_KEY: LEGACY_SERVICE_ROLE, + }, + () => { + assertThrows(() => adminKey(), Error, 'SUPABASE_SECRET_KEYS') + }, + ) +}) + +Deno.test('ignores malformed SUPABASE_SECRET_KEYS', () => { + withEnv({ SUPABASE_SECRET_KEYS: 'not json' }, () => { + assertEquals( + requireSecretKey(request({ Authorization: 'Bearer not json' }))?.status, + 401, + ) + assertThrows(() => adminKey(), Error, 'SUPABASE_SECRET_KEYS') + }) +}) diff --git a/frontend/supabase/functions/_shared/auth.ts b/frontend/supabase/functions/_shared/auth.ts index 8ff61ca..9774cde 100644 --- a/frontend/supabase/functions/_shared/auth.ts +++ b/frontend/supabase/functions/_shared/auth.ts @@ -1,6 +1,8 @@ // These functions are internal: they are called by the Next.js admin API routes (which check the -// admin role first), by database triggers and by cron, all with the service role key. The anon -// key is public (it ships in the browser bundle), so it must never be enough to trigger an email. +// admin role first), by database triggers and by cron, all with one of the project's secret API keys +// (sb_secret_...). The publishable key is public (it ships in the browser bundle), so it must never be +// enough to trigger an email. The legacy service_role JWT is deliberately never accepted or used, so +// disabling the legacy API keys in the dashboard fully retires it. const encoder = new TextEncoder() @@ -13,18 +15,53 @@ function timingSafeEqual(a: string, b: string): boolean { return diff === 0 } -/** Returns a 401 response unless the request carries the service role key, otherwise null. */ -export function requireServiceRole( +/** + * The project's secret API keys by name. Supabase injects them into every function as + * SUPABASE_SECRET_KEYS (a JSON object), and keeps it current when keys are created or deleted. + */ +function secretKeys(): Map { + try { + const parsed = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS') ?? '{}') + return new Map( + Object.entries(parsed ?? {}).filter( + (entry): entry is [string, string] => + typeof entry[1] === 'string' && entry[1].length > 0, + ), + ) + } catch { + return new Map() + } +} + +/** The secret key the functions use for their own database access. */ +export function adminKey(): string { + const keys = secretKeys() + const key = keys.get('default') ?? keys.values().next().value + if (!key) { + throw new Error( + 'No secret API key available: SUPABASE_SECRET_KEYS is empty. Create a secret key under Project Settings -> API Keys.', + ) + } + return key +} + +/** Returns a 401 response unless the request carries one of the project's secret keys, otherwise null. */ +export function requireSecretKey( req: Request, headers: Record = {}, ): Response | null { - const serviceRoleKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '' - const token = (req.headers.get('Authorization') ?? '').replace( + const bearer = (req.headers.get('Authorization') ?? '').replace( /^Bearer\s+/i, '', ) + const presented = [req.headers.get('apikey') ?? '', bearer].filter(Boolean) + const accepted = [...secretKeys().values()] - if (serviceRoleKey && token && timingSafeEqual(token, serviceRoleKey)) { + if ( + presented.some((token) => + accepted.some((key) => timingSafeEqual(token, key)), + ) + ) { return null } diff --git a/frontend/supabase/functions/delays-sweep/index.ts b/frontend/supabase/functions/delays-sweep/index.ts index b32b532..cd3bb6e 100644 --- a/frontend/supabase/functions/delays-sweep/index.ts +++ b/frontend/supabase/functions/delays-sweep/index.ts @@ -1,11 +1,11 @@ // supabase/functions/delays-sweep/index.ts -// Run by the delays-sweep-20 cron job, which must send the service role key. -import { requireServiceRole } from '../_shared/auth.ts' +// Run by the delays-sweep-20 cron job, which must send a secret API key (sb_secret_...). +import { requireSecretKey } from '../_shared/auth.ts' import { type FlightUpdate, processUpdate } from './processUpdate.ts' // flip this flag to true locally to simulate delays/cancellations // const TEST_MODE = true; Deno.serve(async (req) => { - const unauthorized = requireServiceRole(req) + const unauthorized = requireSecretKey(req) if (unauthorized) return unauthorized const airports = ['LAX', 'ONT'] diff --git a/frontend/supabase/functions/delays-sweep/processUpdate.ts b/frontend/supabase/functions/delays-sweep/processUpdate.ts index 1c99eb4..47aa3b8 100644 --- a/frontend/supabase/functions/delays-sweep/processUpdate.ts +++ b/frontend/supabase/functions/delays-sweep/processUpdate.ts @@ -1,11 +1,9 @@ // supabase/functions/delays-sweep/processUpdate.ts import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' +import { adminKey } from '../_shared/auth.ts' import { escapeHtml } from '../_shared/html.ts' import { pacificDateTime, pacificToday } from '../_shared/time.ts' -const supabase = createClient( - Deno.env.get('SUPABASE_URL') ?? '', - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '', -) +const supabase = createClient(Deno.env.get('SUPABASE_URL') ?? '', adminKey()) export type FlightUpdate = { airline_iata: string diff --git a/frontend/supabase/functions/send-algorithm-match-email/index.ts b/frontend/supabase/functions/send-algorithm-match-email/index.ts index ff037a6..fab455a 100644 --- a/frontend/supabase/functions/send-algorithm-match-email/index.ts +++ b/frontend/supabase/functions/send-algorithm-match-email/index.ts @@ -1,6 +1,6 @@ import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' -import { requireServiceRole } from '../_shared/auth.ts' +import { adminKey, requireSecretKey } from '../_shared/auth.ts' import { escapeHtml } from '../_shared/html.ts' const corsHeaders = { 'Access-Control-Allow-Origin': '*', @@ -25,13 +25,13 @@ serve(async (req) => { }) } // Called by the Matches triggers (handle_algorithm_match_created) with app.secrets.edge_auth - const unauthorized = requireServiceRole(req, corsHeaders) + const unauthorized = requireSecretKey(req, corsHeaders) if (unauthorized) return unauthorized try { const supabase = createClient( Deno.env.get('SUPABASE_URL') ?? '', - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '', + adminKey(), ) const { user_id, ride_id, flight_id } = await req.json() // Get user details diff --git a/frontend/supabase/functions/send-all-match-emails-batch/index.ts b/frontend/supabase/functions/send-all-match-emails-batch/index.ts index 3cb73b2..7fad187 100644 --- a/frontend/supabase/functions/send-all-match-emails-batch/index.ts +++ b/frontend/supabase/functions/send-all-match-emails-batch/index.ts @@ -1,6 +1,6 @@ import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' -import { requireServiceRole } from '../_shared/auth.ts' +import { adminKey, requireSecretKey } from '../_shared/auth.ts' import { escapeHtml, plainTextToHtml } from '../_shared/html.ts' const corsHeaders = { @@ -236,13 +236,13 @@ serve(async (req) => { }) } - const unauthorized = requireServiceRole(req, corsHeaders) + const unauthorized = requireSecretKey(req, corsHeaders) if (unauthorized) return unauthorized try { const supabase = createClient( Deno.env.get('SUPABASE_URL') ?? '', - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '', + adminKey(), ) const { diff --git a/frontend/supabase/functions/send-flight-submission-email/index.ts b/frontend/supabase/functions/send-flight-submission-email/index.ts index 8d79698..75eef9f 100644 --- a/frontend/supabase/functions/send-flight-submission-email/index.ts +++ b/frontend/supabase/functions/send-flight-submission-email/index.ts @@ -1,7 +1,7 @@ // supabase/functions/send-flight-submission-email/index.ts import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' -import { requireServiceRole } from '../_shared/auth.ts' +import { adminKey, requireSecretKey } from '../_shared/auth.ts' import { escapeHtml } from '../_shared/html.ts' const corsHeaders = { 'Access-Control-Allow-Origin': '*', @@ -15,7 +15,7 @@ serve(async (req) => { }) } // Called by the trg_flights_after_insert_notify trigger with app.secrets.edge_auth - const unauthorized = requireServiceRole(req, corsHeaders) + const unauthorized = requireSecretKey(req, corsHeaders) if (unauthorized) return unauthorized try { @@ -35,7 +35,7 @@ serve(async (req) => { } const supabase = createClient( Deno.env.get('SUPABASE_URL') ?? '', - Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '', + adminKey(), ) // Fetch user (source of truth for email & name) const { data: userData, error: userErr } = await supabase diff --git a/frontend/supabase/functions/send-unmatched-emails-batch/index.ts b/frontend/supabase/functions/send-unmatched-emails-batch/index.ts index ed99fa3..6f2f066 100644 --- a/frontend/supabase/functions/send-unmatched-emails-batch/index.ts +++ b/frontend/supabase/functions/send-unmatched-emails-batch/index.ts @@ -1,14 +1,13 @@ // Supabase Edge Function: send-unmatched-emails-batch -// Called by /api/admin/send-unmatched-emails with the service role key. +// Called by /api/admin/send-unmatched-emails with a secret API key. import { serve } from 'https://deno.land/std@0.168.0/http/server.ts' import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' -import { requireServiceRole } from '../_shared/auth.ts' +import { adminKey, requireSecretKey } from '../_shared/auth.ts' import { escapeHtml, plainTextToHtml } from '../_shared/html.ts' const RESEND_API_KEY = Deno.env.get('RESEND_API_KEY')! const SUPABASE_URL = Deno.env.get('SUPABASE_URL')! -const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')! interface UnmatchedFlight { flight_id: number @@ -178,7 +177,7 @@ serve(async (req) => { }) } - const unauthorized = requireServiceRole(req, { + const unauthorized = requireSecretKey(req, { 'Access-Control-Allow-Origin': '*', }) if (unauthorized) return unauthorized @@ -200,8 +199,8 @@ serve(async (req) => { ) } - // Create Supabase client with service role key - const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY) + // Create Supabase client with the secret API key + const supabase = createClient(SUPABASE_URL, adminKey()) // Fetch flights in date range that haven't been emailed yet // Unmatched = NOT in Matches table (source of truth), not matched=false diff --git a/start.sh b/start.sh index dcf6a1d..251c32f 100755 --- a/start.sh +++ b/start.sh @@ -110,23 +110,23 @@ start_local_db() { # Exports the local stack's URL and keys under the names each app expects. export_local_credentials() { - local status api_url anon_key service_key attempt + local status api_url publishable_key secret_key attempt # Right after Docker Desktop starts, containers auto-restart and status fails # until they are healthy, so give the stack a moment before giving up. for attempt in $(seq 1 15); do status="$(supabase_cli status -o env 2>/dev/null || true)" api_url="$(env_value <(printf '%s\n' "$status") API_URL)" - anon_key="$(env_value <(printf '%s\n' "$status") ANON_KEY)" - service_key="$(env_value <(printf '%s\n' "$status") SERVICE_ROLE_KEY)" - [[ -n "$api_url" && -n "$anon_key" && -n "$service_key" ]] && break + publishable_key="$(env_value <(printf '%s\n' "$status") PUBLISHABLE_KEY)" + secret_key="$(env_value <(printf '%s\n' "$status") SECRET_KEY)" + [[ -n "$api_url" && -n "$publishable_key" && -n "$secret_key" ]] && break [[ "$attempt" -lt 15 ]] && sleep 2 done - [[ -n "$api_url" && -n "$anon_key" && -n "$service_key" ]] || die "Could not read local Supabase credentials. Run ./start.sh db:status to see which service is down, or ./start.sh db:stop and retry." + [[ -n "$api_url" && -n "$publishable_key" && -n "$secret_key" ]] || die "Could not read local Supabase credentials. Run ./start.sh db:status to see which service is down, or ./start.sh db:stop and retry." # Process env takes precedence over frontend/.env and ML/.env, so production values there are ignored. export NEXT_PUBLIC_SUPABASE_URL="$api_url" - export NEXT_PUBLIC_SUPABASE_ANON_KEY="$anon_key" - export SUPABASE_SECRET_KEY="$service_key" + export NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY="$publishable_key" + export SUPABASE_SECRET_KEY="$secret_key" export SUPABASE_URL="$api_url" } @@ -154,7 +154,7 @@ cmd_prod() { printf '\033[1;31mYou are about to run against PRODUCTION data at %s.\033[0m\n' "$url" read -r -p "Type 'prod' to continue: " answer [[ "$answer" == "prod" ]] || die "Aborted." - unset NEXT_PUBLIC_SUPABASE_URL NEXT_PUBLIC_SUPABASE_ANON_KEY SUPABASE_SECRET_KEY + unset NEXT_PUBLIC_SUPABASE_URL NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY SUPABASE_SECRET_KEY cd "$FRONTEND" && exec pnpm dev } From a5db831e11c771012bc864066e60dd911b4bc43d Mon Sep 17 00:00:00 2001 From: Vadym Musiienko Date: Wed, 2 Dec 2026 20:08:48 -0800 Subject: [PATCH 2/3] Patch cross-spawn and ws advisories --- frontend/package.json | 4 +++- frontend/pnpm-lock.yaml | 34 ++++++++++++++++++---------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/frontend/package.json b/frontend/package.json index 7f40d32..e73d0e3 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -83,6 +83,7 @@ "@typescript-eslint/parser": "8.61.0", "brace-expansion": "5.0.12", "browserslist": "4.29.3", + "cross-spawn@^7.0.0": "7.1.2", "js-yaml@^3.0.0": "3.15.2", "js-yaml@^4.0.0": "4.3.2", "nanoid@^3.0.0": "3.3.20", @@ -91,7 +92,8 @@ "smol-toml": "1.9.1", "source-map-js": "1.2.2", "tar": "7.5.22", - "webpack-bundle-analyzer>ws": "7.5.11" + "webpack-bundle-analyzer>ws": "7.5.14", + "ws@^8.0.0": "8.23.1" }, "auditConfig": { "ignoreGhsas": [ diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 03c4f2d..b9e66af 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -9,6 +9,7 @@ overrides: '@typescript-eslint/parser': 8.61.0 brace-expansion: 5.0.12 browserslist: 4.29.3 + cross-spawn@^7.0.0: 7.1.2 js-yaml@^3.0.0: 3.15.2 js-yaml@^4.0.0: 4.3.2 nanoid@^3.0.0: 3.3.20 @@ -17,7 +18,8 @@ overrides: smol-toml: 1.9.1 source-map-js: 1.2.2 tar: 7.5.22 - webpack-bundle-analyzer>ws: 7.5.11 + webpack-bundle-analyzer>ws: 7.5.14 + ws@^8.0.0: 8.23.1 importers: @@ -2004,8 +2006,8 @@ packages: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + cross-spawn@7.1.2: + resolution: {integrity: sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==} engines: {node: '>= 8'} css.escape@1.5.1: @@ -4129,8 +4131,8 @@ packages: resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} - ws@7.5.11: - resolution: {integrity: sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA==} + ws@7.5.14: + resolution: {integrity: sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==} engines: {node: '>=8.3.0'} peerDependencies: bufferutil: ^4.0.1 @@ -4141,8 +4143,8 @@ packages: utf-8-validate: optional: true - ws@8.21.0: - resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} + ws@8.23.1: + resolution: {integrity: sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==} engines: {node: '>=10.0.0'} peerDependencies: bufferutil: ^4.0.1 @@ -6020,7 +6022,7 @@ snapshots: cookie@1.1.1: {} - cross-spawn@7.0.6: + cross-spawn@7.1.2: dependencies: path-key: 3.1.1 shebang-command: 2.0.0 @@ -6441,7 +6443,7 @@ snapshots: '@ungap/structured-clone': 1.3.1 ajv: 6.15.0 chalk: 4.1.2 - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 debug: 4.4.3 doctrine: 3.0.0 escape-string-regexp: 4.0.0 @@ -6496,7 +6498,7 @@ snapshots: execa@5.1.1: dependencies: - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 get-stream: 6.0.1 human-signals: 2.1.0 is-stream: 2.0.1 @@ -6508,7 +6510,7 @@ snapshots: execa@8.0.1: dependencies: - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 get-stream: 8.0.1 human-signals: 5.0.0 is-stream: 3.0.0 @@ -6599,7 +6601,7 @@ snapshots: foreground-child@3.3.1: dependencies: - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 signal-exit: 4.1.0 formatly@0.11.4: @@ -7352,7 +7354,7 @@ snapshots: whatwg-encoding: 3.1.1 whatwg-mimetype: 4.0.0 whatwg-url: 14.2.0 - ws: 8.21.0 + ws: 8.23.1 xml-name-validator: 5.0.0 transitivePeerDependencies: - bufferutil @@ -8542,7 +8544,7 @@ snapshots: opener: 1.5.2 picocolors: 1.1.1 sirv: 2.0.4 - ws: 7.5.11 + ws: 7.5.14 transitivePeerDependencies: - bufferutil - utf-8-validate @@ -8630,9 +8632,9 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 4.1.0 - ws@7.5.11: {} + ws@7.5.14: {} - ws@8.21.0: {} + ws@8.23.1: {} xml-name-validator@5.0.0: {} From de6813483446308e0445cb137d68b4f19343c002 Mon Sep 17 00:00:00 2001 From: Vadym Musiienko Date: Wed, 2 Dec 2026 20:09:05 -0800 Subject: [PATCH 3/3] Document delays cron auth header --- frontend/documentation/OPERATIONS.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/frontend/documentation/OPERATIONS.md b/frontend/documentation/OPERATIONS.md index 32388b4..1fff4bb 100644 --- a/frontend/documentation/OPERATIONS.md +++ b/frontend/documentation/OPERATIONS.md @@ -66,3 +66,15 @@ You can change the edge functions to only send emails when the matches are manua Supabase Dashboard → **Integrations** → **Cron** → enable job **`delays-sweep-20`**. [Cron jobs](https://supabase.com/dashboard/project/zgunhxopkgbksfoxthpn/integrations/cron/jobs) + +The job must send the same `Authorization` header as the database triggers, or `delays-sweep` answers 401 on every run. Its command reads the header from `app.secrets`, so rotating the secret key only needs the `edge_auth` row updated: + +```sql +select net.http_post( + url := 'https://zgunhxopkgbksfoxthpn.supabase.co/functions/v1/delays-sweep', + headers := jsonb_build_object( + 'Authorization', (select value from app.secrets where name = 'edge_auth') + ), + timeout_milliseconds := 5000 +); +```