-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathproxy.ts
More file actions
539 lines (486 loc) · 18.7 KB
/
proxy.ts
File metadata and controls
539 lines (486 loc) · 18.7 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
* Proxy - Auth caching
*
* IMPORTANT: Uses native Response everywhere to avoid polyfill conflicts.
* The mcp-handler package triggers undici's Response polyfill which breaks
* NextResponse instanceof checks. We use x-middleware-next header instead.
* See: https://github.com/vercel/next.js/issues/58611
*/
import { PrivyClient } from "@privy-io/server-auth";
import { Redis } from "@upstash/redis";
import type { NextRequest } from "next/server";
import { jsonError } from "@/lib/api/errors";
import { CORS_ALLOW_HEADERS, CORS_ALLOW_METHODS, CORS_MAX_AGE } from "@/lib/cors-constants";
// Helper to create "next" response (continue to route handler)
// Uses internal Next.js header that NextResponse.next() sets
function middlewareNext(options?: {
headers?: Record<string, string>;
requestHeaders?: Headers;
}): Response {
const headers = new Headers(options?.headers);
headers.set("x-middleware-next", "1");
// Forward modified request headers if provided
if (options?.requestHeaders) {
const headersList: string[] = [];
options.requestHeaders.forEach((value, key) => {
headersList.push(`${key}:${value}`);
});
if (headersList.length > 0) {
headers.set(
"x-middleware-override-headers",
Array.from(options.requestHeaders.keys()).join(","),
);
options.requestHeaders.forEach((value, key) => {
headers.set(`x-middleware-request-${key}`, value);
});
}
}
return new Response(null, { status: 200, headers });
}
// Helper to create redirect response
function middlewareRedirect(
url: URL | string,
options?: { headers?: Record<string, string>; deleteCookies?: string[] },
): Response {
const headers = new Headers(options?.headers);
headers.set("Location", url.toString());
// Set cookies to delete
if (options?.deleteCookies) {
for (const cookie of options.deleteCookies) {
headers.append("Set-Cookie", `${cookie}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`);
}
}
return new Response(null, { status: 307, headers });
}
const privyClient = new PrivyClient(
process.env.NEXT_PUBLIC_PRIVY_APP_ID!,
process.env.PRIVY_APP_SECRET!,
);
let redis: Redis | null = null;
function getRedis(): Redis | null {
if (redis) return redis;
const url = process.env.KV_REST_API_URL || process.env.UPSTASH_REDIS_REST_URL;
const token = process.env.KV_REST_API_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN;
if (url && token) redis = new Redis({ url, token });
return redis;
}
const AUTH_CACHE_TTL = 300;
const PLAYWRIGHT_TEST_SESSION_COOKIE_NAME = "eliza-test-session";
interface CachedAuth {
valid: boolean;
userId?: string;
expiration?: number;
reason?: "expired" | "invalid";
cachedAt: number;
}
function hashToken(token: string): string {
let hash = 0;
for (let i = 0; i < Math.min(token.length, 100); i++) {
hash = (hash << 5) - hash + token.charCodeAt(i);
hash = hash & hash;
}
return Math.abs(hash).toString(36);
}
async function getCachedAuth(token: string): Promise<CachedAuth | null> {
const client = getRedis();
if (!client) return null;
try {
const cached = await client.get<CachedAuth | string>(`proxy:auth:${hashToken(token)}`);
if (!cached) return null;
// Handle both old string format and new object format
if (typeof cached === "string") {
// Skip corrupted cache entries (e.g., "[object Object]")
if (cached === "[object Object]" || !cached.startsWith("{")) {
return null;
}
return JSON.parse(cached);
}
// Validate it's actually a CachedAuth object
if (typeof cached === "object" && "valid" in cached && "cachedAt" in cached) {
return cached;
}
return null;
} catch (error) {
// Silently ignore corrupted cache entries (e.g., "[object Object]" stored incorrectly)
// This happens when Upstash tries to auto-parse invalid JSON - just fall back to fresh auth
const errorMessage = error instanceof Error ? error.message : String(error);
if (errorMessage.includes("is not valid JSON")) {
return null;
}
// Log other unexpected Redis errors but don't block auth
console.warn("[Proxy] Redis cache read failed:", errorMessage);
return null;
}
}
async function setCachedAuth(token: string, auth: CachedAuth): Promise<void> {
const client = getRedis();
if (!client) return;
try {
await client.setex(`proxy:auth:${hashToken(token)}`, AUTH_CACHE_TTL, JSON.stringify(auth));
} catch (error) {
// Log Redis write errors but don't block auth - caching is best-effort
console.warn(
"[Proxy] Redis cache write failed:",
error instanceof Error ? error.message : String(error),
);
}
}
function isJwtExpiredError(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const e = error as { code?: unknown; claim?: unknown; reason?: unknown };
return e.code === "ERR_JWT_EXPIRED" || (e.claim === "exp" && e.reason === "check_failed");
}
function isInvalidOrMalformedJwtError(error: unknown): boolean {
if (!error || typeof error !== "object" || isJwtExpiredError(error)) return false;
const e = error as { code?: unknown; name?: unknown; message?: unknown };
const code = typeof e.code === "string" ? e.code : "";
const name = typeof e.name === "string" ? e.name : "";
const message = typeof e.message === "string" ? e.message : "";
return (
code === "ERR_JWS_INVALID" ||
code === "ERR_JWT_INVALID" ||
code === "ERR_JWT_MALFORMED" ||
code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED" ||
name === "JWSInvalid" ||
name === "JWTInvalid" ||
name === "JWTMalformed" ||
name === "JWSSignatureVerificationFailed" ||
message.includes("Invalid Compact JWS") ||
message.includes("JWSInvalid") ||
message.includes("JWTInvalid") ||
message.includes("JWTMalformed") ||
message.includes("JWSSignatureVerificationFailed") ||
message.toLowerCase().includes("invalid jwt")
);
}
function isObviouslyMalformedToken(token: string): boolean {
const normalized = token.trim();
if (normalized.length === 0 || /\s/.test(normalized)) {
return true;
}
const segments = normalized.split(".");
return segments.length !== 3 || segments.some((segment) => segment.length === 0);
}
function buildLoginRedirectUrl(request: NextRequest): URL {
const url = request.nextUrl.clone();
const returnTo = `${url.pathname}${url.search}`;
url.pathname = "/login";
url.search = "";
url.searchParams.set("returnTo", returnTo || "/dashboard");
return url;
}
function handleTokenFailure(
request: NextRequest,
pathname: string,
startTime: number,
reason: "expired" | "invalid",
options?: { clearCookies?: boolean },
): Response {
if (pathname.startsWith("/api/")) {
const errorMessage = reason === "expired" ? "Token expired" : "Invalid authentication token";
return jsonError(errorMessage, 401, "authentication_required", {
"X-Proxy-Time": `${Date.now() - startTime}ms`,
});
}
return middlewareRedirect(buildLoginRedirectUrl(request), {
deleteCookies: options?.clearCookies ? ["privy-token", "privy-id-token"] : undefined,
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
});
}
const publicPaths = [
"/",
"/marketplace",
"/payment/success",
"/dashboard/chat",
"/dashboard/build",
"/chat",
"/api/health",
"/api/eliza",
"/api/models",
"/api/fal/proxy",
"/api/og",
"/api/public",
"/auth/error",
"/auth/cli-login",
"/api/auth/pair", // Milady agent pairing (validates its own one-time tokens)
"/api/auth/siwe", // SIWE nonce + verify (EIP-4361)
"/api/auth/steward-session", // Steward session cookie bridge
"/api/auth/steward-debug", // Debug endpoint (temporary) (validates its own JWT)
"/api/set-anonymous-session",
"/api/anonymous-session",
"/api/auth/create-anonymous-session",
"/api/affiliate",
"/api/v1/generate-image",
"/api/v1/generate-video",
"/api/v1/chat",
"/api/v1/chat/completions",
"/api/v1/messages",
"/api/v1/responses",
"/api/v1/embeddings",
"/api/v1/models",
"/api/v1/credits/topup",
"/api/v1/topup", // x402 payment-gated topup (auth via payment proof, not session)
"/api/stripe/credit-packs", // Public catalog of purchasable credit packs
"/api/stripe/webhook",
"/api/crypto/webhook",
"/api/privy/webhook",
"/api/cron",
"/api/v1/cron",
"/api/mcps",
"/api/mcp/list",
"/api/mcp",
"/api/a2a",
"/api/agents",
"/api/v1/track",
"/api/v1/discovery", // Public discovery endpoint for agents/MCPs
"/api/v1/discord/callback", // Discord OAuth callback (redirects from Discord)
"/api/v1/twitter/callback", // Twitter OAuth callback
"/api/v1/oauth/providers", // Public endpoint - list available OAuth providers
"/api/v1/oauth/callback", // Legacy OAuth callback wrapper (redirects from providers)
"/api/v1/app-auth",
"/app-auth",
"/.well-known",
"/api/.well-known", // JWKS endpoint for JWT verification
"/api/internal", // Internal service-to-service API (has own auth via JWT Bearer token)
"/api/webhooks", // Twilio, Blooio webhooks (they verify their own signatures)
"/api/v1/telegram/webhook", // Telegram webhook (validates via bot token lookup)
"/api/eliza-app/auth", // Eliza App public auth endpoints
"/api/eliza-app/webhook", // Eliza App webhooks (they verify their own signatures)
"/api/eliza-app/user", // Eliza App user endpoints (uses own session validation)
"/api/eliza-app/cli-auth", // Eliza app CLI authorization endpoints
"/api/eliza-app/provision-agent", // Eliza CLI provisioning endpoint
"/api/eliza-app/gateway", // Eliza CLI gateway proxies
];
const publicPathPatterns = [
/^\/api\/v1\/apps\/[^/]+\/public$/,
/^\/api\/characters\/[^/]+\/public$/,
/^\/api\/v1\/oauth\/[^/]+\/callback$/, // Generic OAuth callbacks (redirects from providers)
/^\/api\/auth\/cli-session\/?$/, // POST create session (not /complete — that needs session auth at edge)
/^\/api\/auth\/cli-session\/[^/]+$/, // GET poll session status (CLI); excludes .../sessionId/complete
];
const protectedPaths = [
"/dashboard",
"/api/v1/user",
"/api/v1/organization",
"/api/v1/api-keys",
"/api/v1/usage",
"/api/v1/generations",
"/api/v1/containers",
];
/**
* Cookie-session-only paths for API-key-shaped credentials (`X-API-Key`, `Bearer eliza_*`).
*
* Why: The block below skips Privy when those headers are present so handlers can validate keys.
* Cookie-only handlers would then return a generic 401. Failing here with `session_auth_required`
* tells integrators this URL expects a browser session, not automation keys.
*
* Wallet passthrough uses a separate branch and is not treated as programmatic auth.
* See docs/auth-api-consistency.md.
*/
const sessionOnlyPaths = [
"/api/auth/migrate-anonymous",
"/api/invites/accept",
"/api/organizations/invites",
"/api/organizations/members",
"/api/signup-code/redeem",
"/api/v1/api-keys",
"/api/v1/api-keys/explorer",
"/api/v1/generate-prompts",
"/api/v1/character-assistant",
"/api/stripe/create-checkout-session",
"/api/my-agents/claim-affiliate-characters",
];
const sessionOnlyPathPatterns = [
/^\/api\/auth\/cli-session\/[^/]+\/complete$/,
/^\/api\/my-agents\/characters\/[^/]+\/track-interaction$/,
/^\/api\/crypto\/payments\/[^/]+\/confirm$/,
];
function isSessionOnlyPath(pathname: string): boolean {
return (
sessionOnlyPaths.some((p) => pathname === p || pathname.startsWith(`${p}/`)) ||
sessionOnlyPathPatterns.some((pattern) => pattern.test(pathname))
);
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const startTime = Date.now();
// Handle CORS preflight (OPTIONS) requests for API routes
if (request.method === "OPTIONS" && pathname.startsWith("/api/")) {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": CORS_ALLOW_METHODS,
"Access-Control-Allow-Headers": CORS_ALLOW_HEADERS,
"Access-Control-Max-Age": CORS_MAX_AGE,
"X-Proxy-Time": `${Date.now() - startTime}ms`,
},
});
}
const isPublicPath =
publicPaths.some((p) => pathname === p || pathname.startsWith(`${p}/`)) ||
publicPathPatterns.some((pattern) => pattern.test(pathname));
if (isPublicPath) {
return middlewareNext({
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
});
}
const isProtectedPath = protectedPaths.some(
(p) => pathname === p || pathname.startsWith(`${p}/`),
);
if (!isProtectedPath && !pathname.startsWith("/api/")) {
return middlewareNext();
}
try {
const privyToken = request.cookies.get("privy-token");
const stewardToken = request.cookies.get("steward-token");
const authToken = privyToken || stewardToken;
const playwrightTestSession =
process.env.PLAYWRIGHT_TEST_AUTH === "true"
? request.cookies.get(PLAYWRIGHT_TEST_SESSION_COOKIE_NAME)
: undefined;
const authHeader = request.headers.get("Authorization");
const bearerToken = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;
// Steward tokens are HS256 (verified by getCurrentUser, not Privy)
// Just pass them through the middleware without Privy verification
if (stewardToken && !privyToken && !bearerToken) {
return middlewareNext({
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms`, "X-Auth-Source": "steward" },
});
}
const apiKey = request.headers.get("X-API-Key");
// Wallet-sig passthrough only for paths that verify the signature (getTopupRecipient or verifyWalletSignature)
const walletSig = request.headers.get("X-Wallet-Signature");
const allowWalletPassthrough =
pathname.startsWith("/api/v1/topup") || pathname.startsWith("/api/v1/user/wallets");
const hasElizaBearer = Boolean(bearerToken && bearerToken.startsWith("eliza_"));
const programmaticAuth = Boolean(apiKey || hasElizaBearer);
// Keys are verified in route handlers (DB), not in middleware — we only avoid burning Privy work.
if (programmaticAuth || (walletSig && allowWalletPassthrough)) {
// Align edge with cookie-only handlers: reject key/bearer early on session-only URLs.
if (programmaticAuth && isSessionOnlyPath(pathname)) {
return jsonError(
"This endpoint requires session authentication. API keys and Bearer tokens are not accepted.",
401,
"session_auth_required",
{ "X-Proxy-Time": `${Date.now() - startTime}ms` },
);
}
return middlewareNext({
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
});
}
if (playwrightTestSession?.value) {
return middlewareNext({
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
});
}
const token = bearerToken || authToken?.value;
const usingCookieToken = !bearerToken && token === authToken?.value;
if (!token) {
if (pathname.startsWith("/api/")) {
return jsonError("Unauthorized", 401, "authentication_required", {
"X-Proxy-Time": `${Date.now() - startTime}ms`,
});
}
return middlewareRedirect(buildLoginRedirectUrl(request), {
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
});
}
if (isObviouslyMalformedToken(token)) {
await setCachedAuth(token, { valid: false, reason: "invalid", cachedAt: Date.now() });
return handleTokenFailure(request, pathname, startTime, "invalid", {
clearCookies: usingCookieToken,
});
}
const cachedAuth = await getCachedAuth(token);
if (cachedAuth && !cachedAuth.valid) {
return handleTokenFailure(request, pathname, startTime, cachedAuth.reason ?? "invalid", {
clearCookies: usingCookieToken,
});
}
if (cachedAuth?.valid && cachedAuth.userId) {
if (cachedAuth.expiration) {
const now = Math.floor(Date.now() / 1000);
if (cachedAuth.expiration <= now) {
await setCachedAuth(token, { valid: false, cachedAt: Date.now() });
} else {
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-privy-user-id", cachedAuth.userId);
requestHeaders.set("x-auth-cached", "true");
return middlewareNext({
headers: {
"X-Proxy-Time": `${Date.now() - startTime}ms`,
"X-Auth-Cached": "true",
},
requestHeaders,
});
}
} else {
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-privy-user-id", cachedAuth.userId);
requestHeaders.set("x-auth-cached", "true");
return middlewareNext({
headers: {
"X-Proxy-Time": `${Date.now() - startTime}ms`,
"X-Auth-Cached": "true",
},
requestHeaders,
});
}
}
let user: Awaited<ReturnType<typeof privyClient.verifyAuthToken>> | null = null;
try {
user = await privyClient.verifyAuthToken(token);
} catch (error) {
if (isJwtExpiredError(error)) {
await setCachedAuth(token, { valid: false, reason: "expired", cachedAt: Date.now() });
return handleTokenFailure(request, pathname, startTime, "expired", {
clearCookies: usingCookieToken,
});
}
if (isInvalidOrMalformedJwtError(error)) {
await setCachedAuth(token, { valid: false, reason: "invalid", cachedAt: Date.now() });
return handleTokenFailure(request, pathname, startTime, "invalid", {
clearCookies: usingCookieToken,
});
}
throw error;
}
if (!user) {
await setCachedAuth(token, { valid: false, reason: "invalid", cachedAt: Date.now() });
return handleTokenFailure(request, pathname, startTime, "invalid", {
clearCookies: usingCookieToken,
});
}
await setCachedAuth(token, {
valid: true,
userId: user.userId,
expiration:
typeof (user as unknown as { expiration?: unknown }).expiration === "number"
? ((user as unknown as { expiration: number }).expiration as number)
: undefined,
cachedAt: Date.now(),
});
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-privy-user-id", user.userId);
return middlewareNext({
headers: { "X-Proxy-Time": `${Date.now() - startTime}ms` },
requestHeaders,
});
} catch (error) {
console.error("Proxy auth error:", error);
if (pathname.startsWith("/api/")) {
return jsonError("Authentication failed", 401, "authentication_required", {
"X-Proxy-Time": `${Date.now() - startTime}ms`,
});
}
const url = request.nextUrl.clone();
url.pathname = "/auth/error";
url.searchParams.set("reason", "auth_failed");
return middlewareRedirect(url);
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};