Repository navigation
Expand file tree
/
Copy pathrequest-handler.ts
More file actions
221 lines (202 loc) · 7.74 KB
/
Copy pathrequest-handler.ts
File metadata and controls
221 lines (202 loc) · 7.74 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
import { type RequestEvent, redirect } from "@sveltejs/kit";
import type { Handle } from "@sveltejs/kit/hooks";
import type { AuthPrincipal } from "$lib/server/core/auth/model";
/**
* Shared SvelteKit request policy: enforce session auth outside the explicit
* public paths, attach browser security headers to every response, and gzip
* HTML/JSON when the client accepts it. API auth failures remain JSON while
* unauthenticated page requests redirect to login; SSE is never compressed by
* this handler.
*/
interface RequestHandlerConfig {
authEnabled: boolean;
resolveSession: (token: string) => AuthPrincipal | null;
sessionCookie: string;
}
const securityHeaders: Record<string, string> = {
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
};
const PUBLIC_PATHS = new Set(["/login", "/logout", "/api/health", "/api/ready"]);
const METRICS_PATH = "/api/metrics";
const PASSWORD_CHANGE_PATH = "/account/password";
const UNSAFE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
// Use resolved route IDs so SvelteKit page-data requests cannot bypass the policy.
// The route access inventory in src/routes/route-access.test.ts checks this policy.
const operatorReads = new Set([
"/",
"/profile",
"/profile/[id]",
"/migrate",
"/migrate/[id]",
"/migrate/batches/[id]",
"/api/profile/[id]",
"/api/migrate/[id]",
"/api/migrate/[id]/events",
]);
const operatorWrites = new Set([
"POST /api/profile/[id]",
"DELETE /api/migrate/[id]",
"POST /api/migrate/[id]/restart",
]);
function applySecurityHeaders(response: Response): Response {
for (const [key, value] of Object.entries(securityHeaders)) {
response.headers.set(key, value);
}
return response;
}
function acceptedEncodingQuality(header: string, encoding: string): number {
let explicitQuality: number | undefined;
let wildcardQuality: number | undefined;
for (const item of header.split(",")) {
const [rawCoding = "", ...parameters] = item.split(";");
const coding = rawCoding.trim().toLowerCase();
if (coding !== encoding && coding !== "*") continue;
let quality = 1;
for (const parameter of parameters) {
const [rawName = "", rawValue = ""] = parameter.split("=", 2);
if (rawName.trim().toLowerCase() !== "q") continue;
const parsed = Number(rawValue.trim());
quality = Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : 0;
break;
}
if (coding === encoding) {
explicitQuality = Math.max(explicitQuality ?? 0, quality);
} else {
wildcardQuality = Math.max(wildcardQuality ?? 0, quality);
}
}
return explicitQuality ?? wildcardQuality ?? 0;
}
function appendVary(response: Response, field: string): void {
const vary = response.headers.get("vary");
if (!vary) {
response.headers.set("vary", field);
return;
}
if (
vary !== "*" &&
!vary.split(",").some((value) => value.trim().toLowerCase() === field.toLowerCase())
) {
response.headers.set("vary", `${vary}, ${field}`);
}
}
/** Session-exempt requests: the public paths and metrics scrapes, which carry their own token. */
function isSessionExempt(event: RequestEvent): boolean {
const isMetricsScrape =
event.url.pathname === METRICS_PATH &&
(event.request.method === "GET" || event.request.method === "HEAD");
return PUBLIC_PATHS.has(event.url.pathname) || isMetricsScrape;
}
function jsonError(status: number, error: string): Response {
return applySecurityHeaders(
new Response(JSON.stringify({ error }), {
status,
headers: { "Content-Type": "application/json" },
}),
);
}
/** API clients get a JSON error; pages are redirected to where the user can resolve it. */
function refuseRequest(
event: RequestEvent,
status: number,
error: string,
location: string,
): Response {
if (event.url.pathname.startsWith("/api/")) return jsonError(status, error);
redirect(302, location);
}
/** Returns a response that ends the request, or null to continue to the next step. */
type RequestStep = (event: RequestEvent) => Response | null;
function authenticate(config: RequestHandlerConfig): RequestStep {
return (event) => {
const sessionCookie = event.cookies.get(config.sessionCookie);
const principal = sessionCookie ? config.resolveSession(sessionCookie) : null;
if (principal) {
event.locals.user = principal.user;
event.locals.sessionTokenHash = principal.sessionTokenHash;
return null;
}
return isSessionExempt(event) ? null : refuseRequest(event, 401, "Unauthorized", "/login");
};
}
function requirePasswordChange(event: RequestEvent): Response | null {
if (
!event.locals.user?.mustChangePassword ||
event.url.pathname === PASSWORD_CHANGE_PATH ||
isSessionExempt(event)
) {
return null;
}
return refuseRequest(event, 403, "Password change required", PASSWORD_CHANGE_PATH);
}
// Runs whether or not authentication is enabled: an unauthenticated instance
// still must not accept API writes driven by another site.
function rejectCrossOriginWrites(event: RequestEvent): Response | null {
const requestOrigin = event.request.headers.get("origin");
if (
event.url.pathname.startsWith("/api/") &&
UNSAFE_METHODS.has(event.request.method) &&
requestOrigin !== null &&
requestOrigin !== event.url.origin
) {
return jsonError(403, "Cross-origin API requests are forbidden");
}
return null;
}
// Operators reach only the listed shared routes, the public routes and the
// password page; any other route answers 404 before it resolves.
function enforceOperatorRoutes(event: RequestEvent): Response | null {
if (event.locals.user?.role !== "operator") return null;
const route = event.route.id ?? "";
const allowed = ["GET", "HEAD"].includes(event.request.method)
? operatorReads.has(route)
: operatorWrites.has(`${event.request.method} ${route}`);
if (PUBLIC_PATHS.has(route) || route === PASSWORD_CHANGE_PATH || allowed) return null;
return applySecurityHeaders(new Response("Not found", { status: 404 }));
}
/** Gzips HTML and JSON when the client accepts it; SSE and encoded bodies pass through. */
function compress(request: Request, response: Response): Response {
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("text/html") && !contentType.includes("application/json")) {
return response;
}
appendVary(response, "Accept-Encoding");
const acceptEncoding = request.headers.get("accept-encoding") || "";
if (
acceptedEncodingQuality(acceptEncoding, "gzip") <= 0 ||
response.headers.has("content-encoding") ||
!response.body
) {
return response;
}
const headers = new Headers(response.headers);
headers.set("content-encoding", "gzip");
headers.delete("content-length");
return new Response(response.body.pipeThrough(new CompressionStream("gzip")), {
status: response.status,
statusText: response.statusText,
headers,
});
}
export function createRequestHandler(config: RequestHandlerConfig): Handle {
// Order matters: identity first, then the password gate, then checks that
// read the established identity. Each step may end the request.
const steps: RequestStep[] = [
...(config.authEnabled ? [authenticate(config), requirePasswordChange] : []),
rejectCrossOriginWrites,
enforceOperatorRoutes,
];
return async ({ event, resolve }) => {
event.locals.authEnabled = config.authEnabled;
for (const step of steps) {
const refusal = step(event);
if (refusal) return refusal;
}
const response = applySecurityHeaders(await resolve(event));
if (event.locals.user) response.headers.set("cache-control", "private, no-store");
return compress(event.request, response);
};
}