-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
78 lines (66 loc) · 2.53 KB
/
Copy pathproxy.ts
File metadata and controls
78 lines (66 loc) · 2.53 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
import { NextRequest, NextResponse } from "next/server";
function decodeBase64Url(value: string): string {
const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
return atob(padded);
}
function base64UrlToArrayBuffer(value: string): ArrayBuffer {
const binary = decodeBase64Url(value);
const buffer = new ArrayBuffer(binary.length);
const bytes = new Uint8Array(buffer);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return buffer;
}
async function isTokenValid(token: string, secret: string): Promise<boolean> {
try {
const [headerPart, payloadPart, signaturePart] = token.split(".");
if (!headerPart || !payloadPart || !signaturePart) return false;
const header = JSON.parse(decodeBase64Url(headerPart)) as { alg?: string };
if (header.alg !== "HS256") return false;
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"]
);
const signedPayload = new TextEncoder().encode(`${headerPart}.${payloadPart}`);
const signature = base64UrlToArrayBuffer(signaturePart);
const signatureValid = await crypto.subtle.verify("HMAC", key, signature, signedPayload);
if (!signatureValid) return false;
const { exp } = JSON.parse(decodeBase64Url(payloadPart)) as { exp?: number };
return exp ? exp * 1000 > Date.now() : true;
} catch {
return false;
}
}
export default async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
if (
pathname.startsWith("/api/") ||
pathname.startsWith("/_next/") ||
pathname === "/favicon.ico"
) {
return NextResponse.next();
}
const jwtSecret = process.env.JWT_SECRET;
if (!jwtSecret) return NextResponse.next();
const loginUrl = process.env.STRUCTUM_LOGIN_URL;
if (!loginUrl) {
console.error("[proxy] STRUCTUM_LOGIN_URL is not set — cannot redirect unauthenticated users");
return NextResponse.next();
}
const token = req.cookies.get("token")?.value;
if (!token || !(await isTokenValid(token, jwtSecret))) {
const response = NextResponse.redirect(
loginUrl.includes("?")
? `${loginUrl}&returnTo=${encodeURIComponent(pathname + req.nextUrl.search)}`
: `${loginUrl}?returnTo=${encodeURIComponent(pathname + req.nextUrl.search)}`
);
if (token) response.cookies.set("token", "", { maxAge: 0, path: "/" });
return response;
}
return NextResponse.next();
}