-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
308 lines (274 loc) · 9.06 KB
/
middleware.ts
File metadata and controls
308 lines (274 loc) · 9.06 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
// Copyright (c) 2025 Benjamin F. Hall
// SPDX-License-Identifier: MIT
import { createServerClient } from '@supabase/ssr';
import { NextResponse, type NextRequest } from 'next/server';
import { getStoreConfig } from './src/server/storeConfig';
// Fail fast if the deployment hasn't selected a provenance store.
getStoreConfig();
function parseEnvFlag(value: string | undefined): boolean {
if (!value) return false;
const normalized = value.trim().toLowerCase();
return normalized === '1' || normalized === 'true' || normalized === 'yes' || normalized === 'on';
}
function isMaintenanceModeEnabled(): boolean {
return parseEnvFlag(process.env.RT_MAINTENANCE_MODE ?? process.env.MAINTENANCE_MODE);
}
function getAdminUserIds(): Set<string> {
const raw = process.env.RT_ADMIN_USER_IDS ?? '';
const ids = raw
.split(',')
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
return new Set(ids);
}
function stripTrailingSlashes(value: string): string {
let result = value;
while (result.endsWith('/')) {
result = result.slice(0, -1);
}
return result;
}
function getSupabaseEnv() {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim();
const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY?.trim();
if (!url || !anonKey) return null;
return { url, anonKey };
}
function isDesktopRuntime(): boolean {
if (process.env.RT_DESKTOP !== '1') return false;
const origin = process.env.RT_APP_ORIGIN ?? '';
return origin.startsWith('http://127.0.0.1:') || origin.startsWith('http://localhost:');
}
function hasAnySupabaseEnv(): boolean {
if (isDesktopRuntime()) {
return false;
}
return Boolean(
process.env.NEXT_PUBLIC_SUPABASE_URL ||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||
process.env.SUPABASE_SERVICE_ROLE_KEY
);
}
function isExplicitLocalMode(): boolean {
return (process.env.RT_PG_ADAPTER ?? '').toLowerCase() === 'local' && (process.env.RT_STORE ?? '').toLowerCase() === 'pg';
}
function isPublicPath(pathname: string): boolean {
if (pathname.startsWith('/assets/')) return true;
if (pathname === '/login') return true;
if (pathname === '/check-email') return true;
if (pathname === '/forgot-password') return true;
if (pathname === '/reset-password') return true;
if (pathname === '/waitlist') return true;
if (pathname.startsWith('/auth/')) return true;
return false;
}
function shouldApplyClickjackingProtection(pathname: string): boolean {
if (pathname === '/login') return true;
if (pathname === '/check-email') return true;
if (pathname === '/forgot-password') return true;
if (pathname === '/reset-password') return true;
if (pathname.startsWith('/auth/')) return true;
return false;
}
function withClickjackingHeaders(pathname: string, response: NextResponse): NextResponse {
if (!shouldApplyClickjackingProtection(pathname)) {
return response;
}
response.headers.set('X-Frame-Options', 'DENY');
response.headers.set('Content-Security-Policy', "frame-ancestors 'none'");
return response;
}
function sanitizeRedirectTo(input: string | null): string | null {
if (!input) return null;
if (!input.startsWith('/')) return null;
if (input.startsWith('//')) return null;
return input;
}
function buildMaintenanceResponse(request: NextRequest): NextResponse {
const retryAfter = '600';
if (request.nextUrl.pathname.startsWith('/api')) {
return NextResponse.json(
{
error: 'maintenance',
message: 'Service temporarily unavailable. Please try again soon.'
},
{
status: 503,
headers: {
'Cache-Control': 'no-store',
'Retry-After': retryAfter
}
}
);
}
const appName = (process.env.NEXT_PUBLIC_APP_NAME ?? 'threds').trim() || 'threds';
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Maintenance</title>
<style>
:root {
color-scheme: light;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, "Times New Roman", serif;
background:
radial-gradient(1100px 700px at 10% -10%, rgba(34, 197, 94, 0.15), transparent),
radial-gradient(900px 600px at 100% 0%, rgba(14, 165, 233, 0.2), transparent),
#f8fafc;
color: #0f172a;
}
.wrap {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 32px 20px;
}
.card {
width: min(560px, 100%);
background: #ffffff;
border-radius: 18px;
border: 1px solid #e2e8f0;
box-shadow: 0 20px 50px rgba(15, 23, 42, 0.12);
padding: 32px 34px;
}
.badge {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-radius: 999px;
background: #ecfdf3;
color: #166534;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
font-weight: 600;
}
h1 {
margin: 18px 0 10px;
font-size: 28px;
line-height: 1.2;
}
p {
margin: 0 0 14px;
color: #475569;
font-size: 16px;
line-height: 1.6;
}
.muted {
font-size: 14px;
color: #64748b;
}
</style>
</head>
<body>
<main class="wrap">
<section class="card" role="status" aria-live="polite">
<span class="badge">Maintenance</span>
<h1>We are tuning things up</h1>
<p>${appName} is temporarily offline while we roll out updates. Your work is safe and will be right here when we are back.</p>
<p class="muted">Thanks for your patience. Please check back soon.</p>
</section>
</main>
</body>
</html>`;
return new NextResponse(html, {
status: 503,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
'Retry-After': retryAfter
}
});
}
function withSupabaseCookies(source: NextResponse, target: NextResponse): NextResponse {
for (const cookie of source.cookies.getAll()) {
target.cookies.set(cookie);
}
return target;
}
export async function middleware(request: NextRequest) {
const maintenanceEnabled = isMaintenanceModeEnabled();
const adminUserIds = maintenanceEnabled ? getAdminUserIds() : new Set<string>();
const pathname = request.nextUrl.pathname;
if (maintenanceEnabled && adminUserIds.size === 0) {
return withClickjackingHeaders(pathname, buildMaintenanceResponse(request));
}
if (!maintenanceEnabled && pathname.startsWith('/api')) {
return NextResponse.next();
}
const anySupabaseEnv = hasAnySupabaseEnv();
if (isExplicitLocalMode() && !anySupabaseEnv) {
if (maintenanceEnabled) {
return withClickjackingHeaders(pathname, buildMaintenanceResponse(request));
}
return withClickjackingHeaders(pathname, NextResponse.next());
}
const supabaseEnv = getSupabaseEnv();
if (!supabaseEnv) {
if (maintenanceEnabled) {
return withClickjackingHeaders(pathname, buildMaintenanceResponse(request));
}
if (anySupabaseEnv) {
return withClickjackingHeaders(pathname, new NextResponse('Supabase env is incomplete', { status: 500 }));
}
return withClickjackingHeaders(pathname, NextResponse.next());
}
let response = NextResponse.next({
request: {
headers: request.headers
}
});
const supabase = createServerClient(supabaseEnv.url, supabaseEnv.anonKey, {
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
for (const { name, value, options } of cookiesToSet) {
response.cookies.set(name, value, options);
}
}
}
});
const { data } = await supabase.auth.getUser();
const user = data.user;
if (maintenanceEnabled) {
const userId = user?.id ?? null;
if (!userId || !adminUserIds.has(userId)) {
return withClickjackingHeaders(pathname, buildMaintenanceResponse(request));
}
}
if (pathname.startsWith('/api')) {
return response;
}
if (user && pathname === '/login') {
const redirectTo = sanitizeRedirectTo(request.nextUrl.searchParams.get('redirectTo')) ?? '/';
const redirectUrl = new URL(redirectTo, request.url);
response = withSupabaseCookies(response, NextResponse.redirect(redirectUrl));
return withClickjackingHeaders(pathname, response);
}
if (isPublicPath(pathname)) {
return withClickjackingHeaders(pathname, response);
}
if (!user) {
const redirectUrl = request.nextUrl.clone();
redirectUrl.pathname = '/login';
redirectUrl.searchParams.set('redirectTo', `${request.nextUrl.pathname}${request.nextUrl.search}`);
redirectUrl.searchParams.set('mode', 'signin');
redirectUrl.hash = 'existing-user';
response = withSupabaseCookies(response, NextResponse.redirect(redirectUrl));
}
return withClickjackingHeaders(pathname, response);
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
};