Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat(staff): staff check (bearer + AEO_STAFF_EMAILS) and requested_by…
… migration draft

Not wired into routes yet. Unset AEO_STAFF_EMAILS means nobody is staff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
razel-hash and claude committed Nov 10, 2026
commit 3ac1005663247fba97cd5a68b5ce9ec1ee81448d
45 changes: 45 additions & 0 deletions src/lib/staff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// FR-014: a caller is staff only when a verified sign-in token belongs to an email on
// AEO_STAFF_EMAILS. Anything missing or unverifiable means public.

import { describe, it, expect, afterEach, vi } from 'vitest';
import { staffEmail, staffList } from './staff';

const req = (auth?: string) => ({ headers: new Headers(auth ? { authorization: auth } : {}) });

afterEach(() => { delete process.env.AEO_STAFF_EMAILS; });

describe('staff list', () => {
it('is empty when unset, and normalised when set', () => {
expect(staffList()).toEqual([]);
process.env.AEO_STAFF_EMAILS = ' Staff@Example.com , , other@example.com ';
expect(staffList()).toEqual(['staff@example.com', 'other@example.com']);
});
});

describe('staffEmail', () => {
it('no list: nobody is staff, and the token is not even checked', async () => {
const verify = vi.fn(async () => 'staff@example.com');
expect(await staffEmail(req('Bearer t'), verify)).toBeNull();
expect(verify).not.toHaveBeenCalled();
});

it('a verified token for a listed email is staff', async () => {
process.env.AEO_STAFF_EMAILS = 'staff@example.com';
expect(await staffEmail(req('Bearer good'), async () => 'Staff@Example.com')).toBe('staff@example.com');
});

it('a verified token for an unlisted email is public', async () => {
process.env.AEO_STAFF_EMAILS = 'staff@example.com';
expect(await staffEmail(req('Bearer good'), async () => 'visitor@example.com')).toBeNull();
});

it('no token, a malformed header, or a token that fails to verify is public', async () => {
process.env.AEO_STAFF_EMAILS = 'staff@example.com';
const ok = async () => 'staff@example.com';
expect(await staffEmail(req(), ok)).toBeNull();
expect(await staffEmail(req('Basic abc'), ok)).toBeNull();
expect(await staffEmail(req('Bearer '), ok)).toBeNull();
expect(await staffEmail(req('Bearer bad'), async () => null)).toBeNull();
expect(await staffEmail(req('Bearer err'), async () => { throw new Error('auth down'); })).toBeNull();
});
});
46 changes: 46 additions & 0 deletions src/lib/staff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { createClient } from '@supabase/supabase-js';

/**
* Staff mode (TDD FR-014). A caller is staff when its bearer token is a valid Supabase
* sign-in for an email on AEO_STAFF_EMAILS. Any doubt means public: no list, no token,
* a token that does not verify, or an auth error.
*/
export function staffList(): string[] {
return (process.env.AEO_STAFF_EMAILS ?? '')
.split(',')
.map(e => e.trim().toLowerCase())
.filter(Boolean);
}

type Verify = (token: string) => Promise<string | null>;

/** The token's email, checked server-side with the service client. */
const verifyWithSupabase: Verify = async (token) => {
const supabase = createClient(
(process.env.NEXT_PUBLIC_SUPABASE_URL ?? '').trim(),
(process.env.SUPABASE_SERVICE_ROLE_KEY ?? '').trim(),
{ auth: { autoRefreshToken: false, persistSession: false } },
);
const { data, error } = await supabase.auth.getUser(token);
return error ? null : data.user?.email ?? null;
};

/** The staff member's email, or null for a public caller. */
export async function staffEmail(
request: { headers: Headers },
verify: Verify = verifyWithSupabase,
): Promise<string | null> {
const list = staffList();
if (list.length === 0) return null;
const header = request.headers.get('authorization') ?? '';
if (!header.startsWith('Bearer ')) return null;
const token = header.slice('Bearer '.length).trim();
if (!token) return null;
try {
const email = (await verify(token))?.trim().toLowerCase();
return email && list.includes(email) ? email : null;
} catch (err) {
console.error('[staff] token check failed; treating the caller as public:', err);
return null;
}
}
24 changes: 24 additions & 0 deletions supabase/drafts/008_audit_requests_requested_by.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
-- =============================================================================
-- DRAFT 008: mark audits started by staff (TDD FR-014, task AEO-T-013)
-- =============================================================================
-- Additive and nullable: existing rows and the current code are unaffected.
-- Apply BEFORE setting AEO_STAFF_EMAILS in any environment: with staff configured,
-- the app writes requested_by = 'staff' on staff audits and counts only rows where
-- requested_by IS NULL toward the daily cap. Without the column those queries fail.

-- STEP 1 (read-only)
-- begin read only;
-- select column_name from information_schema.columns
-- where table_schema = 'public' and table_name = 'audit_requests' and column_name = 'requested_by'; [0 rows]
-- rollback;

-- STEP 2
SET lock_timeout = '3s';
ALTER TABLE public.audit_requests ADD COLUMN IF NOT EXISTS requested_by text;
COMMENT ON COLUMN public.audit_requests.requested_by IS
'NULL for public visitors; ''staff'' for audits started by an allow-listed staff sign-in.';

-- STEP 3 (read-only)
-- select data_type, is_nullable from information_schema.columns
-- where table_schema = 'public' and table_name = 'audit_requests' and column_name = 'requested_by'; [text, YES]
-- select count(*) from public.audit_requests where requested_by is not null; [0]