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 unlock without the form (no lead, no CRM), Staff b…
…adge, 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 <noreply@anthropic.com>
  • Loading branch information
razel-hash and claude committed Nov 10, 2026
commit a2ef292ba2ab433a2576fd22e2b0c229c57bfb35
23 changes: 23 additions & 0 deletions src/app/api/audit/[auditId]/unlock/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ vi.mock('@/lib/hubspot', () => ({
syncAeoLead: syncMock,
}));

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

vi.mock('@supabase/supabase-js', () => ({
createClient: () => ({
from: (table: string) => ({
Expand Down Expand Up @@ -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');
Expand Down
45 changes: 31 additions & 14 deletions src/app/api/audit/[auditId]/unlock/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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(
{
Expand Down Expand Up @@ -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, {
Expand Down
21 changes: 21 additions & 0 deletions src/app/api/staff/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, it, expect, vi } from 'vitest';

const { staffMock } = vi.hoisted(() => ({ staffMock: vi.fn(async (): Promise<string | null> => 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('@');
});
});
10 changes: 10 additions & 0 deletions src/app/api/staff/route.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
return NextResponse.json({ staff: (await staffEmail(request)) !== null });
}
3 changes: 2 additions & 1 deletion src/components/aeo/AuditForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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();
Expand Down
25 changes: 25 additions & 0 deletions src/components/aeo/AuditResultPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -301,6 +302,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());
Expand Down
13 changes: 13 additions & 0 deletions src/components/layout/Header.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions src/components/layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<header className={styles.header} role="banner">
Expand All @@ -20,6 +22,7 @@ export function Header() {
className={styles.logoImg}
/>
</Link>
{staff && <span className={styles.staffBadge}>Staff</span>}

{isHomepage && (
<nav className={styles.nav} aria-label="Main navigation">
Expand Down
15 changes: 15 additions & 0 deletions src/lib/staffClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createSupabaseBrowser } from '@/lib/supabase/browser';

/**
* The browser's staff sign-in token as an Authorization header, or {} when nobody is
* signed in (or Supabase isn't configured). The server decides whether it counts as staff.
*/
export async function staffAuthHeader(): Promise<Record<string, string>> {
try {
const { data } = await createSupabaseBrowser().auth.getSession();
const token = data.session?.access_token;
return token ? { Authorization: `Bearer ${token}` } : {};
} catch {
return {};
}
}
25 changes: 25 additions & 0 deletions src/lib/useStaff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use client';

import { useEffect, useState } from 'react';
import { staffAuthHeader } from '@/lib/staffClient';

/** True once the server has confirmed this browser's sign-in is on the staff list. */
export function useStaff(): boolean {
const [staff, setStaff] = useState(false);
useEffect(() => {
let live = true;
(async () => {
const auth = await staffAuthHeader();
if (!auth.Authorization) return;
try {
const res = await fetch('/api/staff', { headers: auth });
const data = (await res.json()) as { staff?: boolean };
if (live && data.staff) setStaff(true);
} catch {
// stays public
}
})();
return () => { live = false; };
}, []);
return staff;
}