-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
734 lines (678 loc) · 26.7 KB
/
Copy pathproxy.ts
File metadata and controls
734 lines (678 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
import {
checkRateLimit,
getClientIP,
getRateLimitMode,
isRateLimitDegraded,
rateLimitResponse,
} from "@/lib/rate-limit";
import { FOUNDER_EMAILS } from "@/lib/constants";
import { auditLog } from "@/lib/audit-log";
import { timingSafeCompare } from "@/lib/security";
import { ABSORBED_REDIRECTS } from "@/lib/absorbed-redirects";
// ── Nonce-based CSP ─────────────────────────────────────────────────
function generateNonce(): string {
const array = new Uint8Array(16);
crypto.getRandomValues(array);
return Buffer.from(array).toString("base64");
}
// Strict embed-path check — `pathname.startsWith("/embed")` alone matches
// "/embedded-fake", which would inherit `frame-ancestors *` without being in
// the public-page allowlist (a forward-looking leak — no such path exists
// today, but the wrong contract decays the moment one gets added).
function isEmbedPath(pathname?: string): boolean {
if (!pathname) return false;
return pathname === "/embed" || pathname.startsWith("/embed/");
}
function buildCSP(nonce: string, pathname?: string): string {
const isEmbed = isEmbedPath(pathname);
return (
[
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}' https://js.stripe.com https://va.vercel-scripts.com${process.env.NODE_ENV === "development" ? " 'unsafe-eval'" : ""}`,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https: blob:",
"font-src 'self' data:",
"connect-src 'self' https://*.supabase.co wss://*.supabase.co https://api.anthropic.com https://api.stripe.com https://js.stripe.com https://*.ingest.sentry.io https://vitals.vercel-insights.com https://va.vercel-scripts.com",
"frame-src https://js.stripe.com",
"worker-src 'self' blob:",
isEmbed ? "frame-ancestors *" : "frame-ancestors 'none'",
"form-action 'self'",
"object-src 'none'",
"base-uri 'self'",
].join("; ") + ";"
);
}
// ── Security Headers (static — CSP applied per-request) ─────────────
// X-Frame-Options is intentionally NOT in this static set — it's applied
// per-path in applySecurityHeaders so /embed/* can be iframed by third
// parties while the rest of the app stays DENY. Modern browsers prefer
// CSP `frame-ancestors`, but XFO is still honored by legacy clients and
// MUST agree with CSP — otherwise embed silently 200s with a blank frame.
const STATIC_SECURITY_HEADERS: Record<string, string> = {
"X-Content-Type-Options": "nosniff",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
};
function applySecurityHeaders(
response: NextResponse,
nonce: string,
pathname?: string,
): NextResponse {
for (const [key, value] of Object.entries(STATIC_SECURITY_HEADERS)) {
response.headers.set(key, value);
}
// Skip X-Frame-Options for embed routes so the iframe widget actually loads
// on customer sites. CSP `frame-ancestors *` (set in buildCSP) is the modern
// equivalent; XFO would override it on legacy browsers.
const isEmbed = isEmbedPath(pathname);
if (!isEmbed) {
response.headers.set("X-Frame-Options", "DENY");
}
response.headers.set("Content-Security-Policy", buildCSP(nonce, pathname));
response.headers.set("x-csp-nonce", nonce);
return response;
}
// ── Rate Limit Tiers (H-1 through H-5) ─────────────────────────────
// Named tiers for clarity and operational monitoring.
// H-1: Sensitive (billing, keys, remote) — strictest
// H-2: Expensive (AI ops, analysis, credits) — moderate
// H-3: Standard (uploads, tournaments, chat) — normal
// H-4: High-Volume (documents, precedents, general) — permissive
// H-5: Webhooks (inbound integrations) — highest throughput
interface RateLimitTier {
prefix: string;
max: number;
windowMs: number;
tier: "H-1" | "H-2" | "H-3" | "H-4" | "H-5";
}
const RATE_LIMIT_TIERS: RateLimitTier[] = [
// H-5 Webhooks — 200 req/min — inbound integrations (Stripe, sync)
// Check these first to avoid overlaps with lower tiers
{
prefix: "/api/v1/billing/webhook",
max: 200,
windowMs: 60_000,
tier: "H-5",
},
{ prefix: "/api/v1/sync/receive", max: 200, windowMs: 60_000, tier: "H-5" },
{ prefix: "/api/webhooks/inbound-email", max: 200, windowMs: 60_000, tier: "H-5" },
// H-1 Sensitive — 5 req/min — billing, key management, remote commands
{ prefix: "/api/v1/billing/checkout", max: 5, windowMs: 60_000, tier: "H-1" },
{ prefix: "/api/v1/billing/portal", max: 5, windowMs: 60_000, tier: "H-1" },
{ prefix: "/api/v1/focus/bootstrap", max: 3, windowMs: 60_000, tier: "H-1" },
{ prefix: "/api/v1/keys", max: 5, windowMs: 60_000, tier: "H-1" },
{ prefix: "/api/v1/remote/command", max: 5, windowMs: 60_000, tier: "H-1" },
// H-2 Expensive — 10-15 req/min — AI analysis, council debates, credits
{ prefix: "/api/v1/analyze", max: 10, windowMs: 60_000, tier: "H-2" },
{ prefix: "/api/v1/credits", max: 10, windowMs: 60_000, tier: "H-2" },
{ prefix: "/api/v1/council", max: 15, windowMs: 60_000, tier: "H-2" },
{ prefix: "/api/council", max: 15, windowMs: 60_000, tier: "H-2" },
{ prefix: "/api/v1/caas/debate", max: 15, windowMs: 60_000, tier: "H-2" },
{
prefix: "/api/v1/precedents/deposit",
max: 10,
windowMs: 60_000,
tier: "H-2",
},
{
prefix: "/api/v1/team/invitations",
max: 10,
windowMs: 60_000,
tier: "H-2",
},
{ prefix: "/api/v1/evidence/scrape", max: 10, windowMs: 60_000, tier: "H-2" },
// H-2 PLG (public, unauthenticated) — tighter limits to prevent abuse
{ prefix: "/api/v1/benchmark", max: 3, windowMs: 60_000, tier: "H-2" },
{ prefix: "/api/v1/scorecard", max: 5, windowMs: 60_000, tier: "H-2" },
// H-3 Standard — 10-30 req/min — uploads, tournaments, ISA chat, precedent search
{ prefix: "/api/v1/isa/chat", max: 20, windowMs: 60_000, tier: "H-3" },
{ prefix: "/api/v1/upload", max: 10, windowMs: 60_000, tier: "H-3" },
{ prefix: "/api/v1/tournament", max: 20, windowMs: 60_000, tier: "H-3" },
{
prefix: "/api/v1/precedents/match",
max: 30,
windowMs: 60_000,
tier: "H-3",
},
{ prefix: "/api/v1/deliverables", max: 20, windowMs: 60_000, tier: "H-3" },
// H-4 High-Volume — 60-100 req/min — documents, verdicts
{ prefix: "/api/v1/documents", max: 60, windowMs: 60_000, tier: "H-4" },
{ prefix: "/api/v1/verdicts", max: 60, windowMs: 60_000, tier: "H-4" },
// H-4 catch-all — MUST be last (matches any /api/ route not matched above)
{ prefix: "/api/", max: 100, windowMs: 60_000, tier: "H-4" },
];
// ── Public API Allowlist (secure-by-default: all other /api/ routes require auth) ──
// Routes in this list are intentionally public and do NOT require a session.
// Webhooks use signature verification. Cron uses CRON_SECRET header.
const PUBLIC_API_ALLOWLIST = [
"/api/health",
"/api/healthz",
"/api/v1/health",
"/api/v1/billing/webhook", // Stripe signature-verified in handler
"/api/v1/sync/receive", // HMAC signature-verified in handler
"/api/webhooks/inbound-email", // Resend inbound webhook signature-verified in handler
"/api/council", // Public council demo (rate-limited)
"/api/councilverse", // Public councilverse API
// PLG funnel (rate-limited, intentionally public for lead generation)
"/api/v1/waitlist",
"/api/v1/scorecard", // Free ops scan result
"/api/v1/benchmark", // Free deal benchmark
// ADV-008: /api/v1/upload removed from public allowlist — file uploads require auth.
// The free scan flow should authenticate users before allowing uploads.
// ADV: /api/v1/ops-scan removed — route does not exist on disk (stale entry)
"/api/v1/quiz", // Stateless scoring
"/api/v1/analytics/funnel", // Anonymous funnel tracking
// Public content feeds (handlers enforce write auth)
"/api/v1/dissent",
"/api/v1/templates",
// ADV: /api/v1/pulse/deliverables — token-based public sharing (expiry-protected)
"/api/v1/pulse/deliverables",
// A2A protocol discovery — /api/v1/a2a/discovery is the real endpoint.
// /api/a2a/health and /api/a2a/registry were removed from agent.json on
// 2026-05-18 (they never existed); dropping them from the allowlist closes
// the inconsistency.
"/api/v1/a2a/discovery",
// P3.6 — Tenant-scoped MCP server. Bearer-token auth happens in the handler.
"/api/mcp",
];
// Cron routes use CRON_SECRET header instead of session auth
const CRON_API_PREFIXES = [
"/api/cron/",
"/api/v1/cron/",
"/api/v1/ghost-teams/cron",
"/api/v1/shadow-board/scan",
"/api/v1/action-map/ingest",
];
// Founder emails — permanent full access bypass (mirrors lib/auth.ts ADMIN_EMAILS)
// Public page prefixes — no auth required for these routes
const PUBLIC_PAGE_PREFIXES = [
"/login",
"/signup",
"/auth",
"/manifest",
"/pricing", // Public pricing page — conversion funnel
"/scan",
"/verdict",
"/v", // Short verdict URLs — viral sharing
"/benchmark", // Public deal benchmark — PLG magnet
"/pulse", // Public industry pulse — SEO + viral data feed
"/dissent", // Public dissent digest — content flywheel
"/templates", // Public template marketplace — SEO + PLG
"/scorecard", // Public shareable deal scorecards
"/privacy",
"/terms",
"/proof",
"/api-docs",
"/report",
"/waitlist",
"/playground",
"/methods", // P1.4 — renamed from /formations
"/wrapped", // Shareable "Deal Wrapped" summaries — viral PLG
"/estimate", // Lost-Revenue Estimator — zero-access acquisition front-door (no login, client-side only)
"/embed",
"/demo",
"/portal", // CouncilVerse portal — public entry point
"/security",
"/opengraph-image",
"/.well-known",
"/docs", // Public docs (MCP server, etc.) — non-auth marketing surface
];
// Starter tier routes ($149/mo) — accessible to Starter and above
const STARTER_ROUTES = [
"/monitoring",
];
// Pro tier routes ($299/mo) — require full Pro or above
const PRO_ROUTES = [
"/missions",
"/shadow-board",
"/decision-rooms",
"/relay-teams",
"/pulse-ops/webhooks",
"/pulse-ops/benchmarks",
];
// Team tier routes ($999/mo)
const TEAM_ROUTES = ["/team"];
// Relay Governance routes — council/dissent IP lives in Enterprise, not SMB.
const ENTERPRISE_ROUTES = ["/council"];
// Founder/Admin-only operational surfaces
const ADMIN_ROUTES = ["/admin"];
const TIER_RANK: Record<string, number> = {
Free: 0,
Starter: 0.5,
Pro: 1,
Team: 2,
Enterprise: 3,
Investor: 10,
Admin: 99,
Founder: 100,
};
function isPublicPath(pathname: string): boolean {
if (pathname === "/") return true;
if (pathname.includes("opengraph-image")) return true;
return PUBLIC_PAGE_PREFIXES.some(
(p) => pathname === p || pathname.startsWith(p + "/"),
);
}
function buildRouteRedirectUrl(request: NextRequest, oldPrefix: string, newPrefix: string) {
const dest = request.nextUrl.clone();
const target = new URL(newPrefix, request.nextUrl.origin);
const suffix = request.nextUrl.pathname.slice(oldPrefix.length);
dest.pathname = target.search ? target.pathname : target.pathname + suffix;
for (const [key, value] of target.searchParams.entries()) {
dest.searchParams.set(key, value);
}
return dest;
}
export async function proxy(request: NextRequest) {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
const { pathname } = request.nextUrl;
const nonce = generateNonce();
// ── S3 Buyer-Facing Renames (301 permanent redirects) ─────────
// Redirect old route prefixes BEFORE auth so every visitor gets the redirect.
// next.config.mjs redirects() handles these too; this is defense in depth.
const routeRedirects: readonly [string, string][] = [
...ABSORBED_REDIRECTS,
["/departments", "/rooms"],
["/formations", "/methods"],
];
// Sources that have LIVE child routes (or are self-referential) must redirect
// on the EXACT path only. Otherwise startsWith(`${oldPrefix}/`) shadows real
// children: e.g. /operations/recovery -> /pulse-ops/recovery (404, the
// owner-approved Back-Office surface), /decision-rooms/<id> -> /council/<id>
// (no [id] under /council, 404), and /discovery/citations ->
// /discovery/citations/citations (404, self-referential loop).
const EXACT_ONLY_REDIRECTS = new Set([
"/operations",
"/decision-rooms",
"/discovery",
"/monitoring",
]);
for (const [oldPrefix, newPrefix] of routeRedirects) {
const matches = EXACT_ONLY_REDIRECTS.has(oldPrefix)
? pathname === oldPrefix
: pathname === oldPrefix || pathname.startsWith(`${oldPrefix}/`);
if (matches) {
return NextResponse.redirect(buildRouteRedirectUrl(request, oldPrefix, newPrefix), 301);
}
}
// ── Rate Limiting (API routes only) ───────────────────────────
if (pathname.startsWith("/api/")) {
// ── CSRF Origin Verification (state-mutating methods) ──────
const method = request.method;
if (
method === "POST" ||
method === "PATCH" ||
method === "PUT" ||
method === "DELETE"
) {
// Webhook endpoints use signature verification instead of origin checking
const CSRF_EXEMPT = [
"/api/v1/billing/webhook",
"/api/v1/sync/receive",
"/api/v1/action-map/ingest",
// P3.5 — MCP server uses bearer-token auth; external AI clients
// (Claude Desktop, Gemini CLI, custom SDKs) don't set an Origin
// header, so we skip the same-origin check and rely on token + rate-limit.
"/api/mcp",
];
const exempt = CSRF_EXEMPT.some((p) => pathname.startsWith(p));
if (!exempt) {
const origin = request.headers.get("origin");
const ALLOWED_ORIGINS = (
process.env.ALLOWED_ORIGINS || "https://deck.relaylaunch.com"
).split(",");
// Allow localhost in development
if (process.env.NODE_ENV === "development") {
ALLOWED_ORIGINS.push(
"http://localhost:3000",
"http://127.0.0.1:3000",
);
}
if (!origin || !ALLOWED_ORIGINS.includes(origin)) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Forbidden — origin not allowed" },
{ status: 403 },
),
nonce,
);
}
}
}
const ip = getClientIP(request);
// Use first match — order matters (RATE_LIMIT_TIERS is ordered specifically)
const tier =
RATE_LIMIT_TIERS.find((t) => pathname.startsWith(t.prefix)) ||
RATE_LIMIT_TIERS.find((t) => t.prefix === "/api/")!;
const key = `${ip}:${tier.prefix}`;
const { allowed, remaining, retryAfterMs } = await checkRateLimit(
key,
tier.max,
tier.windowMs,
);
if (!allowed && retryAfterMs) {
const blocked = rateLimitResponse(retryAfterMs);
blocked.headers.set("X-RateLimit-Tier", tier.tier);
return applySecurityHeaders(blocked, nonce);
}
// ── API Auth: Secure-by-default ────────────────────────────────
// Check if this route is in the public allowlist
const isPublicApi = PUBLIC_API_ALLOWLIST.some(
(p) => pathname === p || pathname.startsWith(p + "/"),
);
const isCronApi = CRON_API_PREFIXES.some((p) => pathname.startsWith(p));
// Cron routes: verify CRON_SECRET header (timing-safe comparison)
if (isCronApi) {
const cronSecret = process.env.CRON_SECRET;
const authHeader = request.headers.get("authorization");
if (!cronSecret || !authHeader || !timingSafeCompare(authHeader, `Bearer ${cronSecret}`)) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Unauthorized — invalid cron secret" },
{ status: 401 },
),
nonce,
);
}
// Valid cron — pass through with rate limit headers
const cronResponse = NextResponse.next({ request });
cronResponse.headers.set("X-RateLimit-Limit", String(tier.max));
cronResponse.headers.set("X-RateLimit-Remaining", String(remaining));
cronResponse.headers.set("X-RateLimit-Tier", tier.tier);
return applySecurityHeaders(cronResponse, nonce);
}
// Public API routes: pass through without auth (rate limiting still applies)
if (isPublicApi) {
const pubResponse = NextResponse.next({ request });
pubResponse.headers.set("X-RateLimit-Limit", String(tier.max));
pubResponse.headers.set("X-RateLimit-Remaining", String(remaining));
pubResponse.headers.set("X-RateLimit-Tier", tier.tier);
pubResponse.headers.set("X-RateLimit-Mode", getRateLimitMode());
if (isRateLimitDegraded()) {
pubResponse.headers.set("X-RateLimit-Warning", "memory-fallback");
}
return applySecurityHeaders(pubResponse, nonce);
}
// Protected API routes: require valid Supabase session
if (!supabaseUrl || !supabaseAnonKey) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Service unavailable — authentication not configured" },
{ status: 503 },
),
nonce,
);
}
if (supabaseUrl && supabaseAnonKey) {
const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll() {
/* middleware can't set cookies on API responses easily */
},
},
});
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
// Also accept Bearer token for programmatic access
const authHeader = request.headers.get("authorization");
const bearerToken = authHeader?.startsWith("Bearer ")
? authHeader.slice(7)
: null;
if (!bearerToken) {
return applySecurityHeaders(
NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
nonce,
);
}
// Verify bearer token via Supabase
const {
data: { user: tokenUser },
} = await supabase.auth.getUser(bearerToken);
if (!tokenUser) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Unauthorized — invalid token" },
{ status: 401 },
),
nonce,
);
}
}
}
// Attach rate limit info headers to successful API responses
const response = NextResponse.next({ request });
response.headers.set("X-RateLimit-Limit", String(tier.max));
response.headers.set("X-RateLimit-Remaining", String(remaining));
response.headers.set("X-RateLimit-Tier", tier.tier);
response.headers.set("X-RateLimit-Mode", getRateLimitMode());
if (isRateLimitDegraded()) {
response.headers.set("X-RateLimit-Warning", "memory-fallback");
}
return applySecurityHeaders(response, nonce);
}
// If Supabase is not configured, block all protected routes — fail CLOSED, not open
if (!supabaseUrl || !supabaseAnonKey) {
const isPublic =
pathname === "/" ||
pathname.startsWith("/login") ||
pathname.startsWith("/api/health");
if (!isPublic) {
return new NextResponse(
"Service unavailable — authentication not configured",
{ status: 503 },
);
}
return NextResponse.next();
}
// Short-circuit: skip the expensive getUser() call for public paths
if (isPublicPath(pathname)) {
// Still need Supabase client to refresh cookies for logged-in users on public pages
let supabaseResponse = NextResponse.next({ request });
const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(
cookiesToSet: {
name: string;
value: string;
options?: Record<string, unknown>;
}[],
) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
);
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
);
},
},
});
// For /login and /signup, check if user is already authenticated → redirect appropriately
if (pathname === "/login" || pathname === "/signup") {
const {
data: { user },
} = await supabase.auth.getUser();
if (user) {
const url = request.nextUrl.clone();
const { data: profile } = await supabase
.from("profiles")
.select("plan_tier")
.eq("user_id", user.id)
.maybeSingle();
url.pathname =
profile?.plan_tier === "Starter" ? "/focus" : "/dashboard";
return NextResponse.redirect(url);
}
}
return applySecurityHeaders(supabaseResponse, nonce, pathname);
}
// Protected path — full auth required
let supabaseResponse = NextResponse.next({ request });
const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(
cookiesToSet: {
name: string;
value: string;
options?: Record<string, unknown>;
}[],
) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
);
supabaseResponse = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
);
},
},
});
const {
data: { user },
} = await supabase.auth.getUser();
// Unauthenticated on protected page → redirect to login
if (!user) {
const url = request.nextUrl.clone();
url.pathname = "/login";
url.searchParams.set("next", pathname);
return NextResponse.redirect(url);
}
// Starter users who hit /dashboard → redirect to /focus (their primary landing)
if (pathname === "/dashboard") {
const { data: profile } = await supabase
.from("profiles")
.select("plan_tier")
.eq("user_id", user.id)
.maybeSingle();
if (profile?.plan_tier === "Starter") {
const url = request.nextUrl.clone();
url.pathname = "/focus";
return NextResponse.redirect(url);
}
}
// Plan Tier Gating — 7-tier SaaS model + Reverse Trial
// Free: dashboard, documents (3/mo), rooms, settings
// Free + Trial: 48-hour full Pro access (server-side expiry, Option A trial-only)
// Starter ($149/mo): + monitoring
// Pro ($299/mo): + missions, decision-rooms, relay-teams, ghost-teams, arena
// Team ($999/mo): + strategy-room, team management, shared workspace
// Enterprise ($3k+/mo): governance councils, custom councils, BYOA
// Investor: full access, demo data pre-loaded, no billing
// Founder: full access, no limits, admin override
const isAdminRoute = ADMIN_ROUTES.some((route) => pathname.startsWith(route));
const isStarterRoute = STARTER_ROUTES.some((route) =>
pathname.startsWith(route),
);
const isProRoute = PRO_ROUTES.some((route) => pathname.startsWith(route));
const isTeamRoute = TEAM_ROUTES.some((route) => pathname.startsWith(route));
const isEnterpriseRoute = ENTERPRISE_ROUTES.some((route) =>
pathname.startsWith(route),
);
if (isAdminRoute) {
const { data: profile } = await supabase
.from("profiles")
.select("role, plan_tier")
.eq("user_id", user.id)
.maybeSingle();
const isFounderEmail =
user.email && FOUNDER_EMAILS.includes(user.email.toLowerCase());
const hasAdminAccess =
isFounderEmail ||
profile?.role === "admin" ||
profile?.plan_tier === "Founder" ||
profile?.plan_tier === "Admin";
if (!hasAdminAccess) {
return applySecurityHeaders(
new NextResponse("Not found", { status: 404 }),
nonce,
pathname,
);
}
// MFA enforcement for admin routes — default ON. Production always enforces;
// non-production can opt out via DISABLE_MFA=true (dev/CI only).
if (
process.env.NODE_ENV === "production" ||
process.env.DISABLE_MFA !== "true"
) {
const { data: mfaData } =
await supabase.auth.mfa.getAuthenticatorAssuranceLevel();
if (
mfaData &&
mfaData.currentLevel !== "aal2" &&
mfaData.nextLevel === "aal2"
) {
auditLog({
userId: user.id,
action: "mfa.blocked",
resource: "middleware",
details: { route: pathname, reason: "MFA challenge required" },
});
const url = request.nextUrl.clone();
url.pathname = "/settings";
url.searchParams.set("mfa_required", "true");
return NextResponse.redirect(url);
}
}
}
if (isStarterRoute || isProRoute || isTeamRoute || isEnterpriseRoute) {
const { data: profile } = await supabase
.from("profiles")
.select("role, plan_tier, trial_expires_at")
.eq("user_id", user.id)
.maybeSingle();
// Admins, Founders, and founder emails bypass all tier gating
const isFounderEmail =
user.email && FOUNDER_EMAILS.includes(user.email.toLowerCase());
if (
!isFounderEmail &&
profile?.role !== "admin" &&
profile?.plan_tier !== "Founder"
) {
// Reverse Trial: Free users with active trial get Pro access
const isTrialActive =
profile?.plan_tier === "Free" &&
profile?.trial_expires_at &&
new Date(profile.trial_expires_at) > new Date();
const effectiveRank = isTrialActive
? TIER_RANK["Pro"]
: (TIER_RANK[profile?.plan_tier || "Free"] ?? 0);
const requiredTierLabel = isTeamRoute
? "Team"
: isEnterpriseRoute
? "Enterprise"
: isProRoute
? "Pro"
: "Starter";
const requiredRank = TIER_RANK[requiredTierLabel] ?? 0.5;
if (effectiveRank < requiredRank) {
const url = request.nextUrl.clone();
url.pathname = "/waitlist";
url.searchParams.set("upgrade_required", "true");
url.searchParams.set("required_tier", requiredTierLabel);
return NextResponse.redirect(url);
}
}
}
return applySecurityHeaders(supabaseResponse, nonce, pathname);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|_next/webpack-hmr|favicon.ico|icon|apple-icon|sw\\.js|manifest\\.json|manifest\\.webmanifest|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};