-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathproxy.ts
More file actions
261 lines (219 loc) · 6.67 KB
/
Copy pathproxy.ts
File metadata and controls
261 lines (219 loc) · 6.67 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import {
AUTH_SESSION_COOKIE_NAME,
isSessionExpired,
parseSessionToken,
} from "@/lib/shared/auth/session";
import { type NextRequest, NextResponse } from "next/server";
const DEMO_MODE = process.env.DEMO_MODE === "true";
const DEMO_BLOCKED_METHODS = new Set(["POST", "PUT", "DELETE", "PATCH"]);
const PUBLIC_ROUTES = new Set(["/login", "/register"]);
const RECOVERY_ROUTES = new Set(["/updating"]);
const AUTH_STATUS_CACHE_MS = 5_000;
let authStatusCache:
| {
hasUsers: boolean;
expiresAt: number;
}
| null = null;
export function resetAuthStatusCacheForTests() {
authStatusCache = null;
}
function isPublicApiRoute(pathname: string) {
return (
pathname === "/api/health" ||
pathname === "/api/auth/login" ||
pathname === "/api/auth/register" ||
pathname === "/api/auth/status" ||
// Second leg of the TOTP login flow. Caller has no session cookie yet —
// only a short-lived partial-auth token. Route handler validates that
// token itself; do not gate it on a session.
pathname === "/api/v1/auth/login/totp" ||
pathname === "/api/v1/logs"
);
}
function isStaticRoute(pathname: string) {
return (
pathname.startsWith("/_next/") ||
pathname.startsWith("/images/") ||
pathname === "/favicon.ico" ||
pathname === "/icon.svg" ||
pathname === "/apple-icon.png" ||
/\.[a-zA-Z0-9]+$/.test(pathname)
);
}
async function signPayloadEdge(payload: string, secret: string) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const signatureBuffer = await crypto.subtle.sign(
"HMAC",
key,
encoder.encode(payload),
);
return Array.from(new Uint8Array(signatureBuffer))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
function safeEqual(left: string, right: string) {
if (left.length !== right.length) return false;
let mismatch = 0;
for (let i = 0; i < left.length; i += 1) {
mismatch |= left.charCodeAt(i) ^ right.charCodeAt(i);
}
return mismatch === 0;
}
export async function verifySessionTokenInMiddleware(
sessionToken: string | undefined,
secret = process.env.AUTH_SESSION_SECRET ?? "dev-session-secret-change-me",
) {
if (!sessionToken) return false;
const parsed = parseSessionToken(sessionToken);
if (!parsed) return false;
if (isSessionExpired(parsed.expiresAtEpochSeconds)) return false;
const expected = await signPayloadEdge(parsed.payload, secret);
return safeEqual(expected, parsed.signature);
}
async function hasUsersInDb(request: NextRequest) {
const now = Date.now();
if (authStatusCache && authStatusCache.expiresAt > now) {
return authStatusCache.hasUsers;
}
try {
const response = await fetch(new URL("/api/auth/status", request.url), {
method: "GET",
cache: "no-store",
});
if (!response.ok) {
throw new Error("Auth status request failed");
}
const json = (await response.json()) as {
data?: {
hasUsers?: boolean;
};
};
const hasUsers = typeof json.data?.hasUsers === "boolean" ? json.data.hasUsers : false;
authStatusCache = {
hasUsers,
expiresAt: now + AUTH_STATUS_CACHE_MS,
};
return hasUsers;
} catch {
if (authStatusCache) {
return authStatusCache.hasUsers;
}
return false;
}
}
function getAuthEntryPath(hasUsers: boolean) {
return hasUsers ? "/login" : "/register";
}
function clearSessionCookie(response: NextResponse) {
response.cookies.set({
name: AUTH_SESSION_COOKIE_NAME,
value: "",
path: "/",
expires: new Date(0),
});
return response;
}
export async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
if (isStaticRoute(pathname)) {
return NextResponse.next();
}
if (isPublicApiRoute(pathname)) {
return NextResponse.next();
}
if (
DEMO_MODE &&
DEMO_BLOCKED_METHODS.has(request.method) &&
pathname.startsWith("/api/v1/")
) {
return NextResponse.json(
{ error: "This action is not available in demo mode." },
{ status: 403 },
);
}
const sessionToken = request.cookies.get(AUTH_SESSION_COOKIE_NAME)?.value;
const isAuthenticated = await verifySessionTokenInMiddleware(sessionToken);
if (PUBLIC_ROUTES.has(pathname)) {
const hasUsers = await hasUsersInDb(request);
const expectedPublicPath = getAuthEntryPath(hasUsers);
if (isAuthenticated) {
if (!hasUsers) {
if (pathname === "/register") {
return clearSessionCookie(NextResponse.next());
}
return clearSessionCookie(
NextResponse.redirect(new URL("/register", request.url)),
);
}
return NextResponse.redirect(new URL("/", request.url));
}
if (pathname !== expectedPublicPath) {
return NextResponse.redirect(new URL(expectedPublicPath, request.url));
}
return NextResponse.next();
}
if (RECOVERY_ROUTES.has(pathname)) {
return NextResponse.next();
}
if (isAuthenticated) {
const hasUsers = await hasUsersInDb(request);
if (!hasUsers) {
if (pathname.startsWith("/api/")) {
if (pathname === "/api/auth/me") {
const response = NextResponse.json(
{
error: "Unauthorized",
redirectTo: "/register",
},
{ status: 401 },
);
response.headers.set("x-auth-entry", "/register");
return clearSessionCookie(response);
}
return clearSessionCookie(
NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
);
}
return clearSessionCookie(
NextResponse.redirect(new URL("/register", request.url)),
);
}
}
if (!isAuthenticated) {
if (pathname.startsWith("/api/")) {
if (pathname === "/api/auth/me") {
const hasUsers = await hasUsersInDb(request);
const authEntry = getAuthEntryPath(hasUsers);
const response = NextResponse.json(
{
error: "Unauthorized",
redirectTo: authEntry,
},
{ status: 401 },
);
response.headers.set("x-auth-entry", authEntry);
return response;
}
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const hasUsers = await hasUsersInDb(request);
const authUrl = new URL(getAuthEntryPath(hasUsers), request.url);
authUrl.searchParams.set(
"next",
`${request.nextUrl.pathname}${request.nextUrl.search}`,
);
return NextResponse.redirect(authUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};