-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
97 lines (78 loc) · 2.84 KB
/
middleware.ts
File metadata and controls
97 lines (78 loc) · 2.84 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const AUTH_COOKIE_NAME = 'admin_auth';
const COOKIE_MAX_AGE = 60 * 60 * 24; // 24 hours in seconds
/**
* Validates an authentication token in Edge runtime.
* Uses Web Crypto API which is available in Edge.
*/
async function validateAuthToken(token: string | undefined, secret: string): Promise<boolean> {
if (!token || !secret) {
return false;
}
const parts = token.split('.');
if (parts.length !== 2) {
return false;
}
const [timestamp, providedSignature] = parts;
// Check if token is expired or has invalid timestamp
const tokenAge = Date.now() - parseInt(timestamp, 10);
// Reject: NaN, negative (future timestamps), or expired tokens
if (isNaN(tokenAge) || tokenAge < 0 || tokenAge > COOKIE_MAX_AGE * 1000) {
return false;
}
// Regenerate the expected signature using Web Crypto API
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(timestamp));
const expectedSignature = Array.from(new Uint8Array(signatureBuffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
// Timing-safe comparison
if (providedSignature.length !== expectedSignature.length) {
return false;
}
let result = 0;
for (let i = 0; i < providedSignature.length; i++) {
result |= providedSignature.charCodeAt(i) ^ expectedSignature.charCodeAt(i);
}
return result === 0;
}
export async function middleware(request: NextRequest) {
const adminPath = process.env.ADMIN_PATH;
const authSecret = process.env.AUTH_SECRET;
// If env vars not set, let the request through - pages will handle the error
if (!adminPath || !authSecret) {
console.error('ADMIN_PATH or AUTH_SECRET environment variable is not set');
return NextResponse.next();
}
const { pathname } = request.nextUrl;
const authCookie = request.cookies.get(AUTH_COOKIE_NAME);
// Protected dashboard route: /p/${ADMIN_PATH}
if (pathname === `/p/${adminPath}`) {
const isValid = await validateAuthToken(authCookie?.value, authSecret);
if (!isValid) {
// Redirect to login page
const loginUrl = new URL(`/p/${adminPath}/login`, request.url);
return NextResponse.redirect(loginUrl);
}
}
// If already authenticated and trying to access login page, redirect to dashboard
if (pathname === `/p/${adminPath}/login`) {
const isValid = await validateAuthToken(authCookie?.value, authSecret);
if (isValid) {
const dashboardUrl = new URL(`/p/${adminPath}`, request.url);
return NextResponse.redirect(dashboardUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/p/:id*'],
};