diff --git a/CLAUDE.md b/CLAUDE.md index 876e851..a215bf8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,9 +26,10 @@ security issues in code, comments, tests, commits, PRs or docs. Use neutral word - `supabase/migrations/` (applied by hand, in order); `supabase/drafts/` are not applied. ## Rules -- The gate ships dark: `AEO_GATE_MODE` unset means off (today's behaviour); `observe` logs - `[gate] observe ...` lines and refuses nothing; `enforce` refuses. Gate env values in - Vercel are set by the owner, never by an agent. +- Two switches. Report access (`AEO_REPORT_GATE`) is on unless set to `off` or `observe`. + The run gate (`AEO_GATE_MODE`) is off unless set; `observe` logs `[gate] observe ...` + lines and refuses nothing; `enforce` refuses. Gate env values in Vercel are set by the + owner, never by an agent. - Previews use the production database and HubSpot (docs/deploy.md): never submit the audit or unlock forms on a preview. Tests mock every external service. - Migrations alter in place: `IF NOT EXISTS`, no `DROP`. diff --git a/docs/guides/aeo-auditor.md b/docs/guides/aeo-auditor.md index bd577ac..7aada32 100644 --- a/docs/guides/aeo-auditor.md +++ b/docs/guides/aeo-auditor.md @@ -15,19 +15,39 @@ An engine whose key is missing, or which fails every question, is left out of the citation rate and shows as "coming soon" or "unavailable". It never counts as "not cited". -## The gate (`AEO_GATE_MODE`) +## Report access (`AEO_REPORT_GATE`) +On by default. Without the per-audit unlock cookie, the report page, the status API and the +print view send only the preview (overall score and grade, date, AI citation count; the +status API also sends up to three short preview tips), and custom questions are refused. An unlock is accepted only for a finished audit with results, +only with a real-looking work email (reserved example and test domains are refused), and +writes nothing new when the same email unlocks the same audit again. One audit accepts at +most five different emails. Staff unlock without the form (signed in, on +`AEO_STAFF_EMAILS`); their unlock lasts the browser session. Anyone else who opens a report +link, a CC rep from the CRM included, sees the preview until they unlock. + +| Value | What happens | +|---|---| +| unset / `enforce` / anything else | The rules above apply. | +| `observe` | The rules are logged as `[gate] observe would-refuse REPORT_LOCKED` or `UNLOCK_NOT_READY`, and nothing is refused. | +| `off` | Everyone gets the full report. The off switch, for an emergency. | + +The cookie is signed with `AEO_UNLOCK_COOKIE_SECRET` when it is set, otherwise with a key +derived from the server's database key. Changing either key asks visitors to unlock again. + +## The run gate (`AEO_GATE_MODE`) | Mode | What happens | |---|---| -| unset / `off` | Today's behaviour. Only `AEO_AUDITS_PAUSED=true` refuses anything. | +| unset / `off` | Only `AEO_AUDITS_PAUSED=true` refuses anything. | | `observe` | Every rule is checked and logged as `[gate] observe would-refuse `, together with `[gate] observe count ` (today's audits). Nothing is refused. | -| `enforce` | The rules refuse: a full report, the print view and custom questions need the unlock cookie; unlocks need a finished audit; new audits stop at the daily cap. | +| `enforce` | The rules refuse: new audits stop at the daily cap, on previews that share the database, and when required settings are missing. | Settings, all in Vercel → project → Settings → Environment Variables (the owner sets them): | Name | Purpose | |---|---| -| `AEO_GATE_MODE` | `off` / `observe` / `enforce` | -| `AEO_UNLOCK_COOKIE_SECRET` | Signs the per-audit unlock cookie. Without it, `enforce` refuses new audits (fails closed). | +| `AEO_REPORT_GATE` | Report access: `enforce` (default) / `observe` / `off` | +| `AEO_GATE_MODE` | Run gate: `off` (default) / `observe` / `enforce` | +| `AEO_UNLOCK_COOKIE_SECRET` | Optional. Signs the per-audit unlock cookie; without it a derived key is used. | | `AEO_DAILY_AUDIT_CAP` | Audits per UTC day. Without it, `enforce` refuses new audits. | | `AEO_PREVIEW_DB_ISOLATED` | `true` only when a preview has its own database. Otherwise `enforce` refuses audits on previews. | | `AEO_AUDITS_PAUSED` | `true` stops new audits and custom questions in every mode. | @@ -43,8 +63,8 @@ Refusal codes in the logs: `PAUSED`, `CONFIG_MISSING`, `PREVIEW_SHARED_DB`, `STA present or absent and the mode. It never prints a value. - Vercel → project → Logs, then search for `[gate]`. -## Rolling out -1. Set `AEO_GATE_MODE=observe`, the cookie secret and the cap on Production, then redeploy. +## Rolling out the run gate +1. Set `AEO_GATE_MODE=observe` and the cap on Production, then redeploy. 2. After about a week, compare the `would-refuse` lines with real leads. 3. With the owner's go, set `enforce`. To roll back, set `off`. diff --git a/scripts/gate-check.mjs b/scripts/gate-check.mjs index badbb40..bd69df2 100644 --- a/scripts/gate-check.mjs +++ b/scripts/gate-check.mjs @@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url'; const NAMES = [ - 'AEO_GATE_MODE', 'AEO_AUDITS_PAUSED', 'AEO_PREVIEW_DB_ISOLATED', 'AEO_PUBLIC_ACCESS', + 'AEO_GATE_MODE', 'AEO_REPORT_GATE', 'AEO_AUDITS_PAUSED', 'AEO_PREVIEW_DB_ISOLATED', 'AEO_PUBLIC_ACCESS', 'AEO_DAILY_AUDIT_CAP', 'AEO_UNLOCK_COOKIE_SECRET', 'AEO_STAFF_EMAILS', 'AEO_HUBSPOT_SYNC', 'NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY', 'ANTHROPIC_API_KEY', 'INNGEST_EVENT_KEY', 'INTERNAL_CRAWLER_SECRET', 'HUBSPOT_PRIVATE_APP_TOKEN', 'VERCEL_ENV', @@ -14,9 +14,11 @@ const NAMES = [ export function report(env) { const m = String(env.AEO_GATE_MODE ?? '').trim().toLowerCase(); const mode = m === 'observe' || m === 'enforce' ? m : 'off'; + const r = String(env.AEO_REPORT_GATE ?? '').trim().toLowerCase(); + const reportGate = r === 'off' || r === 'observe' ? r : 'enforce'; const width = Math.max(...NAMES.map(n => n.length)); const lines = NAMES.map(n => `${n.padEnd(width)} ${String(env[n] ?? '').trim() ? 'present' : 'absent'}`); - return [`mode: ${mode}`, ...lines].join('\n'); + return [`mode: ${mode}`, `report gate: ${reportGate}`, ...lines].join('\n'); } async function todaysCount(env) { diff --git a/src/app/api/audit/[auditId]/custom-prompts/route.test.ts b/src/app/api/audit/[auditId]/custom-prompts/route.test.ts index 2a9d4b8..50a23b7 100644 --- a/src/app/api/audit/[auditId]/custom-prompts/route.test.ts +++ b/src/app/api/audit/[auditId]/custom-prompts/route.test.ts @@ -159,6 +159,8 @@ beforeEach(() => { delete process.env.CUSTOM_PROMPTS_GLOBAL_MAX; delete process.env.AEO_GATE_MODE; delete process.env.AEO_UNLOCK_COOKIE_SECRET; + // The budget specs below are about spending, not access; access has its own block. + process.env.AEO_REPORT_GATE = 'off'; }); describe('custom prompts follow report access', () => { @@ -170,7 +172,7 @@ describe('custom prompts follow report access', () => { beforeEach(() => { process.env.AEO_GATE_MODE = 'enforce'; - process.env.AEO_UNLOCK_COOKIE_SECRET = 'test-value'; + delete process.env.AEO_REPORT_GATE; vi.spyOn(console, 'log').mockImplementation(() => {}); }); @@ -209,7 +211,8 @@ describe('custom prompts follow report access', () => { expect(engineCalls()).toBe(0); }); - it('observe: runs as today without the cookie', async () => { + it('report gate observe: runs without the cookie', async () => { + process.env.AEO_REPORT_GATE = 'observe'; process.env.AEO_GATE_MODE = 'observe'; addAudit(AUDIT_ID); const res = await call(AUDIT_ID); diff --git a/src/app/api/audit/[auditId]/status/route.test.ts b/src/app/api/audit/[auditId]/status/route.test.ts index 640a36d..8f13d8c 100644 --- a/src/app/api/audit/[auditId]/status/route.test.ts +++ b/src/app/api/audit/[auditId]/status/route.test.ts @@ -44,24 +44,30 @@ beforeEach(() => { process.env.AEO_UNLOCK_COOKIE_SECRET = 'test-value'; vi.spyOn(console, 'log').mockImplementation(() => {}); }); -afterEach(() => { delete process.env.AEO_GATE_MODE; delete process.env.AEO_UNLOCK_COOKIE_SECRET; }); +afterEach(() => { delete process.env.AEO_REPORT_GATE; delete process.env.AEO_UNLOCK_COOKIE_SECRET; }); describe('GET /api/audit/[auditId]/status', () => { it('enforce without an unlock returns only the overall score', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const body = await get(); expect(body.status).toBe('complete'); expect(body.categories).toEqual({ overall: { score: 61, grade: 'B' } }); }); it('enforce with the unlock cookie returns every category', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const { unlockToken, unlockCookieName } = await import('@/lib/gate'); const body = await get(`${unlockCookieName(AUDIT)}=${unlockToken(AUDIT)}`); expect(body.categories.trust).toEqual({ score: 53, grade: 'C' }); }); - it('off returns every category, as today', async () => { + it('unset is enforce: only the overall score', async () => { + const body = await get(); + expect(body.categories).toEqual({ overall: { score: 61, grade: 'B' } }); + }); + + it('off returns every category', async () => { + process.env.AEO_REPORT_GATE = 'off'; const body = await get(); expect(body.categories.trust).toEqual({ score: 53, grade: 'C' }); }); diff --git a/src/app/api/audit/[auditId]/unlock/route.test.ts b/src/app/api/audit/[auditId]/unlock/route.test.ts index 09ef6bb..1caf4db 100644 --- a/src/app/api/audit/[auditId]/unlock/route.test.ts +++ b/src/app/api/audit/[auditId]/unlock/route.test.ts @@ -1,6 +1,7 @@ -// The unlock endpoint is public and unauthenticated, and every call writes a lead row and -// a HubSpot contact. These cover the budget that now sits in front of it — and the -// deliberate decision to let a real capture through when the limiter itself is broken. +// The unlock endpoint is public and unauthenticated, and a call can write a lead row and +// a HubSpot contact. These cover the budget that sits in front of it, the deliberate +// decision to let a real capture through when the limiter itself is broken, and the +// checks on which audits and which details it accepts. import { describe, it, expect, beforeEach, vi } from 'vitest'; @@ -8,7 +9,12 @@ const { rateLimitMock, syncMock, upsertMock, db } = vi.hoisted(() => ({ rateLimitMock: vi.fn(), syncMock: vi.fn(), upsertMock: vi.fn(), - db: { request: {} as Record, result: null as unknown }, + db: { + request: {} as Record, + result: null as unknown, + leads: [] as Array>, + failLeadCount: false, + }, })); vi.mock('@/lib/rateLimit', () => ({ @@ -23,14 +29,25 @@ vi.mock('@/lib/hubspot', () => ({ const { staffMock } = vi.hoisted(() => ({ staffMock: vi.fn(async (): Promise => null) })); vi.mock('@/lib/staff', () => ({ staffEmail: staffMock })); +/** A `leads` count query: `.eq()` filters chain, awaiting gives `{ count, error }`. */ +function leadCount(filters: Array<[string, string]> = []): unknown { + const run = () => db.failLeadCount + ? { count: null, error: { message: 'down' } } + : { count: db.leads.filter(l => filters.every(([c, v]) => l[c] === v)).length, error: null }; + return { + eq: (c: string, v: string) => leadCount([...filters, [c, v]]), + then: (ok: (v: unknown) => unknown, bad?: (e: unknown) => unknown) => Promise.resolve(run()).then(ok, bad), + }; +} + vi.mock('@supabase/supabase-js', () => ({ createClient: () => ({ from: (table: string) => ({ - select: () => ({ + select: () => table === 'leads' ? leadCount() : ({ eq: () => ({ maybeSingle: async () => table === 'audit_requests' - ? { data: { id: 'audit-1', url: 'https://example.com', created_at: '2026-09-01T00:00:00Z', ...db.request } } + ? { data: { id: AUDIT, url: 'https://example.com', created_at: '2026-09-01T00:00:00Z', ...db.request } } : { data: db.result }, }), }), @@ -43,25 +60,35 @@ vi.mock('@supabase/supabase-js', () => ({ }), })); -function makeRequest(body: unknown) { - return new Request('http://localhost:3000/api/audit/audit-1/unlock', { +const AUDIT = '22222222-2222-4222-8222-222222222222'; + +function makeRequest(body: unknown, id = AUDIT) { + return new Request(`http://localhost:3000/api/audit/${id}/unlock`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.7' }, body: JSON.stringify(body), }) as unknown as import('next/server').NextRequest; } -const ctx = { params: Promise.resolve({ auditId: 'audit-1' }) }; -const validBody = { name: 'Ada Lovelace', email: 'ada@example.com' }; +const ctxFor = (auditId: string) => ({ params: Promise.resolve({ auditId }) }); +const ctx = ctxFor(AUDIT); +const validBody = { name: 'Ada Lovelace', email: 'ada@acme-widgets.com' }; +const ready = () => { db.request = { status: 'complete' }; db.result = { overall_score: 50, raw_findings: null }; }; beforeEach(() => { vi.resetModules(); rateLimitMock.mockReset(); syncMock.mockReset(); upsertMock.mockReset(); + staffMock.mockReset(); + staffMock.mockResolvedValue(null); db.request = {}; db.result = null; + db.leads = []; + db.failLeadCount = false; + ready(); delete process.env.AEO_GATE_MODE; + delete process.env.AEO_REPORT_GATE; delete process.env.AEO_UNLOCK_COOKIE_SECRET; rateLimitMock.mockResolvedValue({ limited: false }); syncMock.mockResolvedValue({ id: 'contact-1' }); @@ -94,9 +121,10 @@ describe('POST /api/audit/[auditId]/unlock', () => { expect(res.status).toBe(200); expect(upsertMock).toHaveBeenCalledWith( - expect.objectContaining({ email: 'ada@example.com', name: 'Ada Lovelace' }), + expect.objectContaining({ email: 'ada@acme-widgets.com', name: 'Ada Lovelace' }), expect.anything(), ); + expect(syncMock).toHaveBeenCalledTimes(1); }); it('fails open: a broken limiter must not cost a real lead', async () => { @@ -118,10 +146,7 @@ describe('POST /api/audit/[auditId]/unlock', () => { }); describe('unlock checks the audit and proves the unlock', () => { - const ready = () => { db.request = { status: 'complete' }; db.result = { overall_score: 50, raw_findings: null }; }; - - it('enforce: an audit that is not finished writes no lead', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + it('an audit that is not finished writes no lead (default, nothing set)', async () => { db.request = { status: 'pending' }; const { POST } = await import('./route'); const res = await POST(makeRequest(validBody), ctx); @@ -131,9 +156,15 @@ describe('unlock checks the audit and proves the unlock', () => { expect(syncMock).not.toHaveBeenCalled(); }); - it('enforce: a finished audit without results writes no lead', async () => { - process.env.AEO_GATE_MODE = 'enforce'; - db.request = { status: 'complete' }; + it('a failed audit writes no lead', async () => { + db.request = { status: 'failed' }; + const { POST } = await import('./route'); + expect((await POST(makeRequest(validBody), ctx)).status).toBe(409); + expect(upsertMock).not.toHaveBeenCalled(); + }); + + it('a finished audit without results writes no lead', async () => { + db.result = null; const { POST } = await import('./route'); const res = await POST(makeRequest(validBody), ctx); @@ -141,8 +172,8 @@ describe('unlock checks the audit and proves the unlock', () => { expect(upsertMock).not.toHaveBeenCalled(); }); - it('observe: an unfinished audit is logged, and the lead is still written', async () => { - process.env.AEO_GATE_MODE = 'observe'; + it('report gate observe: an unfinished audit is logged, and the lead is still written', async () => { + process.env.AEO_REPORT_GATE = 'observe'; db.request = { status: 'failed' }; const log = vi.spyOn(console, 'log').mockImplementation(() => {}); const { POST } = await import('./route'); @@ -155,9 +186,7 @@ describe('unlock checks the audit and proves the unlock', () => { }); it('a finished audit unlocks and sets an httpOnly proof cookie for that audit', async () => { - process.env.AEO_GATE_MODE = 'enforce'; process.env.AEO_UNLOCK_COOKIE_SECRET = 'test-value'; - ready(); const { POST } = await import('./route'); const { unlockToken } = await import('@/lib/gate'); const res = await POST(makeRequest(validBody), ctx); @@ -165,13 +194,20 @@ describe('unlock checks the audit and proves the unlock', () => { expect(res.status).toBe(200); expect(upsertMock).toHaveBeenCalled(); const cookie = res.headers.get('set-cookie') ?? ''; - expect(cookie).toContain(`aeo_unlock_audit-1=${unlockToken('audit-1')}`); + expect(cookie).toContain(`aeo_unlock_${AUDIT}=${unlockToken(AUDIT)}`); expect(cookie.toLowerCase()).toContain('httponly'); }); + it('sets the proof cookie with no dedicated key configured', async () => { + const { POST } = await import('./route'); + const { unlockToken } = await import('@/lib/gate'); + const res = await POST(makeRequest(validBody), ctx); + + expect(res.status).toBe(200); + expect(res.headers.get('set-cookie') ?? '').toContain(`aeo_unlock_${AUDIT}=${unlockToken(AUDIT)}`); + }); + 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); @@ -179,22 +215,98 @@ describe('unlock checks the audit and proves the unlock', () => { expect(res.status).toBe(200); expect(upsertMock).not.toHaveBeenCalled(); expect(syncMock).not.toHaveBeenCalled(); - expect(res.headers.get('set-cookie') ?? '').toContain('aeo_unlock_audit-1='); + expect(res.headers.get('set-cookie') ?? '').toContain(`aeo_unlock_${AUDIT}=`); + }); + + it('staff cookies last the browser session only (staff unlock again on each visit)', async () => { + staffMock.mockResolvedValueOnce('staff@example.com'); + const { POST } = await import('./route'); + const cookie = ((await POST(makeRequest({}), ctx)).headers.get('set-cookie') ?? '').toLowerCase(); + expect(cookie).toContain(`aeo_unlock_${AUDIT}=`); + expect(cookie).not.toContain('max-age'); + expect(cookie).not.toContain('expires'); }); 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(); +describe('unlock accepts only real ids and real details', () => { + it('refuses an id that is not an audit id, before touching the database', async () => { const { POST } = await import('./route'); - const res = await POST(makeRequest(validBody), ctx); + const res = await POST(makeRequest(validBody, 'not-an-id'), ctxFor('not-an-id')); + + expect(res.status).toBe(400); + expect(upsertMock).not.toHaveBeenCalled(); + expect(syncMock).not.toHaveBeenCalled(); + }); + + it.each(['someone@example.com', 'a@b.example.org', 'x@host.test', 'x@site.invalid', 'x@box.localhost'])( + 'refuses a reserved address (%s)', async (email) => { + const { POST } = await import('./route'); + const res = await POST(makeRequest({ name: 'Test', email }), ctx); + + expect(res.status).toBe(400); + expect(upsertMock).not.toHaveBeenCalled(); + expect(syncMock).not.toHaveBeenCalled(); + }, + ); + + it('the same email on the same audit again: no new write, no CRM call, still unlocked', async () => { + db.leads = [{ audit_request_id: AUDIT, email: 'ada@acme-widgets.com' }]; + const { POST } = await import('./route'); + const res = await POST(makeRequest({ ...validBody, email: 'ADA@acme-widgets.com' }), ctx); expect(res.status).toBe(200); + expect(upsertMock).not.toHaveBeenCalled(); + expect(syncMock).not.toHaveBeenCalled(); + expect(res.headers.get('set-cookie') ?? '').toContain(`aeo_unlock_${AUDIT}=`); + }); + + it('refuses a new email once an audit already has the most leads it accepts', async () => { + db.leads = Array.from({ length: 5 }, (_, i) => ({ audit_request_id: AUDIT, email: `p${i}@acme-widgets.com` })); + const { POST } = await import('./route'); + const res = await POST(makeRequest(validBody), ctx); + + expect(res.status).toBe(429); + expect(upsertMock).not.toHaveBeenCalled(); + expect(syncMock).not.toHaveBeenCalled(); + expect(res.headers.get('set-cookie')).toBeNull(); + }); + + it('requests that pass the limit together: the ones past it get no CRM call and no access', async () => { + db.leads = Array.from({ length: 4 }, (_, i) => ({ audit_request_id: AUDIT, email: `p${i}@acme-widgets.com` })); + // Two other readers are written between this request's check and its own write. + upsertMock.mockImplementation((row: Record) => { + db.leads.push({ audit_request_id: AUDIT, email: 'q1@acme-widgets.com' }, { audit_request_id: AUDIT, email: 'q2@acme-widgets.com' }); + db.leads.push({ audit_request_id: row.audit_request_id, email: row.email }); + }); + const { POST } = await import('./route'); + const res = await POST(makeRequest(validBody), ctx); + + expect(res.status).toBe(429); + expect(syncMock).not.toHaveBeenCalled(); expect(res.headers.get('set-cookie')).toBeNull(); }); + + it('leads on other audits do not count toward that limit', async () => { + db.leads = Array.from({ length: 5 }, (_, i) => ({ audit_request_id: 'other', email: `p${i}@acme-widgets.com` })); + const { POST } = await import('./route'); + expect((await POST(makeRequest(validBody), ctx)).status).toBe(200); + expect(upsertMock).toHaveBeenCalled(); + }); + + it('fails open when the lead check cannot run: the capture still happens', async () => { + db.failLeadCount = true; + const err = vi.spyOn(console, 'error').mockImplementation(() => {}); + const { POST } = await import('./route'); + const res = await POST(makeRequest(validBody), ctx); + err.mockRestore(); + + expect(res.status).toBe(200); + expect(upsertMock).toHaveBeenCalled(); + }); }); diff --git a/src/app/api/audit/[auditId]/unlock/route.ts b/src/app/api/audit/[auditId]/unlock/route.ts index 7bc3f73..0589505 100644 --- a/src/app/api/audit/[auditId]/unlock/route.ts +++ b/src/app/api/audit/[auditId]/unlock/route.ts @@ -17,11 +17,28 @@ function getSupabase() { ); } +const UUID_REGEX = + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +/** Domains reserved for examples and testing (RFC 2606 / 6761): never a real contact. */ +function isReservedEmailDomain(email: string): boolean { + const domain = email.slice(email.lastIndexOf('@') + 1); + const labels = domain.split('.'); + const tld = labels.at(-1) ?? ''; + if (['test', 'example', 'invalid', 'localhost'].includes(tld)) return true; + const base = labels.slice(-2).join('.'); + return ['example.com', 'example.net', 'example.org'].includes(base); +} + const unlockSchema = z.object({ name: z.string().trim().min(1).max(100), - email: z.string().trim().toLowerCase().max(254).email(), + email: z.string().trim().toLowerCase().max(254).email() + .refine(e => !isReservedEmailDomain(e), { message: 'Enter your work email.' }), }); +/** Distinct emails one audit accepts. A shared report gets a few readers, not dozens. */ +const LEADS_PER_AUDIT_MAX = 5; + // Engine display names for HubSpot properties const ENGINE_NAMES: Record = { claude: 'Claude', @@ -54,10 +71,9 @@ function findTopWeakness(result: { * starting an audit, so a visitor running several audits cannot exhaust their own * ability to read the reports. * - * This is defence in depth, not the protection that matters: one request is enough to - * write a contact, so the limit changes how fast, not whether. What stops an unlock from - * damaging an existing CRM record is that the sync now fills blank fields only — - * see lib/hubspot.ts. + * Other checks below: the audit must be finished, the address must be real-looking, a + * repeat reader writes nothing new, and each audit accepts a few readers. The CRM sync + * fills blank fields only (lib/hubspot.ts). */ const UNLOCK_LIMIT = Number.parseInt(process.env.RATE_LIMIT_UNLOCK_MAX ?? '10', 10) || 10; @@ -82,6 +98,10 @@ export async function POST( console.error('[unlock] rate limit check failed; allowing the request:', err); } + if (!UUID_REGEX.test(auditId)) { + return NextResponse.json({ error: 'Invalid auditId' }, { status: 400 }); + } + // Staff (FR-014) see the full report without the form: no lead, no CRM sync. const staff = await staffEmail(request); @@ -129,10 +149,19 @@ export async function POST( if (staff) { console.log('[unlock] staff view for audit', auditId); - return withUnlockProof(NextResponse.json({ success: true, staff: true }), auditId); + // Session only: staff unlock again on each visit, so their cookies don't pile up. + return withUnlockProof(NextResponse.json({ success: true, staff: true }), auditId, { session: true }); + } + + // ── 1. Known reader, or room for a new one ─────────────────────────── + const seen = await existingLeads(supabase, auditId, email); + if (seen?.sameEmail) { + // Already captured: unlock again without a second write or CRM call. + return withUnlockProof(NextResponse.json({ success: true }), auditId); } + if (seen && seen.total >= LEADS_PER_AUDIT_MAX) return readerLimit(auditId); - // ── 1. Save lead to Supabase ────────────────────────────────────────── + // ── 2. Save lead to Supabase ────────────────────────────────────────── const { error: leadError } = await supabase.from('leads').upsert( { audit_request_id: auditId, @@ -145,6 +174,10 @@ export async function POST( console.error('[unlock] Supabase leads upsert failed:', JSON.stringify(leadError)); } else { console.log('[unlock] lead saved for audit', auditId); + // Requests that passed the check together are counted again after writing, so the + // ones past the limit get neither the CRM sync nor access. + const after = seen ? await existingLeads(supabase, auditId, email) : null; + if (after && after.total > LEADS_PER_AUDIT_MAX) return readerLimit(auditId); } // Touch the audit_requests updated_at @@ -161,7 +194,7 @@ export async function POST( Supabase and the contact is in HubSpot; the log only needs to say which audit. */ console.log('LEAD_CAPTURED:', JSON.stringify({ auditId })); - // ── 2. Sync to HubSpot (async, non-blocking) ───────────────────────── + // ── 3. Sync to HubSpot (async, non-blocking) ───────────────────────── // Fire-and-forget so the user isn't waiting on HubSpot const appUrl = (process.env.NEXT_PUBLIC_APP_URL ?? 'https://aeo.campaigncreators.com').replace(/\/$/, ''); @@ -231,13 +264,45 @@ export async function POST( 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 { +type CountQuery = PromiseLike<{ count: number | null; error: unknown }> & { eq(c: string, v: string): CountQuery }; + +/** + * This audit's lead count and whether this email is already one of them. Null when the + * lookup fails: the caller then writes the lead as before (the write is idempotent), since + * a dropped capture costs more than a duplicate check. + */ +async function existingLeads( + supabase: ReturnType, + auditId: string, + email: string, +): Promise<{ total: number; sameEmail: boolean } | null> { + const forAudit = () => (supabase.from('leads') + .select('id', { count: 'exact', head: true }) as unknown as CountQuery) + .eq('audit_request_id', auditId); + const [all, same] = await Promise.all([forAudit(), forAudit().eq('email', email)]); + if (all.error || same.error) { + console.error('[unlock] lead lookup failed; writing the lead anyway'); + return null; + } + return { total: all.count ?? 0, sameEmail: (same.count ?? 0) > 0 }; +} + +/** Sets the signed per-audit unlock cookie when a cookie key is available. */ +function withUnlockProof(res: NextResponse, auditId: string, { session = false } = {}): NextResponse { const proof = unlockToken(auditId); if (proof) { res.cookies.set(unlockCookieName(auditId), proof, { - httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 60 * 60 * 24 * 365, + httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', + ...(session ? {} : { maxAge: 60 * 60 * 24 * 365 }), }); } return res; } + +function readerLimit(auditId: string): NextResponse { + console.log('[unlock] lead limit reached for audit', auditId); + return NextResponse.json( + { error: 'This report has reached its limit of readers. Run your own free audit instead.' }, + { status: 429 }, + ); +} diff --git a/src/app/audit/[auditId]/page.test.ts b/src/app/audit/[auditId]/page.test.ts index cd4b47d..484b0da 100644 --- a/src/app/audit/[auditId]/page.test.ts +++ b/src/app/audit/[auditId]/page.test.ts @@ -76,12 +76,12 @@ beforeEach(() => { }); afterEach(() => { - for (const k of ['AEO_GATE_MODE', 'AEO_UNLOCK_COOKIE_SECRET']) delete process.env[k]; + for (const k of ['AEO_REPORT_GATE', 'AEO_UNLOCK_COOKIE_SECRET']) delete process.env[k]; }); describe('report data sent to the browser', () => { it('enforce without an unlock sends only the preview fields', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const p = await renderProps(); const sent = JSON.stringify(p.auditData); expect(p.locked).toBe(true); @@ -95,7 +95,7 @@ describe('report data sent to the browser', () => { }); it('enforce with a valid unlock sends the full report', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const { unlockToken } = await import('@/lib/gate'); cookieValue.v = unlockToken(AUDIT)!; const p = await renderProps(); @@ -103,8 +103,8 @@ describe('report data sent to the browser', () => { expect(JSON.stringify(p.auditData)).toContain('secret-page'); }); - it('enforce with no cookie secret configured fails closed', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + it('enforce with a forged cookie and no dedicated key stays locked', async () => { + process.env.AEO_REPORT_GATE = 'enforce'; delete process.env.AEO_UNLOCK_COOKIE_SECRET; cookieValue.v = 'anything'; const p = await renderProps(); @@ -112,7 +112,7 @@ describe('report data sent to the browser', () => { }); it('observe sends the full report', async () => { - process.env.AEO_GATE_MODE = 'observe'; + process.env.AEO_REPORT_GATE = 'observe'; const log = vi.spyOn(console, 'log').mockImplementation(() => {}); const p = await renderProps(); expect(p.locked).toBe(false); @@ -121,7 +121,14 @@ describe('report data sent to the browser', () => { log.mockRestore(); }); - it('off (unset) sends the full report', async () => { + it('unset is enforce: no unlock, preview only', async () => { + const p = await renderProps(); + expect(p.locked).toBe(true); + expect(JSON.stringify(p.auditData)).not.toContain('secret-page'); + }); + + it('off sends the full report', async () => { + process.env.AEO_REPORT_GATE = 'off'; const p = await renderProps(); expect(p.locked).toBe(false); expect(JSON.stringify(p.auditData)).toContain('secret-page'); diff --git a/src/app/audit/[auditId]/pdf/page.test.ts b/src/app/audit/[auditId]/pdf/page.test.ts index 17181fe..2ac3cc0 100644 --- a/src/app/audit/[auditId]/pdf/page.test.ts +++ b/src/app/audit/[auditId]/pdf/page.test.ts @@ -35,7 +35,7 @@ vi.mock('@supabase/supabase-js', () => ({ })); const AUDIT = '11111111-1111-4111-8111-111111111111'; -const ENV_KEYS = ['AEO_GATE_MODE', 'AEO_UNLOCK_COOKIE_SECRET', 'NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY']; +const ENV_KEYS = ['AEO_REPORT_GATE', 'AEO_UNLOCK_COOKIE_SECRET', 'NEXT_PUBLIC_SUPABASE_URL', 'SUPABASE_SERVICE_ROLE_KEY']; async function render(): Promise { const { default: Page } = await import('./page'); @@ -57,7 +57,7 @@ afterEach(() => { describe('print report access', () => { it('enforce without an unlock returns no report detail', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const html = await render(); expect(html).not.toContain('secret-page'); expect(html).not.toContain('robots.txt allows AI bots'); @@ -65,7 +65,7 @@ describe('print report access', () => { }); it('enforce with a valid unlock returns the report', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; const { unlockToken } = await import('@/lib/gate'); cookieValue.v = unlockToken(AUDIT)!; const html = await render(); @@ -73,14 +73,14 @@ describe('print report access', () => { }); it('enforce with a forged cookie returns no report detail', async () => { - process.env.AEO_GATE_MODE = 'enforce'; + process.env.AEO_REPORT_GATE = 'enforce'; cookieValue.v = 'forged'; const html = await render(); expect(html).not.toContain('robots.txt allows AI bots'); }); it('observe still returns the report and logs a would-refuse', async () => { - process.env.AEO_GATE_MODE = 'observe'; + process.env.AEO_REPORT_GATE = 'observe'; const log = vi.spyOn(console, 'log').mockImplementation(() => {}); const html = await render(); expect(html).toContain('robots.txt allows AI bots'); @@ -88,7 +88,14 @@ describe('print report access', () => { log.mockRestore(); }); - it('off (unset) keeps today\'s behaviour', async () => { + it('unset is enforce: no unlock, no report detail', async () => { + const html = await render(); + expect(html).not.toContain('robots.txt allows AI bots'); + expect(html).not.toContain('secret-page'); + }); + + it('off returns the report', async () => { + process.env.AEO_REPORT_GATE = 'off'; const html = await render(); expect(html).toContain('robots.txt allows AI bots'); }); diff --git a/src/lib/gate.report.test.ts b/src/lib/gate.report.test.ts new file mode 100644 index 0000000..0469cda --- /dev/null +++ b/src/lib/gate.report.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { reportAccess, reportGateMode, unlockRefusal, unlockToken } from './gate'; + +const KEYS = ['AEO_GATE_MODE', 'AEO_REPORT_GATE', 'AEO_UNLOCK_COOKIE_SECRET', 'SUPABASE_SERVICE_ROLE_KEY']; + +let log: ReturnType; +beforeEach(() => { + for (const k of KEYS) delete process.env[k]; + process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'; + log = vi.spyOn(console, 'log').mockImplementation(() => {}); +}); +afterEach(() => { log.mockRestore(); for (const k of KEYS) delete process.env[k]; }); + +describe('report gate: on by default, separate from the run gate', () => { + it('is enforce with nothing set, even when the run gate is off', () => { + expect(reportGateMode()).toBe('enforce'); + expect(reportAccess('audit-1', undefined)).toBe('preview'); + }); + + it('can be switched off or to observe on its own', () => { + process.env.AEO_REPORT_GATE = 'off'; + expect(reportAccess('audit-1', undefined)).toBe('full'); + process.env.AEO_REPORT_GATE = 'observe'; + expect(reportAccess('audit-1', undefined)).toBe('full'); + expect(log.mock.calls.flat().join(' ')).toContain('[gate] observe would-refuse REPORT_LOCKED'); + }); + + it('an unknown value stays enforce (fails closed)', () => { + process.env.AEO_REPORT_GATE = 'disabled'; + expect(reportGateMode()).toBe('enforce'); + }); + + it('a valid proof opens the report', () => { + expect(reportAccess('audit-1', unlockToken('audit-1')!)).toBe('full'); + }); + + it('a proof for another audit does not', () => { + expect(reportAccess('audit-2', unlockToken('audit-1')!)).toBe('preview'); + }); +}); + +describe('unlock proof key', () => { + it('works without a dedicated key, from the server key', () => { + expect(unlockToken('audit-1')).toMatch(/^[A-Za-z0-9_-]{43}$/); + }); + + it('a dedicated key, when set, gives a different proof', () => { + const derived = unlockToken('audit-1'); + process.env.AEO_UNLOCK_COOKIE_SECRET = 'dedicated'; + expect(unlockToken('audit-1')).not.toBe(derived); + }); + + it('the proof is not signed with the server key itself (a separate derived key)', () => { + const t = unlockToken('audit-1')!; + const withServerKey = createHmac('sha256', 'service-role-key').update('unlock:audit-1').digest('base64url'); + expect(t).not.toBe(withServerKey); + }); + + it('no key at all gives no proof, so the report stays locked', () => { + delete process.env.SUPABASE_SERVICE_ROLE_KEY; + expect(unlockToken('audit-1')).toBeNull(); + expect(reportAccess('audit-1', 'anything')).toBe('preview'); + }); +}); + +describe('unlock readiness follows the report gate', () => { + it('refuses an unfinished audit with nothing set', () => { + expect(unlockRefusal('audit-1', 'pending', false)?.status).toBe(409); + expect(unlockRefusal('audit-1', 'complete', false)?.status).toBe(409); + expect(unlockRefusal('audit-1', 'complete', true)).toBeNull(); + }); +}); diff --git a/src/lib/gate.test.ts b/src/lib/gate.test.ts index da15571..8c770a4 100644 --- a/src/lib/gate.test.ts +++ b/src/lib/gate.test.ts @@ -52,10 +52,10 @@ describe('run gate', () => { expect((await runGate(async () => 0))?.body.code).toBe('CONFIG_MISSING'); }); - it('rule 2: no unlock cookie key counts as missing config', async () => { + it('rule 2: no dedicated unlock key is fine (the proof key is derived)', async () => { healthy('enforce'); delete process.env.AEO_UNLOCK_COOKIE_SECRET; - expect((await runGate(async () => 0))?.body.code).toBe('CONFIG_MISSING'); + expect(await runGate(async () => 0)).toBeNull(); }); it('rule 2: the crawler fallback counts in place of the queue key', async () => { diff --git a/src/lib/gate.ts b/src/lib/gate.ts index 3a8c7e5..f2340bb 100644 --- a/src/lib/gate.ts +++ b/src/lib/gate.ts @@ -1,9 +1,12 @@ -import { createHmac, timingSafeEqual } from 'node:crypto'; +import { createHmac, hkdfSync, timingSafeEqual } from 'node:crypto'; /** - * Access and run gate. Ships dark: AEO_GATE_MODE unset (or anything unknown) is `off`, - * which keeps today's behaviour. `observe` evaluates every rule and logs what it would - * refuse, refusing nothing; `enforce` refuses. Log lines: `[gate] `. + * Access and run gate, two independent switches. + * - Report access (who sees the full report, and which audits accept an unlock): + * AEO_REPORT_GATE, `enforce` unless set to `off` or `observe`. + * - Run gate (who may start an audit): AEO_GATE_MODE, unset or unknown is `off`. + * `observe` evaluates every rule and logs what it would refuse, refusing nothing; + * `enforce` refuses. Log lines: `[gate] `. */ export type GateMode = 'off' | 'observe' | 'enforce'; type Decision = 'refuse' | 'would-refuse'; @@ -23,11 +26,30 @@ export function unlockCookieName(auditId: string): string { return `aeo_unlock_${auditId}`; } -/** The signed proof that this browser unlocked this audit; null when no secret is set. */ +/** The report-access switch. Anything other than `off` or `observe` is `enforce`. */ +export function reportGateMode(): GateMode { + const m = (process.env.AEO_REPORT_GATE ?? '').trim().toLowerCase(); + return m === 'off' || m === 'observe' ? m : 'enforce'; +} + +/** + * The key that signs unlock proofs: AEO_UNLOCK_COOKIE_SECRET when set, otherwise a key + * derived (HKDF, own label) from the server key the app already needs, so the gate works + * with no extra setting. Rotating either key re-locks reports until the visitor unlocks again. + */ +function unlockKey(): Buffer | string | null { + const dedicated = (process.env.AEO_UNLOCK_COOKIE_SECRET ?? '').trim(); + if (dedicated) return dedicated; + const server = (process.env.SUPABASE_SERVICE_ROLE_KEY ?? '').trim(); + if (!server) return null; + return Buffer.from(hkdfSync('sha256', server, 'aeo-auditor', 'unlock-proof-v1', 32)); +} + +/** The signed proof that this browser unlocked this audit; null when no key is available. */ export function unlockToken(auditId: string): string | null { - const secret = (process.env.AEO_UNLOCK_COOKIE_SECRET ?? '').trim(); - if (!secret) return null; - return createHmac('sha256', secret).update(`unlock:${auditId}`).digest('base64url'); + const key = unlockKey(); + if (!key) return null; + return createHmac('sha256', key).update(`unlock:${auditId}`).digest('base64url'); } function hasUnlockProof(auditId: string, value: string | undefined): boolean { @@ -40,7 +62,7 @@ function hasUnlockProof(auditId: string, value: string | undefined): boolean { /** 'full' or 'preview' for this viewer. Only `enforce` ever returns 'preview'. */ export function reportAccess(auditId: string, cookieValue: string | undefined): 'full' | 'preview' { - const mode = gateMode(); + const mode = reportGateMode(); if (mode === 'off' || hasUnlockProof(auditId, cookieValue)) return 'full'; logGate(mode, mode === 'enforce' ? 'refuse' : 'would-refuse', 'REPORT_LOCKED', auditId); return mode === 'enforce' ? 'preview' : 'full'; @@ -99,7 +121,7 @@ export function redactForPreview>(audit: T): T /** An unlock is accepted only for a finished audit with results. Returns a refusal or null. */ export function unlockRefusal(auditId: string, status: string | undefined, hasResult: boolean): { status: number; body: { error: string; code: string } } | null { - const mode = gateMode(); + const mode = reportGateMode(); if (mode === 'off' || (status === 'complete' && hasResult)) return null; logGate(mode, mode === 'enforce' ? 'refuse' : 'would-refuse', 'UNLOCK_NOT_READY', auditId); return mode === 'enforce' @@ -160,9 +182,7 @@ async function firstFailingRule(countToday: () => Promise, mode: GateMod 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'; + || !(has('INNGEST_EVENT_KEY') || has('INTERNAL_CRAWLER_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'; diff --git a/src/lib/gateCheck.test.ts b/src/lib/gateCheck.test.ts index bdd6b00..9f4b7b6 100644 --- a/src/lib/gateCheck.test.ts +++ b/src/lib/gateCheck.test.ts @@ -16,6 +16,13 @@ describe('npm run gate:check', () => { expect(out).not.toContain('50'); }); + it('prints the report gate on its own line: enforce unless off or observe', () => { + expect(report({})).toContain('report gate: enforce'); + expect(report({ AEO_REPORT_GATE: 'off' })).toContain('report gate: off'); + expect(report({ AEO_REPORT_GATE: 'nonsense' })).toContain('report gate: enforce'); + expect(report({ AEO_REPORT_GATE: 'off' })).toMatch(/AEO_REPORT_GATE\s+present/); + }); + it('an unset or unknown mode reads as off', () => { expect(report({})).toContain('mode: off'); expect(report({ AEO_GATE_MODE: 'on' })).toContain('mode: off');