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
Prev Previous commit
fix(report): reader limit re-checked after the write; staff unlock la…
…sts the session; doc and comment wording

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
razel-hash and claude committed Nov 16, 2026
commit a2bdc0da42644acabf1eeb4348d366f61e9b9241
8 changes: 5 additions & 3 deletions docs/guides/aeo-auditor.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ rate and shows as "coming soon" or "unavailable". It never counts as "not cited"

## 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), and
custom questions are refused. An unlock is accepted only for a finished audit with results,
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.
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 |
|---|---|
Expand Down
24 changes: 24 additions & 0 deletions src/app/api/audit/[auditId]/unlock/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,15 @@ describe('unlock checks the audit and proves the unlock', () => {
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 () => {
const { POST } = await import('./route');
const res = await POST(makeRequest({}), ctx);
Expand Down Expand Up @@ -268,6 +277,21 @@ describe('unlock accepts only real ids and real details', () => {
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<string, string>) => {
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');
Expand Down
35 changes: 21 additions & 14 deletions src/app/api/audit/[auditId]/unlock/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,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;

Expand Down Expand Up @@ -150,7 +149,8 @@ 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 ───────────────────────────
Expand All @@ -159,13 +159,7 @@ export async function POST(
// 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) {
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 },
);
}
if (seen && seen.total >= LEADS_PER_AUDIT_MAX) return readerLimit(auditId);

// ── 2. Save lead to Supabase ──────────────────────────────────────────
const { error: leadError } = await supabase.from('leads').upsert(
Expand All @@ -180,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
Expand Down Expand Up @@ -290,12 +288,21 @@ async function existingLeads(
}

/** Sets the signed per-audit unlock cookie when a cookie key is available. */
function withUnlockProof(res: NextResponse, auditId: string): NextResponse {
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 },
);
}
6 changes: 4 additions & 2 deletions src/lib/gate.report.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
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'];
Expand Down Expand Up @@ -50,9 +51,10 @@ describe('unlock proof key', () => {
expect(unlockToken('audit-1')).not.toBe(derived);
});

it('the proof is not the server key or a plain hash of it', () => {
it('the proof is not signed with the server key itself (a separate derived key)', () => {
const t = unlockToken('audit-1')!;
expect(t).not.toContain('service-role-key');
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', () => {
Expand Down
Loading