forked from Streampay-Org/StreamPay-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
259 lines (224 loc) · 8.14 KB
/
Copy pathmiddleware.ts
File metadata and controls
259 lines (224 loc) · 8.14 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
import { NextRequest, NextResponse } from 'next/server';
import { validateConfig } from './app/lib/config/index';
import {
buildAllowedOriginSet,
isOriginAllowed,
DEFAULT_CORS_HEADERS,
DEFAULT_CORS_METHODS,
DEFAULT_CORS_MAX_AGE_SECONDS,
} from './app/lib/cors';
import {
REQUEST_FINGERPRINT_HEADER,
captureRequestFingerprint,
} from './lib/fingerprint';
import {
checkRequestBodySize,
buildLimitsConfig,
} from './lib/bodySize';
import {
attachCsrfCookie,
createCsrfForbiddenResponse,
getCsrfCookieValue,
getCsrfHeaderValue,
isCsrfProtectedMethod,
validateCsrfToken,
} from './lib/csrf';
import {
REQUEST_ID_HEADER,
applyRequestIdPolicy,
resolveRequestId,
} from './lib/requestId';
import { getChaosConfig } from './lib/chaos';
import { touchLastSeenFromRequest } from './lib/lastSeen';
// ---------------------------------------------------------------------------
// Request body size cap
// ---------------------------------------------------------------------------
//
// Supports per-route body size limits:
// - Default routes: 256 KB (override via MAX_STREAM_BODY_BYTES)
// - Webhook routes (/api/webhooks/*): 1 MB (override via MAX_WEBHOOK_BODY_BYTES)
//
// The check is intentionally O(1): we read the Content-Length header rather
// than buffering the body. Clients that omit Content-Length are allowed
// through — the application layer is responsible for streaming limits.
//
// Only write methods (POST, PUT, PATCH) are checked; safe methods (GET, HEAD,
// OPTIONS, DELETE) are not expected to carry a body and are skipped.
// Build limits configuration at module initialization
const bodyLimits = buildLimitsConfig();
// Validate configuration at middleware initialization so invalid CORS settings fail early.
validateConfig();
const allowedOrigins = buildAllowedOriginSet(process.env.ALLOWED_ORIGINS);
// Chaos/fault injection config. Resolved once at module init; force-disabled in
// production by getChaosConfig regardless of env vars.
const chaosConfig = getChaosConfig();
export const config = {
matcher: ['/api/:path*'],
};
const CANARY_HEADER_NAME = 'X-Canary';
function buildCorsHeaders(origin: string) {
const headers = new Headers();
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Methods', DEFAULT_CORS_METHODS);
headers.set('Access-Control-Allow-Headers', DEFAULT_CORS_HEADERS);
headers.set('Access-Control-Max-Age', String(DEFAULT_CORS_MAX_AGE_SECONDS));
headers.set('Vary', 'Origin');
return headers;
}
function getCanaryPercentage(): number {
const rawValue = process.env.CANARY_PERCENTAGE;
if (rawValue === undefined || rawValue.trim() === '') {
return 0;
}
const parsedValue = Number.parseFloat(rawValue);
if (!Number.isFinite(parsedValue)) {
return 0;
}
return Math.min(100, Math.max(0, Math.trunc(parsedValue)));
}
function getCanarySeed(request: NextRequest): string {
return (
request.headers.get('x-tenant-id') ??
request.headers.get('x-user-id') ??
request.headers.get('x-forwarded-user') ??
request.headers.get('authorization') ??
request.url
);
}
function hashSeed(seed: string): number {
let hash = 2166136261;
for (let index = 0; index < seed.length; index += 1) {
hash ^= seed.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
// Deterministically bucket requests by a stable tenant/user-derived seed so
// the same identity consistently lands in the same canary cohort.
function shouldRouteToCanary(request: NextRequest): boolean {
const percentage = getCanaryPercentage();
if (percentage <= 0) {
return false;
}
if (percentage >= 100) {
return true;
}
const seed = getCanarySeed(request);
const bucket = hashSeed(seed) % 100;
return bucket < percentage;
}
function setCanaryHeader(headers: Headers, isCanary: boolean) {
if (isCanary) {
headers.set(CANARY_HEADER_NAME, 'true');
}
}
export async function middleware(request: NextRequest) {
const fingerprint = await captureRequestFingerprint(request);
touchLastSeenFromRequest(request);
const requestHeaders = new Headers(request.headers);
requestHeaders.set(REQUEST_FINGERPRINT_HEADER, fingerprint);
const isCanary = shouldRouteToCanary(request);
if (isCanary) {
requestHeaders.set(CANARY_HEADER_NAME, 'true');
}
const origin = request.headers.get('origin');
// ------------------------------------------------------------------
// 1. Request body size cap (O(1) — reads Content-Length)
// ------------------------------------------------------------------
const sizeError = checkRequestBodySize(request, bodyLimits);
if (sizeError !== null) {
const requestId = resolveRequestId(request.headers);
sizeError.headers.set(REQUEST_FINGERPRINT_HEADER, fingerprint);
sizeError.headers.set(REQUEST_ID_HEADER, requestId);
setCanaryHeader(sizeError.headers, isCanary);
return sizeError;
}
// ------------------------------------------------------------------
// 2. CSRF protection for state-changing requests
// ------------------------------------------------------------------
if (isCsrfProtectedMethod(request.method)) {
const cookieToken = getCsrfCookieValue(request);
const headerToken = getCsrfHeaderValue(request);
if (!validateCsrfToken(cookieToken, headerToken)) {
const response = createCsrfForbiddenResponse(request);
const requestId = resolveRequestId(request.headers);
response.headers.set(REQUEST_FINGERPRINT_HEADER, fingerprint);
response.headers.set(REQUEST_ID_HEADER, requestId);
return response;
}
}
// ------------------------------------------------------------------
// 3. CORS
// ------------------------------------------------------------------
let originAllowed = false;
if (origin) {
originAllowed = isOriginAllowed(origin, allowedOrigins);
if (!originAllowed) {
const requestId = resolveRequestId(request.headers);
console.warn(
JSON.stringify({
type: 'cors.rejection',
origin,
method: request.method,
pathname: request.nextUrl?.pathname ?? '',
request_id: requestId,
})
);
const errorResponse = NextResponse.json(
{
error: {
code: 'CORS_ORIGIN_DISALLOWED',
message: `Origin '${origin}' is not allowed.`,
request_id: requestId,
},
},
{ status: 403 }
);
errorResponse.headers.set(REQUEST_FINGERPRINT_HEADER, fingerprint);
errorResponse.headers.set(REQUEST_ID_HEADER, requestId);
errorResponse.headers.set('Vary', 'Origin');
setCanaryHeader(errorResponse.headers, isCanary);
return errorResponse;
}
if (request.method === 'OPTIONS') {
const headers = buildCorsHeaders(origin);
const requestId = resolveRequestId(request.headers);
headers.set(REQUEST_ID_HEADER, requestId);
setCanaryHeader(headers, isCanary);
return new NextResponse(null, {
status: 204,
headers,
});
}
}
if (request.method === 'OPTIONS' && !origin) {
const requestId = resolveRequestId(request.headers);
const response = new NextResponse(null, { status: 204 });
response.headers.set(REQUEST_ID_HEADER, requestId);
setCanaryHeader(response.headers, isCanary);
return response;
}
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
// ------------------------------------------------------------------
// Request-Id propagation
// ------------------------------------------------------------------
applyRequestIdPolicy(request.headers, requestHeaders, response.headers);
if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {
const csrfResponse = attachCsrfCookie(response, request);
if (originAllowed) {
csrfResponse.headers.set('Access-Control-Allow-Origin', origin!);
csrfResponse.headers.set('Vary', 'Origin');
}
return csrfResponse;
}
// Add CORS headers for allowed origins on non-preflight requests
if (originAllowed) {
response.headers.set('Access-Control-Allow-Origin', origin!);
response.headers.set('Vary', 'Origin');
}
return response;
}