-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
86 lines (71 loc) · 2.31 KB
/
proxy.ts
File metadata and controls
86 lines (71 loc) · 2.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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const AUTH_SECRET = process.env.AUTH_SECRET || 'default-secret-change-me';
async function hashString(str: string) {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
async function verifySessionToken(token: string) {
try {
const parts = token.split(':');
if (parts.length !== 3) return false;
const [status, expiryStr, signature] = parts;
const expiry = parseInt(expiryStr, 10);
// Check expiry
if (Date.now() > expiry) return false;
// Verify signature
const payload = `${status}:${expiryStr}`;
const expectedSignature = await hashString(payload + AUTH_SECRET);
return signature === expectedSignature;
} catch {
return false;
}
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow access to login page, auth API routes, and MCP server
if (
pathname === '/login' ||
pathname.startsWith('/api/auth/') ||
pathname.startsWith('/api/mcp') ||
pathname.startsWith('/_next/') ||
pathname.startsWith('/favicon') ||
pathname.endsWith('.ico') ||
process.env.NODE_ENV === 'development'
) {
return NextResponse.next();
}
// Allow Vercel cron requests (requires CRON_SECRET for security)
if (
pathname === '/api/linkedin-posts' ||
pathname === '/api/youtube-transcripts'
) {
const authHeader = request.headers.get('authorization');
const cronSecret = process.env.CRON_SECRET;
if (!cronSecret || authHeader === `Bearer ${cronSecret}`) {
return NextResponse.next();
}
}
// Check for auth cookie
const sessionCookie = request.cookies.get('auth_session');
if (!sessionCookie || !(await verifySessionToken(sessionCookie.value))) {
// Redirect to login
const loginUrl = new URL('/login', request.url);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
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).*)',
],
};