-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathproxy.ts
More file actions
169 lines (139 loc) · 5.31 KB
/
proxy.ts
File metadata and controls
169 lines (139 loc) · 5.31 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
import { createServerClient } from '@supabase/ssr';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
/**
* Public API routes that skip authentication.
*/
const PUBLIC_API_PREFIXES = [
'/ycode/api/setup/', // Setup wizard — needed before any user exists
'/ycode/api/supabase/', // Supabase config — needed for browser client init
'/ycode/api/auth/', // Auth callbacks and session checks
'/ycode/api/v1/', // Public API — has own API key auth
];
/**
* Patterns for collection item endpoints that must be accessible on published pages
* (load-more pagination, filter). Matched via regex since the collection ID is dynamic.
*/
const PUBLIC_COLLECTION_ITEM_SUFFIXES = ['/items/filter', '/items/load-more'];
const PUBLIC_API_EXACT = [
'/ycode/api/revalidate', // Cache revalidation — has own secret token auth
];
/**
* Derive the Supabase project URL and anon key from environment variables.
* Returns null if env vars are not set (pre-setup or local dev without .env.local).
*/
function getSupabaseEnvConfig(): { url: string; anonKey: string } | null {
const anonKey = process.env.SUPABASE_PUBLISHABLE_KEY
|| process.env.SUPABASE_ANON_KEY;
const connectionUrl = process.env.SUPABASE_CONNECTION_URL;
if (!anonKey || !connectionUrl) return null;
// Extract project ID from connection URL
// e.g. "postgresql://postgres.abc123:..." → "abc123"
const match = connectionUrl.match(/\/\/postgres\.([a-z0-9]+):/);
if (!match) return null;
return {
url: `https://${match[1]}.supabase.co`,
anonKey,
};
}
function isPublicApiRoute(pathname: string, method: string): boolean {
// POST to form-submissions is public (website visitors submitting forms)
if (pathname === '/ycode/api/form-submissions' && method === 'POST') {
return true;
}
if (PUBLIC_API_EXACT.includes(pathname)) return true;
if (PUBLIC_API_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return true;
// Collection item endpoints for published pages (POST only — filter, load-more)
if (method === 'POST' && pathname.startsWith('/ycode/api/collections/') &&
PUBLIC_COLLECTION_ITEM_SUFFIXES.some(suffix => pathname.endsWith(suffix))) {
return true;
}
return false;
}
/**
* Verify Supabase session for protected API routes.
* Returns a 401 response if not authenticated, or null to continue.
*/
async function verifyApiAuth(request: NextRequest): Promise<NextResponse | null> {
if (isPublicApiRoute(request.nextUrl.pathname, request.method)) {
return null;
}
const config = getSupabaseEnvConfig();
// If env vars aren't set (pre-setup or local dev without .env.local), let through
if (!config) return null;
let response = NextResponse.next({ request });
const supabase = createServerClient(config.url, config.anonKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => {
request.cookies.set(name, value);
});
response = NextResponse.next({ request });
cookiesToSet.forEach(({ name, value, options }) => {
response.cookies.set(name, value, options);
});
},
},
});
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
return NextResponse.json(
{ error: 'Not authenticated' },
{ status: 401 }
);
}
return null;
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// MCP endpoint uses its own token-based authentication — skip session auth.
// Cloud overlay proxies MUST also exempt this path to avoid login redirects.
if (pathname.startsWith('/ycode/mcp/')) {
const response = NextResponse.next();
response.headers.set('x-pathname', pathname);
return response;
}
// Protect API and preview routes with auth
if (pathname.startsWith('/ycode/api') || pathname.startsWith('/ycode/preview')) {
const authResponse = await verifyApiAuth(request);
if (authResponse) {
if (pathname.startsWith('/ycode/preview')) {
return NextResponse.redirect(new URL('/ycode', request.url));
}
return authResponse;
}
}
const isPublicPage = !pathname.startsWith('/ycode')
&& !pathname.startsWith('/_next')
&& !pathname.startsWith('/api')
&& !pathname.startsWith('/dynamic');
const hasPaginationParams = Array.from(request.nextUrl.searchParams.keys())
.some((key) => key.startsWith('p_'));
if (isPublicPage && hasPaginationParams) {
const rewriteUrl = request.nextUrl.clone();
rewriteUrl.pathname = pathname === '/' ? '/dynamic' : `/dynamic${pathname}`;
const rewriteResponse = NextResponse.rewrite(rewriteUrl);
rewriteResponse.headers.set('x-pathname', pathname);
return rewriteResponse;
}
// Create response
const response = NextResponse.next();
// Add pathname header for layout to determine dark mode
response.headers.set('x-pathname', pathname);
// Cache-Control for public pages is configured centrally via next.config.ts headers().
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};