-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathproxy.ts
More file actions
126 lines (101 loc) · 3.49 KB
/
proxy.ts
File metadata and controls
126 lines (101 loc) · 3.49 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { isDebugFlag, getSessionCookieName } from "./app/_utils/env-utils";
const debugProxy = isDebugFlag("proxy");
const SESSION_CACHE_TTL = 10_000;
const sessionCache = new Map<string, { valid: boolean; ts: number }>();
const _checkSession = async (sessionId: string, internalApiUrl: string, cookie: string) => {
const cached = sessionCache.get(sessionId);
if (cached && Date.now() - cached.ts < SESSION_CACHE_TTL) return cached.valid;
const sessionCheckUrl = new URL(`${internalApiUrl}/api/auth/check-session`);
if (debugProxy) {
console.log("MIDDLEWARE - Session Check URL:", sessionCheckUrl.href);
}
const res = await fetch(sessionCheckUrl, {
headers: { Cookie: cookie },
cache: "no-store",
});
if (debugProxy) {
console.log("MIDDLEWARE - Session Check Response:");
console.log(" status:", res.status);
console.log(" statusText:", res.statusText);
console.log(" ok:", res.ok);
}
sessionCache.set(sessionId, { valid: res.ok, ts: Date.now() });
if (sessionCache.size > 1000) {
const now = Date.now();
sessionCache.forEach((val, key) => {
if (now - val.ts > SESSION_CACHE_TTL) sessionCache.delete(key);
});
}
return res.ok;
};
export const proxy = async (request: NextRequest) => {
const { pathname } = request.nextUrl;
if (
pathname.startsWith("/api/auth/check-session") ||
pathname.startsWith("/api/auth/login") ||
pathname.startsWith("/auth") ||
pathname.startsWith("/public/")
) {
const response = NextResponse.next();
response.headers.set("x-pathname", pathname);
return response;
}
if (pathname.startsWith("/api/")) {
return NextResponse.next();
}
const sessionId = request.cookies.get(getSessionCookieName())?.value;
if (debugProxy) {
console.log(
"MIDDLEWARE - session cookie:",
sessionId ? "present" : "absent",
);
}
const appUrlBase = process.env.APP_URL
? process.env.APP_URL.replace(/\/$/, "")
: request.nextUrl.origin;
const loginUrl = new URL(`${appUrlBase}/auth/login`);
if (!sessionId) {
return NextResponse.redirect(loginUrl);
}
try {
const internalApiUrl =
process.env.INTERNAL_API_URL ||
(process.env.APP_URL ? new URL(process.env.APP_URL).origin : null) ||
request.nextUrl.origin;
if (debugProxy) {
console.log("MIDDLEWARE - URL Resolution:");
console.log(
" INTERNAL_API_URL:",
process.env.INTERNAL_API_URL || "(not set)",
);
console.log(" APP_URL:", process.env.APP_URL || "(not set)");
console.log(" request.nextUrl.origin:", request.nextUrl.origin);
console.log(" → Using:", internalApiUrl);
}
const valid = await _checkSession(
sessionId,
internalApiUrl,
request.headers.get("Cookie") || "",
);
if (!valid) {
const redirectResponse = NextResponse.redirect(loginUrl);
redirectResponse.cookies.delete(getSessionCookieName());
if (debugProxy) {
console.log("MIDDLEWARE - session is not ok");
}
return redirectResponse;
}
} catch (error) {
console.error("Session check error:", error);
}
const response = NextResponse.next();
response.headers.set("x-pathname", pathname);
return response;
};
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|site.webmanifest|sw.js|app-icons|app-screenshots|flags|fonts|images|repo-images|themes|openapi.yaml).*)",
],
};