-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproxy.ts
More file actions
199 lines (165 loc) · 5.7 KB
/
Copy pathproxy.ts
File metadata and controls
199 lines (165 loc) · 5.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
import { NextRequest, NextResponse } from "next/server";
import { decode } from "@auth/core/jwt";
// Pages that require authentication
const PROTECTED_PAGES = ["/settings", "/admin"];
// Pages that require admin role specifically
const ADMIN_ONLY_PAGES = ["/admin"];
// API routes that use their own auth (Bearer token)
const EXTENSION_API_PATHS = [
"/api/extension/",
"/api/ingest",
"/api/remote/",
];
// API routes that are always public (any method)
const PUBLIC_API_PATHS = [
"/api/auth/",
"/api/setup/",
"/api/admin/setup",
"/api/r2/",
"/api/local-media/",
];
// POST routes accessible without authentication
const PUBLIC_POST_PATHS: string[] = [];
// GET routes that trigger mutations or expensive operations — admin only
const ADMIN_ONLY_GET_PATHS = [
"/api/backfill/",
"/api/media/backfill",
"/api/media/local-backfill",
"/api/embeddings/",
"/api/search/reindex",
"/api/data/",
"/api/export",
];
// Static/framework paths — skip entirely
const SKIP_PATHS = ["/_next", "/favicon.ico"];
// Public non-API paths that should be reachable without a session.
const PUBLIC_PAGE_PATHS = ["/privacy-policy", "/launch"];
function matchPath(pathname: string, pattern: string): boolean {
if (pattern.endsWith("/")) {
return pathname.startsWith(pattern);
}
return pathname === pattern ||
pathname.startsWith(pattern + "/") ||
pathname.startsWith(pattern + "?");
}
function matchAny(pathname: string, patterns: string[]): boolean {
return patterns.some((p) => matchPath(pathname, p));
}
/**
* Extract role from the NextAuth JWT session cookie.
* Returns the role string, or null if the token can't be decoded.
*/
async function getRoleFromToken(request: NextRequest): Promise<string | null> {
const secret = process.env.AUTH_SECRET;
if (!secret) return null;
const sessionToken =
request.cookies.get("__Secure-authjs.session-token")?.value ||
request.cookies.get("authjs.session-token")?.value;
if (!sessionToken) return null;
try {
const token = await decode({
token: sessionToken,
secret,
salt: request.cookies.has("__Secure-authjs.session-token")
? "__Secure-authjs.session-token"
: "authjs.session-token",
});
return (token?.role as string) ?? "viewer";
} catch {
return null;
}
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const method = request.method;
// Skip framework paths
if (SKIP_PATHS.some((p) => pathname.startsWith(p))) {
return NextResponse.next();
}
// Onboarding check (existing logic)
if (
!pathname.startsWith("/onboarding") &&
pathname !== "/login" &&
!pathname.startsWith("/api/")
) {
const hasEnv = Boolean(process.env.DATABASE_URL && process.env.DATABASE_TYPE);
const configured = request.cookies.get("scrollback-configured");
if (!hasEnv && configured?.value !== "true") {
return NextResponse.redirect(new URL("/onboarding", request.url));
}
}
// Public POST paths — allow without auth
if (matchAny(pathname, PUBLIC_POST_PATHS) && method === "POST") {
return NextResponse.next();
}
// Extension API routes — handled by their own Bearer token auth
if (matchAny(pathname, EXTENSION_API_PATHS)) {
return NextResponse.next();
}
// Public API routes — allow all methods
// But check admin-only GET paths first (more specific takes priority)
if (matchAny(pathname, PUBLIC_API_PATHS) && !matchAny(pathname, ADMIN_ONLY_GET_PATHS)) {
return NextResponse.next();
}
const protectedApi =
pathname.startsWith("/api/") &&
!matchAny(pathname, EXTENSION_API_PATHS) &&
!matchAny(pathname, PUBLIC_API_PATHS);
const isAdminOnlyGet = matchAny(pathname, ADMIN_ONLY_GET_PATHS);
// All pages require auth except /login, /onboarding, and public marketing/legal pages
const isPublicPage =
pathname === "/login" ||
pathname.startsWith("/onboarding") ||
matchAny(pathname, PUBLIC_PAGE_PATHS);
const isPage = !pathname.startsWith("/api/");
const needsAuth =
(isPage && !isPublicPage) ||
PROTECTED_PAGES.some((p) => pathname.startsWith(p)) ||
protectedApi ||
isAdminOnlyGet;
if (!needsAuth) {
return NextResponse.next();
}
// Check for NextAuth session token (same cookie check as the original middleware)
const sessionToken =
request.cookies.get("__Secure-authjs.session-token") ||
request.cookies.get("authjs.session-token");
if (!sessionToken) {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
if (process.env.SCROLLBACK_PUBLIC_DEMO === "true") {
loginUrl.searchParams.set("demo", "1");
}
return NextResponse.redirect(loginUrl);
}
// --- Role enforcement for authenticated users ---
const role = await getRoleFromToken(request) ?? "viewer";
if (role === "admin") {
return NextResponse.next();
}
// Non-admin: block admin-only pages
if (ADMIN_ONLY_PAGES.some((p) => pathname.startsWith(p))) {
return NextResponse.redirect(new URL("/?denied=1", request.url));
}
// Non-admin: block admin-only GET paths (mutations disguised as GETs)
if (isAdminOnlyGet) {
return NextResponse.json(
{ error: "Demo account is view-only" },
{ status: 403 }
);
}
// Non-admin: block all non-GET/HEAD API requests (default-deny)
if (pathname.startsWith("/api/") && method !== "GET" && method !== "HEAD") {
return NextResponse.json(
{ error: "Demo account is view-only" },
{ status: 403 }
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};