Skip to content
Closed
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
Prev Previous commit
Next Next commit
feat(staff): staff skip the daily cap and staff_only; staff audits ma…
…rked and left out of the count

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
razel-hash and claude committed Nov 10, 2026
commit c343b30671f397272faa9f9dfb18faeb5dd19711
49 changes: 45 additions & 4 deletions src/app/api/audit/start/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
const { rateLimitMock, supabaseInsertMock, today } = vi.hoisted(() => ({
rateLimitMock: vi.fn(),
supabaseInsertMock: vi.fn(),
today: { count: 0, since: '' },
today: { count: 0, since: '', publicOnly: false },
}));

const { staffMock } = vi.hoisted(() => ({ staffMock: vi.fn(async (): Promise<string | null> => null) }));
vi.mock('@/lib/staff', async (orig) => ({
...(await orig<typeof import('@/lib/staff')>()),
staffEmail: staffMock,
}));

vi.mock('@/lib/rateLimit', () => ({
Expand All @@ -16,9 +22,21 @@ vi.mock('@/lib/rateLimit', () => ({
vi.mock('@supabase/supabase-js', () => ({
createClient: () => ({
from: () => ({
select: () => ({
gte: async (_col: string, since: string) => { today.since = since; return { count: today.count, error: null }; },
}),
select: () => {
const result = () => ({ count: today.count, error: null });
return {
gte: (_col: string, since: string) => {
today.since = since;
const p = Promise.resolve(result());
return Object.assign(p, {
is: async (col: string, v: unknown) => {
if (col === 'requested_by' && v === null) today.publicOnly = true;
return result();
},
});
},
};
},
insert: (...args: unknown[]) => {
supabaseInsertMock(...args);
return {
Expand Down Expand Up @@ -141,6 +159,29 @@ describe('POST /api/audit/start daily cap', () => {
expect(res.status).toBe(201);
});

it('staff: at the cap, the audit starts and is marked as a staff audit (AC-019)', async () => {
process.env.AEO_GATE_MODE = 'enforce';
process.env.AEO_STAFF_EMAILS = 'staff@example.com';
today.count = 3;
staffMock.mockResolvedValueOnce('staff@example.com');
const { POST } = await import('./route');
const res = await POST(makeRequest({ url: 'https://example.com' }, { authorization: 'Bearer t' }));
delete process.env.AEO_STAFF_EMAILS;
expect(res.status).toBe(201);
expect(supabaseInsertMock).toHaveBeenCalledWith(expect.objectContaining({ requested_by: 'staff' }));
});

it('with staff configured, the daily count leaves staff audits out', async () => {
process.env.AEO_GATE_MODE = 'enforce';
process.env.AEO_STAFF_EMAILS = 'staff@example.com';
today.publicOnly = false;
const { POST } = await import('./route');
await POST(makeRequest({ url: 'https://example.com' }));
delete process.env.AEO_STAFF_EMAILS;
expect(today.publicOnly).toBe(true);
expect(supabaseInsertMock).toHaveBeenCalledWith(expect.not.objectContaining({ requested_by: expect.anything() }));
});

it('observe: at the cap, logs and still starts the audit', async () => {
process.env.AEO_GATE_MODE = 'observe';
today.count = 3;
Expand Down
10 changes: 8 additions & 2 deletions src/app/api/audit/start/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { checkRateLimit, getClientIp } from '@/lib/rateLimit';
import { isBlockedHost } from '@/lib/safeFetch';
import { inngest } from '@/lib/inngest/client';
import { runGate, startOfUtcDay } from '@/lib/gate';
import { staffEmail, staffList } from '@/lib/staff';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
Expand Down Expand Up @@ -52,14 +53,18 @@ export async function POST(request: NextRequest): Promise<Response> {
const ip = getClientIp(request);

try {
const staff = (await staffEmail(request)) !== null;
// requested_by exists only once draft 008 is applied, which comes before AEO_STAFF_EMAILS is set.
const staffConfigured = staffList().length > 0;
const refused = await runGate(async () => {
const { count, error } = await getSupabase()
const q = getSupabase()
.from('audit_requests')
.select('id', { count: 'exact', head: true })
.gte('created_at', startOfUtcDay());
const { count, error } = await (staffConfigured ? q.is('requested_by', null) : q);
if (error) throw error;
return count ?? 0;
});
}, { staff });
if (refused) return NextResponse.json(refused.body, { status: refused.status });

try {
Expand Down Expand Up @@ -120,6 +125,7 @@ export async function POST(request: NextRequest): Promise<Response> {
utm_campaign: parsed.data.utm_campaign || null,
utm_content: parsed.data.utm_content || null,
utm_term: parsed.data.utm_term || null,
...(staff ? { requested_by: 'staff' } : {}),
})
.select('id')
.single();
Expand Down
9 changes: 9 additions & 0 deletions src/lib/gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@ describe('run gate', () => {
err.mockRestore();
});

it('staff skip the daily cap and staff_only (AC-019); pause still applies', async () => {
healthy('enforce');
expect(await runGate(async () => 50, { staff: true })).toBeNull();
process.env.AEO_PUBLIC_ACCESS = 'staff_only';
expect(await runGate(async () => 0, { staff: true })).toBeNull();
process.env.AEO_AUDITS_PAUSED = 'true';
expect((await runGate(async () => 0, { staff: true }))?.body.code).toBe('PAUSED');
});

it('observe logs what it would refuse and refuses nothing', async () => {
healthy('observe');
expect(await runGate(async () => 50)).toBeNull();
Expand Down
13 changes: 9 additions & 4 deletions src/lib/gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,14 @@ export function startOfUtcDay(now = new Date()): string {
}

/**
* Rules in order, first failure wins. Every caller is public until staff sign-in exists.
* Rules in order, first failure wins. Staff (a verified allow-listed sign-in, lib/staff.ts)
* skip the public-only rules: staff_only and the daily cap.
* `countToday` is only called when the earlier rules pass and a cap applies.
*/
export async function runGate(countToday: () => Promise<number>): Promise<Refusal | null> {
export async function runGate(
countToday: () => Promise<number>,
{ staff = false }: { staff?: boolean } = {},
): Promise<Refusal | null> {
const env = process.env;
const mode = gateMode();
if ((env.AEO_AUDITS_PAUSED ?? '').trim() === 'true') {
Expand All @@ -140,20 +144,21 @@ export async function runGate(countToday: () => Promise<number>): Promise<Refusa
}
if (mode === 'off') return null;

const code = await firstFailingRule(countToday, mode);
const code = await firstFailingRule(countToday, mode, staff);
if (!code) return null;
logGate(mode, mode === 'enforce' ? 'refuse' : 'would-refuse', code);
return mode === 'enforce' ? refusal(code) : null;
}

async function firstFailingRule(countToday: () => Promise<number>, mode: GateMode): Promise<string | null> {
async function firstFailingRule(countToday: () => Promise<number>, mode: GateMode, staff: boolean): Promise<string | null> {
const env = process.env;
const has = (k: string) => !!(env[k] ?? '').trim();
if (!has('NEXT_PUBLIC_SUPABASE_URL') || !has('SUPABASE_SERVICE_ROLE_KEY') || !has('ANTHROPIC_API_KEY')
|| !(has('INNGEST_EVENT_KEY') || has('INTERNAL_CRAWLER_SECRET'))
// Without it no visitor can ever unlock, so enforce would show previews only.
|| !has('AEO_UNLOCK_COOKIE_SECRET')) return 'CONFIG_MISSING';
if (env.VERCEL_ENV !== 'production' && (env.AEO_PREVIEW_DB_ISOLATED ?? '').trim() !== 'true') return 'PREVIEW_SHARED_DB';
if (staff) return null;
if ((env.AEO_PUBLIC_ACCESS ?? '').trim() === 'staff_only') return 'STAFF_ONLY';

const cap = dailyCap();
Expand Down