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/audit/start/route.test.ts b/src/app/api/audit/start/route.test.ts index 691dabc..a0ddfbb 100644 --- a/src/app/api/audit/start/route.test.ts +++ b/src/app/api/audit/start/route.test.ts @@ -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 => null) })); +vi.mock('@/lib/staff', async (orig) => ({ + ...(await orig()), + staffEmail: staffMock, })); vi.mock('@/lib/rateLimit', () => ({ @@ -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 { @@ -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; diff --git a/src/app/api/audit/start/route.ts b/src/app/api/audit/start/route.ts index e38697a..96b4c08 100644 --- a/src/app/api/audit/start/route.ts +++ b/src/app/api/audit/start/route.ts @@ -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'; @@ -52,14 +53,18 @@ export async function POST(request: NextRequest): Promise { 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 { @@ -120,6 +125,7 @@ export async function POST(request: NextRequest): Promise { 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(); 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 986db66..5e148cf 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 styles from './AuditResultPage.module.css'; @@ -301,6 +302,33 @@ 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 { + // Ask first, so a signed-in non-staff browser spends none of the unlock budget. + const who = (await (await fetch('/api/staff', { headers: auth })).json()) as { staff?: boolean }; + if (!who.staff) return; + 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 && (