From 3ac1005663247fba97cd5a68b5ce9ec1ee81448d Mon Sep 17 00:00:00 2001 From: Razel De Jesus Date: Tue, 10 Nov 2026 20:34:00 +0800 Subject: [PATCH 1/5] 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 --- src/lib/staff.test.ts | 45 ++++++++++++++++++ src/lib/staff.ts | 46 +++++++++++++++++++ .../008_audit_requests_requested_by.sql | 24 ++++++++++ 3 files changed, 115 insertions(+) create mode 100644 src/lib/staff.test.ts create mode 100644 src/lib/staff.ts create mode 100644 supabase/drafts/008_audit_requests_requested_by.sql diff --git a/src/lib/staff.test.ts b/src/lib/staff.test.ts new file mode 100644 index 0000000..188013f --- /dev/null +++ b/src/lib/staff.test.ts @@ -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(); + }); +}); diff --git a/src/lib/staff.ts b/src/lib/staff.ts new file mode 100644 index 0000000..566f7e9 --- /dev/null +++ b/src/lib/staff.ts @@ -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; + +/** 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 { + 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; + } +} diff --git a/supabase/drafts/008_audit_requests_requested_by.sql b/supabase/drafts/008_audit_requests_requested_by.sql new file mode 100644 index 0000000..e05caad --- /dev/null +++ b/supabase/drafts/008_audit_requests_requested_by.sql @@ -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] From 2993c514ad45d1409b618e8e833143b30f34233d Mon Sep 17 00:00:00 2001 From: Razel De Jesus Date: Tue, 10 Nov 2026 20:38:27 +0800 Subject: [PATCH 2/5] feat(staff): staff unlock without the form (no lead, no CRM), Staff badge, token sent on audit start - unlock: an allow-listed staff sign-in gets the unlock cookie without name/email; no lead row, no HubSpot sync - report: a signed-in browser asks once; the server decides; public visitors unchanged - header: Staff badge after the server confirms (GET /api/staff, yes/no only) - audit form sends the sign-in token, for the run gate's staff rule Co-Authored-By: Claude Opus 5.5 --- .../api/audit/[auditId]/unlock/route.test.ts | 23 ++++++++++ src/app/api/audit/[auditId]/unlock/route.ts | 45 +++++++++++++------ src/app/api/staff/route.test.ts | 21 +++++++++ src/app/api/staff/route.ts | 10 +++++ src/components/aeo/AuditForm.tsx | 3 +- src/components/aeo/AuditResultPage.tsx | 25 +++++++++++ src/components/layout/Header.module.css | 13 ++++++ src/components/layout/Header.tsx | 3 ++ src/lib/staffClient.ts | 15 +++++++ src/lib/useStaff.ts | 25 +++++++++++ 10 files changed, 168 insertions(+), 15 deletions(-) create mode 100644 src/app/api/staff/route.test.ts create mode 100644 src/app/api/staff/route.ts create mode 100644 src/lib/staffClient.ts create mode 100644 src/lib/useStaff.ts diff --git a/src/app/api/audit/[auditId]/unlock/route.test.ts b/src/app/api/audit/[auditId]/unlock/route.test.ts index 5293bb1..1fd26e3 100644 --- a/src/app/api/audit/[auditId]/unlock/route.test.ts +++ b/src/app/api/audit/[auditId]/unlock/route.test.ts @@ -22,6 +22,9 @@ vi.mock('@/lib/hubspot', () => ({ syncAeoLead: syncMock, })); +const { staffMock } = vi.hoisted(() => ({ staffMock: vi.fn(async (): Promise => null) })); +vi.mock('@/lib/staff', () => ({ staffEmail: staffMock })); + vi.mock('@supabase/supabase-js', () => ({ createClient: () => ({ from: (table: string) => ({ @@ -168,6 +171,26 @@ describe('unlock checks the audit and proves the unlock', () => { expect(cookie.toLowerCase()).toContain('httponly'); }); + it('staff unlock: no name or email needed, no lead, no HubSpot, but the cookie is set (AC-020)', async () => { + process.env.AEO_UNLOCK_COOKIE_SECRET = 'test-value'; + ready(); + staffMock.mockResolvedValueOnce('staff@example.com'); + const { POST } = await import('./route'); + const res = await POST(makeRequest({}), ctx); + + expect(res.status).toBe(200); + expect(upsertMock).not.toHaveBeenCalled(); + expect(syncMock).not.toHaveBeenCalled(); + expect(res.headers.get('set-cookie') ?? '').toContain('aeo_unlock_audit-1='); + }); + + it('a public caller with an empty body is still refused', async () => { + ready(); + const { POST } = await import('./route'); + const res = await POST(makeRequest({}), ctx); + expect(res.status).toBe(400); + }); + it('sets no cookie when none is configured', async () => { ready(); const { POST } = await import('./route'); diff --git a/src/app/api/audit/[auditId]/unlock/route.ts b/src/app/api/audit/[auditId]/unlock/route.ts index 820d8a2..f490827 100644 --- a/src/app/api/audit/[auditId]/unlock/route.ts +++ b/src/app/api/audit/[auditId]/unlock/route.ts @@ -4,6 +4,7 @@ import { z } from 'zod'; import { syncAeoLead, type AeoLeadPayload } from '@/lib/hubspot'; import { checkRateLimit, getClientIp } from '@/lib/rateLimit'; import { unlockCookieName, unlockRefusal, unlockToken } from '@/lib/gate'; +import { staffEmail } from '@/lib/staff'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; @@ -81,22 +82,29 @@ export async function POST( console.error('[unlock] rate limit check failed; allowing the request:', err); } - let body: unknown; - try { - body = await request.json(); - } catch { - return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }); - } + // Staff (FR-014) see the full report without the form: no lead, no CRM sync. + const staff = await staffEmail(request); - const parsed = unlockSchema.safeParse(body); - if (!parsed.success) { - return NextResponse.json( - { error: parsed.error.issues[0].message }, - { status: 400 }, - ); + let name = ''; + let email = ''; + if (!staff) { + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }); + } + + const parsed = unlockSchema.safeParse(body); + if (!parsed.success) { + return NextResponse.json( + { error: parsed.error.issues[0].message }, + { status: 400 }, + ); + } + ({ name, email } = parsed.data); } - const { name, email } = parsed.data; const supabase = getSupabase(); // Fetch audit request + results in one go @@ -119,6 +127,11 @@ export async function POST( const notReady = unlockRefusal(auditId, audit.status, !!result); if (notReady) return NextResponse.json(notReady.body, { status: notReady.status }); + if (staff) { + console.log('[unlock] staff view for audit', auditId); + return withUnlockProof(NextResponse.json({ success: true, staff: true }), auditId); + } + // ── 1. Save lead to Supabase ────────────────────────────────────────── const { error: leadError } = await supabase.from('leads').upsert( { @@ -215,7 +228,11 @@ export async function POST( console.warn('[unlock] No audit results found for HubSpot sync — audit may still be processing'); } - const res = NextResponse.json({ success: true }); + return withUnlockProof(NextResponse.json({ success: true }), auditId); +} + +/** Sets the signed per-audit unlock cookie when a cookie key is configured. */ +function withUnlockProof(res: NextResponse, auditId: string): NextResponse { const proof = unlockToken(auditId); if (proof) { res.cookies.set(unlockCookieName(auditId), proof, { diff --git a/src/app/api/staff/route.test.ts b/src/app/api/staff/route.test.ts new file mode 100644 index 0000000..0a56b79 --- /dev/null +++ b/src/app/api/staff/route.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect, vi } from 'vitest'; + +const { staffMock } = vi.hoisted(() => ({ staffMock: vi.fn(async (): Promise => null) })); +vi.mock('@/lib/staff', () => ({ staffEmail: staffMock })); + +import { GET } from './route'; + +async function ask() { + const { NextRequest } = await import('next/server'); + return (await GET(new NextRequest('http://localhost:3000/api/staff'))).json(); +} + +describe('GET /api/staff', () => { + it('answers yes or no and never returns the email', async () => { + expect(await ask()).toEqual({ staff: false }); + staffMock.mockResolvedValueOnce('staff@example.com'); + const body = await ask(); + expect(body).toEqual({ staff: true }); + expect(JSON.stringify(body)).not.toContain('@'); + }); +}); diff --git a/src/app/api/staff/route.ts b/src/app/api/staff/route.ts new file mode 100644 index 0000000..53a1aee --- /dev/null +++ b/src/app/api/staff/route.ts @@ -0,0 +1,10 @@ +import { NextResponse, type NextRequest } from 'next/server'; +import { staffEmail } from '@/lib/staff'; + +export const runtime = 'nodejs'; +export const dynamic = 'force-dynamic'; + +/** GET: is this browser's sign-in on the staff list? Only a yes/no, never the list. */ +export async function GET(request: NextRequest): Promise { + return NextResponse.json({ staff: (await staffEmail(request)) !== null }); +} diff --git a/src/components/aeo/AuditForm.tsx b/src/components/aeo/AuditForm.tsx index 47dac2c..8986e66 100644 --- a/src/components/aeo/AuditForm.tsx +++ b/src/components/aeo/AuditForm.tsx @@ -2,6 +2,7 @@ import { useState, useRef, type FormEvent } from 'react'; import styles from './AuditForm.module.css'; +import { staffAuthHeader } from '@/lib/staffClient'; function ArrowIcon() { return ( @@ -62,7 +63,7 @@ export function AuditForm() { }; const res = await fetch('/api/audit/start', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...(await staffAuthHeader()) }, body: JSON.stringify({ url: `https://${clean}`, ...utm }), }); const data = await res.json(); diff --git a/src/components/aeo/AuditResultPage.tsx b/src/components/aeo/AuditResultPage.tsx index d1b2f93..b864639 100644 --- a/src/components/aeo/AuditResultPage.tsx +++ b/src/components/aeo/AuditResultPage.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useRouter } from 'next/navigation'; +import { staffAuthHeader } from '@/lib/staffClient'; import { OpenAIIcon, PerplexityIcon, GoogleAIIcon, ClaudeIcon } from '@/components/aeo/EngineIcons'; import { engineBadge } from '@/lib/auditor/engineBadge'; import styles from './AuditResultPage.module.css'; @@ -304,6 +305,30 @@ export default function AuditResultPage({ requestData, auditData, locked = false } }, [requestData.id, locked]); + // Staff (FR-014): a signed-in, allow-listed browser opens the full report without the form. + // The server checks the token; a public visitor's empty request is refused and ignored. + useEffect(() => { + let live = true; + (async () => { + const auth = await staffAuthHeader(); + if (!auth.Authorization) return; + try { + const res = await fetch(`/api/audit/${requestData.id}/unlock`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...auth }, + body: '{}', + }); + const data = (await res.json()) as { staff?: boolean }; + if (!live || !res.ok || !data.staff) return; + setUnlocked(true); + if (locked) router.refresh(); + } catch { + // stays on the public view + } + })(); + return () => { live = false; }; + }, [requestData.id, locked, router]); + const handleUnlock = async () => { if (!gateName.trim()) { setGateError('Please enter your full name'); return; } const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(gateEmail.trim()); diff --git a/src/components/layout/Header.module.css b/src/components/layout/Header.module.css index 4f18910..2b48491 100644 --- a/src/components/layout/Header.module.css +++ b/src/components/layout/Header.module.css @@ -34,6 +34,19 @@ width: auto; } +/* Shown only to signed-in staff; sits next to the logo, pushing the nav right. */ +.staffBadge { + margin-right: auto; + padding: 2px 8px; + border: 1px solid var(--primary); + border-radius: var(--radius-full); + font-size: 12px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--primary); +} + /* ── Nav ── */ .nav { display: flex; diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx index 0d9e4b8..1197c18 100644 --- a/src/components/layout/Header.tsx +++ b/src/components/layout/Header.tsx @@ -2,11 +2,13 @@ import Link from 'next/link'; import { usePathname } from 'next/navigation'; +import { useStaff } from '@/lib/useStaff'; import styles from './Header.module.css'; export function Header() { const pathname = usePathname(); const isHomepage = pathname === '/'; + const staff = useStaff(); return (
@@ -20,6 +22,7 @@ export function Header() { className={styles.logoImg} /> + {staff && Staff} {isHomepage && (