forked from hackerai-tech/hackerai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
382 lines (340 loc) · 10.4 KB
/
Copy pathproxy.ts
File metadata and controls
382 lines (340 loc) · 10.4 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { authkit } from "@workos-inc/authkit-nextjs";
import { NextResponse, type NextRequest } from "next/server";
import { isRateLimitError } from "@/lib/api/response";
import { isEndedSessionRefreshError } from "@/lib/auth/expected-auth-errors";
import {
REFERRAL_COOKIE_CREATED_AT_NAME,
REFERRAL_COOKIE_NAME,
getReferralRewardConfig,
isValidReferralCode,
} from "@/lib/referrals/config";
const AUTHKIT_BYPASS_PATHS = new Set([
"/api/health/core",
"/api/health/trigger-agent-mode",
"/robots.txt",
"/sitemap.xml",
]);
const ROOT_PAGE_PATHS = new Set(["/", "/index"]);
const NEXT_ACTION_HEADER = "next-action";
const UNAUTHENTICATED_PATHS = new Set([
...AUTHKIT_BYPASS_PATHS,
"/",
"/login",
"/signup",
"/signup/auth",
"/logout",
"/api/clear-auth-cookies",
"/api/auth/desktop-callback",
"/api/extra-usage/webhook",
"/api/fraud/webhook",
"/api/subscription/webhook",
"/api/workos/webhook",
"/callback",
"/desktop-login",
"/desktop-callback",
"/auth-error",
"/privacy-policy",
"/terms-of-service",
"/trust",
"/download",
"/manifest.json",
]);
function getRedirectUri(): string | undefined {
if (process.env.VERCEL_ENV === "preview" && process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}/callback`;
}
return undefined;
}
function isDesktopApp(request: NextRequest): boolean {
const userAgent = request.headers.get("user-agent") || "";
return userAgent.includes("HackerAI-Desktop");
}
function isUnauthenticatedPath(pathname: string): boolean {
if (UNAUTHENTICATED_PATHS.has(pathname)) {
return true;
}
if (pathname.startsWith("/share/")) {
return true;
}
if (pathname.startsWith("/invite/")) {
return true;
}
return false;
}
function shouldBypassAuthkit(pathname: string): boolean {
return AUTHKIT_BYPASS_PATHS.has(pathname);
}
function isUnsupportedRootPageRequest(
request: NextRequest,
pathname: string,
): boolean {
if (!ROOT_PAGE_PATHS.has(pathname)) return false;
if (request.method === "GET" || request.method === "HEAD") return false;
return !isNextActionRequest(request);
}
function isNextActionRequest(request: NextRequest): boolean {
return request.method === "POST" && request.headers.has(NEXT_ACTION_HEADER);
}
function isBrowserRequest(request: NextRequest): boolean {
const accept = request.headers.get("accept") ?? "";
return accept.includes("text/html");
}
const SESSION_HEADER = "x-workos-session";
function withReferralCookie(
request: NextRequest,
response: NextResponse,
): NextResponse {
const referralCode =
request.nextUrl.searchParams.get("referral_code") ??
request.nextUrl.searchParams.get("ref");
if (!referralCode || !isValidReferralCode(referralCode)) return response;
const config = getReferralRewardConfig();
if (!config.enabled) return response;
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
maxAge: config.cookieMaxAgeSeconds,
path: "/",
};
response.cookies.set(REFERRAL_COOKIE_NAME, referralCode, cookieOptions);
response.cookies.set(
REFERRAL_COOKIE_CREATED_AT_NAME,
String(Date.now()),
cookieOptions,
);
return response;
}
function withSessionCookieCleared(response: NextResponse): NextResponse {
response.cookies.delete("wos-session");
return response;
}
function buildEndedSessionResponse(
request: NextRequest,
pathname: string,
): NextResponse {
// A Server Action still runs after middleware. Letting an ended session
// through on a public page means the action's `withAuth()` call has no
// AuthKit middleware context and throws a misleading 500 instead of a clean
// authentication response.
if (isNextActionRequest(request)) {
return withSessionCookieCleared(
NextResponse.json(
{
code: "unauthorized:auth",
message: "You need to sign in before continuing.",
cause: "Session expired or invalid",
},
{ status: 401 },
),
);
}
if (isUnauthenticatedPath(pathname)) {
return withSessionCookieCleared(
withReferralCookie(request, NextResponse.next()),
);
}
if (!isBrowserRequest(request)) {
return withSessionCookieCleared(
withReferralCookie(
request,
NextResponse.json(
{
code: "unauthorized:auth",
message: "You need to sign in before continuing.",
cause: "Session expired or invalid",
},
{ status: 401 },
),
),
);
}
const redirectUrl = isDesktopApp(request)
? new URL("/desktop-callback?error=unauthenticated", request.url)
: new URL("/login", request.url);
return withSessionCookieCleared(
withReferralCookie(request, NextResponse.redirect(redirectUrl)),
);
}
export default async function proxy(request: NextRequest) {
const pathname = request.nextUrl.pathname;
if (isUnsupportedRootPageRequest(request, pathname)) {
return NextResponse.json(
{
code: "method_not_allowed",
message: `${request.method} is not supported for this route.`,
},
{
status: 405,
headers: {
Allow: request.method === "POST" ? "GET, HEAD" : "GET, HEAD, POST",
},
},
);
}
if (shouldBypassAuthkit(pathname)) {
return NextResponse.next();
}
// Desktop app: redirect unauthenticated users to desktop-specific error page
if (isDesktopApp(request)) {
const hasSession = request.cookies.has("wos-session");
if (!hasSession && !isUnauthenticatedPath(pathname)) {
return withReferralCookie(
request,
NextResponse.redirect(
new URL("/desktop-callback?error=unauthenticated", request.url),
),
);
}
}
let refreshHitRateLimit = false;
let refreshEndedSession = false;
const hadSessionCookie = request.cookies.has("wos-session");
let authkitResult: Awaited<ReturnType<typeof authkit>>;
try {
authkitResult = await authkit(request, {
redirectUri: getRedirectUri(),
eagerAuth: true,
onSessionRefreshError: ({ error }) => {
if (isEndedSessionRefreshError(error)) {
refreshEndedSession = true;
console.info(
JSON.stringify({
timestamp: new Date().toISOString(),
level: "info",
event: "auth.session_refresh_ended",
service: "hackerai-web",
environment:
process.env.VERCEL_ENV ?? process.env.NODE_ENV ?? "unknown",
pathname,
}),
);
return;
}
if (isRateLimitError(error)) {
refreshHitRateLimit = true;
console.warn(
JSON.stringify({
timestamp: new Date().toISOString(),
level: "warn",
event: "auth.session_refresh_rate_limited",
service: "hackerai-web",
environment:
process.env.VERCEL_ENV ?? process.env.NODE_ENV ?? "unknown",
pathname,
}),
);
return;
}
console.warn(
JSON.stringify({
timestamp: new Date().toISOString(),
level: "warn",
event: "auth.session_refresh_failed",
service: "hackerai-web",
environment:
process.env.VERCEL_ENV ?? process.env.NODE_ENV ?? "unknown",
pathname,
error: error instanceof Error ? error.message : String(error),
}),
);
},
});
} catch (error) {
if (isEndedSessionRefreshError(error)) {
return buildEndedSessionResponse(request, pathname);
}
throw error;
}
const { session, headers, authorizationUrl } = authkitResult;
if (refreshEndedSession) {
return buildEndedSessionResponse(request, pathname);
}
const requestHeaders = buildRequestHeaders(request, headers);
const responseHeaders = buildResponseHeaders(headers);
if (session.user || isUnauthenticatedPath(pathname)) {
return withReferralCookie(
request,
NextResponse.next({
request: { headers: requestHeaders },
headers: responseHeaders,
}),
);
}
// If rate-limited (not a real session expiry), don't redirect to login
if (hadSessionCookie && refreshHitRateLimit) {
if (!isBrowserRequest(request)) {
const rateLimitHeaders = new Headers(responseHeaders);
rateLimitHeaders.set("Retry-After", "5");
return withReferralCookie(
request,
NextResponse.json(
{ code: "rate_limited", message: "Please retry shortly." },
{ status: 503, headers: rateLimitHeaders },
),
);
}
// For browser requests, let through rather than forcing a confusing login redirect
return withReferralCookie(
request,
NextResponse.next({
request: { headers: requestHeaders },
headers: responseHeaders,
}),
);
}
if (!isBrowserRequest(request)) {
return withReferralCookie(
request,
NextResponse.json(
{
code: "unauthorized:auth",
message: "You need to sign in before continuing.",
cause: "Session expired or invalid",
},
{ status: 401, headers: responseHeaders },
),
);
}
if (!authorizationUrl) {
console.error("[Auth Proxy] authorizationUrl unavailable", {
pathname,
hasSession: !!session.user,
});
const errorUrl = new URL("/auth-error", request.url);
errorUrl.searchParams.set("code", "503");
return withReferralCookie(
request,
NextResponse.redirect(errorUrl, { headers: responseHeaders }),
);
}
return withReferralCookie(
request,
NextResponse.redirect(authorizationUrl, { headers: responseHeaders }),
);
}
function buildRequestHeaders(
request: NextRequest,
authkitHeaders: Headers,
): Headers {
const merged = new Headers(request.headers);
authkitHeaders.forEach((value, key) => {
if (key.startsWith("x-")) {
merged.set(key, value);
}
});
return merged;
}
function buildResponseHeaders(authkitHeaders: Headers): Headers {
const responseHeaders = new Headers(authkitHeaders);
responseHeaders.delete(SESSION_HEADER);
return responseHeaders;
}
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};