-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproxy.ts
More file actions
59 lines (50 loc) · 1.83 KB
/
proxy.ts
File metadata and controls
59 lines (50 loc) · 1.83 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
// src/proxy.ts
import { type NextRequest, NextResponse } from "next/server"
import { shouldSecureCookies } from "@/lib/cookie-security"
const PUBLIC_EXACT = ["/login", "/setup", "/api/health"]
const PUBLIC_PREFIX = ["/api/auth/", "/api/verify-report", "/_next/", "/img/", "/favicon"]
const SESSION_COOKIE = "tt_session"
const MAX_AGE_COOKIE = "tt_max_age"
const MAX_COOKIE_AGE = 60 * 60 * 24 * 30 // 30-day hard cap
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (PUBLIC_EXACT.includes(pathname) || PUBLIC_PREFIX.some((p) => pathname.startsWith(p))) {
return NextResponse.next()
}
const session = request.cookies.get(SESSION_COOKIE)
if (!session) {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
return NextResponse.redirect(new URL("/login", request.url))
}
// Sliding window: re-set both cookies with a fresh maxAge on every
// authenticated request. This extends the inactivity timeout without
// needing to decrypt or re-create the JWE.
const response = NextResponse.next()
const maxAgeStr = request.cookies.get(MAX_AGE_COOKIE)?.value
const maxAge = maxAgeStr ? parseInt(maxAgeStr, 10) : null
if (maxAge && maxAge > 0 && maxAge <= MAX_COOKIE_AGE) {
const secureCookies = shouldSecureCookies()
response.cookies.set(SESSION_COOKIE, session.value, {
httpOnly: true,
secure: secureCookies,
sameSite: "strict",
maxAge,
path: "/",
})
response.cookies.set(MAX_AGE_COOKIE, String(maxAge), {
httpOnly: true,
secure: secureCookies,
sameSite: "strict",
maxAge,
path: "/",
})
}
return response
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.png|tracker-logos|trackerHub_logo|trackerTracker_logo).*)",
],
}