-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
75 lines (62 loc) · 1.94 KB
/
Copy pathproxy.ts
File metadata and controls
75 lines (62 loc) · 1.94 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const PUBLIC_PATHS = ["/login", "/verify", "/about"];
async function verifySessionToken(token: string): Promise<boolean> {
try {
const secret = process.env.AUTH_SECRET || "dev-secret-change-me";
const [payloadB64, sig] = token.split(".");
if (!payloadB64 || !sig) return false;
const payload = atob(payloadB64);
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const signatureBytes = await crypto.subtle.sign(
"HMAC",
key,
encoder.encode(payload),
);
const expectedSig = Array.from(new Uint8Array(signatureBytes))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
// Constant-time comparison
if (sig.length !== expectedSig.length) return false;
let diff = 0;
for (let i = 0; i < sig.length; i++) {
diff |= sig.charCodeAt(i) ^ expectedSig.charCodeAt(i);
}
if (diff !== 0) return false;
const data = JSON.parse(payload);
return data.exp > Date.now();
} catch {
return false;
}
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow public paths
if (PUBLIC_PATHS.some((p) => pathname.startsWith(p))) {
return NextResponse.next();
}
// Allow static assets
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/images") ||
pathname.startsWith("/data")
) {
return NextResponse.next();
}
// Check for valid auth cookie
const session = request.cookies.get("auth_session")?.value;
if (!session || !(await verifySessionToken(session))) {
return NextResponse.redirect(new URL("/about", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};