@zero-server/sdk 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/cluster.d.ts +75 -75
  113. package/types/env.d.ts +80 -80
  114. package/types/errors.d.ts +316 -316
  115. package/types/fetch.d.ts +43 -43
  116. package/types/grpc.d.ts +432 -432
  117. package/types/index.d.ts +384 -384
  118. package/types/lifecycle.d.ts +60 -60
  119. package/types/middleware.d.ts +320 -320
  120. package/types/observe.d.ts +304 -304
  121. package/types/orm.d.ts +1887 -1887
  122. package/types/request.d.ts +109 -109
  123. package/types/response.d.ts +157 -157
  124. package/types/router.d.ts +78 -78
  125. package/types/sse.d.ts +78 -78
  126. package/types/websocket.d.ts +126 -126
@@ -1,727 +1,727 @@
1
- /**
2
- * @module http/request
3
- * @description Lightweight wrapper around Node's `IncomingMessage`.
4
- * Provides parsed query string, params, body, and convenience helpers.
5
- *
6
- * Supports trust-proxy configuration via `app.set('trust proxy', value)`
7
- * to correctly resolve `req.ip`, `req.ips`, `req.protocol`, `req.secure`,
8
- * and `req.hostname` when behind reverse proxies.
9
- *
10
- * HTTP/2 compatible — detects pseudo-headers (`:method`, `:path`,
11
- * `:authority`) from HTTP/2 requests automatically.
12
- */
13
- const net = require('net');
14
-
15
- // -- Trust Proxy Helpers ------------------------------------------
16
-
17
- /**
18
- * Parse a CIDR notation string into address and prefix length.
19
- *
20
- * @param {string} cidr - CIDR string (e.g. `'10.0.0.0/8'`, `'::1/128'`).
21
- * @returns {{ ip: string, prefixLen: number, isIPv6: boolean }|null}
22
- * @private
23
- */
24
- function _parseCIDR(cidr)
25
- {
26
- const slash = cidr.indexOf('/');
27
- if (slash === -1) return null;
28
- const ip = cidr.substring(0, slash);
29
- const prefixLen = parseInt(cidr.substring(slash + 1), 10);
30
- if (!net.isIP(ip) || isNaN(prefixLen)) return null;
31
- const isIPv6 = net.isIPv6(ip);
32
- const maxBits = isIPv6 ? 128 : 32;
33
- if (prefixLen < 0 || prefixLen > maxBits) return null;
34
- return { ip, prefixLen, isIPv6 };
35
- }
36
-
37
- /**
38
- * Convert an IPv4 address string to a 32-bit integer.
39
- *
40
- * @param {string} ip - IPv4 address.
41
- * @returns {number}
42
- * @private
43
- */
44
- function _ipv4ToInt(ip)
45
- {
46
- const parts = ip.split('.');
47
- return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
48
- }
49
-
50
- /**
51
- * Convert an IPv6 address to a 16-byte Uint8Array.
52
- *
53
- * @param {string} ip - IPv6 address (full or abbreviated).
54
- * @returns {Uint8Array}
55
- * @private
56
- */
57
- function _ipv6ToBytes(ip)
58
- {
59
- // Handle IPv4-mapped IPv6
60
- if (ip.startsWith('::ffff:') && net.isIPv4(ip.substring(7)))
61
- {
62
- const v4 = _ipv4ToInt(ip.substring(7));
63
- const bytes = new Uint8Array(16);
64
- bytes[10] = 0xff; bytes[11] = 0xff;
65
- bytes[12] = (v4 >>> 24) & 0xff;
66
- bytes[13] = (v4 >>> 16) & 0xff;
67
- bytes[14] = (v4 >>> 8) & 0xff;
68
- bytes[15] = v4 & 0xff;
69
- return bytes;
70
- }
71
-
72
- const bytes = new Uint8Array(16);
73
- const parts = ip.split('::');
74
- let groups;
75
-
76
- if (parts.length === 2)
77
- {
78
- const left = parts[0] ? parts[0].split(':') : [];
79
- const right = parts[1] ? parts[1].split(':') : [];
80
- const missing = 8 - left.length - right.length;
81
- groups = [...left, ...Array(missing).fill('0'), ...right];
82
- }
83
- else
84
- {
85
- groups = ip.split(':');
86
- }
87
-
88
- for (let i = 0; i < 8; i++)
89
- {
90
- const val = parseInt(groups[i] || '0', 16);
91
- bytes[i * 2] = (val >>> 8) & 0xff;
92
- bytes[i * 2 + 1] = val & 0xff;
93
- }
94
- return bytes;
95
- }
96
-
97
- /**
98
- * Check if an IP address is within a CIDR range.
99
- *
100
- * @param {string} addr - IP address to check.
101
- * @param {object} cidr - Parsed CIDR from `_parseCIDR()`.
102
- * @returns {boolean}
103
- * @private
104
- */
105
- function _inCIDR(addr, cidr)
106
- {
107
- const addrIsV6 = net.isIPv6(addr);
108
- const addrIsV4 = net.isIPv4(addr);
109
-
110
- // Normalise IPv4-mapped IPv6 to plain IPv4 for comparison
111
- let normAddr = addr;
112
- if (addrIsV6 && addr.startsWith('::ffff:'))
113
- {
114
- const v4Part = addr.substring(7);
115
- if (net.isIPv4(v4Part)) normAddr = v4Part;
116
- }
117
-
118
- if (cidr.isIPv6)
119
- {
120
- // Both must be IPv6 (or IPv4-mapped)
121
- const addrBytes = addrIsV6 ? _ipv6ToBytes(addr) : _ipv6ToBytes('::ffff:' + addr);
122
- const cidrBytes = _ipv6ToBytes(cidr.ip);
123
- const fullBytes = Math.floor(cidr.prefixLen / 8);
124
- const remainBits = cidr.prefixLen % 8;
125
-
126
- for (let i = 0; i < fullBytes; i++)
127
- {
128
- if (addrBytes[i] !== cidrBytes[i]) return false;
129
- }
130
- if (remainBits > 0)
131
- {
132
- const mask = (0xff << (8 - remainBits)) & 0xff;
133
- if ((addrBytes[fullBytes] & mask) !== (cidrBytes[fullBytes] & mask)) return false;
134
- }
135
- return true;
136
- }
137
-
138
- // IPv4 CIDR
139
- if (!net.isIPv4(normAddr)) return false;
140
- const addrInt = _ipv4ToInt(normAddr);
141
- const cidrInt = _ipv4ToInt(cidr.ip);
142
- const mask = cidr.prefixLen === 0 ? 0 : (~0 << (32 - cidr.prefixLen)) >>> 0;
143
- return (addrInt & mask) === (cidrInt & mask);
144
- }
145
-
146
- /**
147
- * Compile a `trust proxy` setting into a function `(addr, index) => boolean`.
148
- *
149
- * Supported values:
150
- * - `true` / `'loopback'` — trust loopback IPs (127.0.0.0/8, ::1)
151
- * - `false` — trust nothing
152
- * - `number` — trust the first N hops (proxies)
153
- * - `string` — comma-separated IPs or CIDR ranges
154
- * - `string[]` — array of IPs or CIDR ranges
155
- * - `function` — custom `(addr, index) => boolean`
156
- *
157
- * @param {*} val - The `trust proxy` setting value.
158
- * @returns {Function} `(addr: string, hopIndex: number) => boolean`
159
- * @private
160
- */
161
- function compileTrust(val)
162
- {
163
- if (typeof val === 'function') return val;
164
- if (val === true || val === 'loopback')
165
- {
166
- return (addr) =>
167
- {
168
- // Trust loopback addresses
169
- if (addr === '127.0.0.1' || addr === '::1') return true;
170
- // IPv4-mapped IPv6 loopback
171
- if (addr === '::ffff:127.0.0.1') return true;
172
- // Full 127.0.0.0/8 range
173
- if (net.isIPv4(addr) && addr.startsWith('127.')) return true;
174
- return false;
175
- };
176
- }
177
- if (val === false || val === undefined || val === null || val === 0) return () => false;
178
- if (typeof val === 'number' && val > 0)
179
- {
180
- // Trust all addresses — the hop count is handled by _resolveProxyChain
181
- return () => true;
182
- }
183
-
184
- // String or array of IPs / CIDRs
185
- const entries = Array.isArray(val)
186
- ? val
187
- : typeof val === 'string' ? val.split(',').map(s => s.trim()) : [];
188
-
189
- const cidrs = [];
190
- const exact = new Set();
191
-
192
- for (const entry of entries)
193
- {
194
- if (entry.indexOf('/') !== -1)
195
- {
196
- const parsed = _parseCIDR(entry);
197
- if (parsed) cidrs.push(parsed);
198
- }
199
- else if (entry === 'loopback')
200
- {
201
- exact.add('127.0.0.1');
202
- exact.add('::1');
203
- exact.add('::ffff:127.0.0.1');
204
- cidrs.push({ ip: '127.0.0.0', prefixLen: 8, isIPv6: false });
205
- }
206
- else if (entry === 'linklocal')
207
- {
208
- cidrs.push({ ip: '169.254.0.0', prefixLen: 16, isIPv6: false });
209
- cidrs.push(_parseCIDR('fe80::/10'));
210
- }
211
- else if (entry === 'uniquelocal')
212
- {
213
- cidrs.push({ ip: '10.0.0.0', prefixLen: 8, isIPv6: false });
214
- cidrs.push({ ip: '172.16.0.0', prefixLen: 12, isIPv6: false });
215
- cidrs.push({ ip: '192.168.0.0', prefixLen: 16, isIPv6: false });
216
- cidrs.push(_parseCIDR('fc00::/7'));
217
- }
218
- else
219
- {
220
- exact.add(entry);
221
- }
222
- }
223
-
224
- return (addr) =>
225
- {
226
- if (exact.has(addr)) return true;
227
- for (let i = 0; i < cidrs.length; i++)
228
- {
229
- if (cidrs[i] && _inCIDR(addr, cidrs[i])) return true;
230
- }
231
- return false;
232
- };
233
- }
234
-
235
- /**
236
- * Walk the X-Forwarded-For chain from right to left, stopping at the
237
- * first untrusted address. Returns the client IP and the full chain.
238
- *
239
- * @param {string} socketAddr - Socket remote address.
240
- * @param {string} [xffHeader] - X-Forwarded-For header value.
241
- * @param {Function} trustFn - Compiled trust function.
242
- * @param {*} trustSetting - Original trust proxy setting (for hop-count mode).
243
- * @returns {{ ip: string, ips: string[] }}
244
- * @private
245
- */
246
- function _resolveProxyChain(socketAddr, xffHeader, trustFn, trustSetting)
247
- {
248
- if (!xffHeader) return { ip: socketAddr, ips: [] };
249
-
250
- const addrs = xffHeader.split(',').map(s => s.trim()).filter(Boolean);
251
- // Full chain from client → proxy1 → proxy2 → socket
252
- const chain = [...addrs, socketAddr];
253
-
254
- // Hop-count mode: trust exactly N proxies from the right
255
- if (typeof trustSetting === 'number' && trustSetting > 0)
256
- {
257
- const hops = Math.min(trustSetting, addrs.length);
258
- const clientIdx = addrs.length - hops;
259
- return {
260
- ip: addrs[clientIdx] || socketAddr,
261
- ips: chain,
262
- };
263
- }
264
-
265
- // Walk from the rightmost (closest proxy) to left
266
- // The socket address is the last proxy
267
- if (!trustFn(socketAddr, 0)) return { ip: socketAddr, ips: [] };
268
-
269
- for (let i = addrs.length - 1; i >= 0; i--)
270
- {
271
- if (!trustFn(addrs[i], addrs.length - i))
272
- {
273
- // This address is not trusted — it's the client
274
- return { ip: addrs[i], ips: chain };
275
- }
276
- }
277
-
278
- // All addresses are trusted — leftmost is the client
279
- return { ip: addrs[0] || socketAddr, ips: chain };
280
- }
281
-
282
- /**
283
- * Wrapped HTTP request.
284
- *
285
- * @property {import('http').IncomingMessage} raw - Original Node request.
286
- * @property {string} method - HTTP method (e.g. 'GET').
287
- * @property {string} url - Full request URL including query string.
288
- * @property {object} headers - Lower-cased request headers.
289
- * @property {object} query - Parsed query-string key/value pairs.
290
- * @property {object} params - Route parameters populated by the router.
291
- * @property {*} body - Request body (set by body-parsing middleware).
292
- * @property {string|null} ip - Remote IP address.
293
- */
294
- class Request
295
- {
296
- /**
297
- * @constructor
298
- * @param {import('http').IncomingMessage} req - Raw Node incoming message.
299
- */
300
- constructor(req)
301
- {
302
- this.raw = req;
303
-
304
- // HTTP/2 pseudo-headers take priority
305
- this.method = req.headers?.[':method'] || req.method;
306
- this.url = req.headers?.[':path'] || req.url;
307
-
308
- this.headers = req.headers;
309
- this.query = this._parseQuery();
310
- this.params = {};
311
- this.body = null;
312
-
313
- /** Raw socket IP (before trust proxy resolution). @private */
314
- this._socketIp = req.socket ? req.socket.remoteAddress : null;
315
-
316
- /** HTTP version (e.g. '2.0' for HTTP/2). @type {string} */
317
- this.httpVersion = req.httpVersion;
318
-
319
- /** `true` when the connection is over TLS (HTTPS) — raw socket check. @private */
320
- this._socketSecure = !!(req.socket && req.socket.encrypted);
321
-
322
- /** ALPN protocol negotiated (e.g. 'h2', 'http/1.1'). @type {string|null} */
323
- this.alpnProtocol = req.socket?.alpnProtocol || null;
324
-
325
- /** `true` when the request was received over HTTP/2. @type {boolean} */
326
- this.isHTTP2 = req.httpVersionMajor === 2 || this.httpVersion === '2.0';
327
-
328
- /** URL path without query string. */
329
- this.path = this.url.split('?')[0];
330
-
331
- /** Cookies parsed by cookie-parser middleware (populated by middleware). */
332
- this.cookies = {};
333
-
334
- /** Request-scoped locals store, shared with response. */
335
- this.locals = {};
336
-
337
- /**
338
- * The original URL as received — never rewritten by middleware.
339
- * Set by `app.handle()`.
340
- * @type {string}
341
- */
342
- this.originalUrl = req.url;
343
-
344
- /**
345
- * The URL path on which the current router was mounted.
346
- * Empty string at the top level; set by nested routers.
347
- * @type {string}
348
- */
349
- this.baseUrl = '';
350
-
351
- /**
352
- * Reference to the parent App instance.
353
- * Set by `app.handle()`.
354
- * @type {import('../app')|null}
355
- */
356
- this.app = null;
357
-
358
- /** @private Cached compiled trust function. */
359
- this._trustFn = null;
360
- /** @private Cached trust proxy resolution. */
361
- this._proxyResolved = null;
362
- }
363
-
364
- // -- Trust Proxy Resolution --------------------------------
365
-
366
- /**
367
- * Get or compile the trust function from `app.set('trust proxy')`.
368
- * @private
369
- * @returns {Function}
370
- */
371
- _getTrustFn()
372
- {
373
- if (this._trustFn) return this._trustFn;
374
- if (!this.app) return () => false;
375
- const setting = this.app.set('trust proxy');
376
- this._trustFn = compileTrust(setting);
377
- return this._trustFn;
378
- }
379
-
380
- /**
381
- * Resolve proxy chain once (cached).
382
- * @private
383
- * @returns {{ ip: string, ips: string[] }}
384
- */
385
- _resolveProxy()
386
- {
387
- if (this._proxyResolved) return this._proxyResolved;
388
- const trustFn = this._getTrustFn();
389
- const setting = this.app ? this.app.set('trust proxy') : false;
390
- // Only parse X-Forwarded-For when trust proxy is enabled
391
- const xff = (setting !== false && setting !== undefined && setting !== null && setting !== 0)
392
- ? this.headers['x-forwarded-for']
393
- : undefined;
394
- this._proxyResolved = _resolveProxyChain(this._socketIp, xff, trustFn, setting);
395
- return this._proxyResolved;
396
- }
397
-
398
- /**
399
- * Client IP address.
400
- * When `trust proxy` is enabled, resolves through the X-Forwarded-For chain.
401
- * @type {string|null}
402
- */
403
- get ip()
404
- {
405
- if (!this.app) return this._socketIp;
406
- const setting = this.app.set('trust proxy');
407
- if (!setting && setting !== 0) return this._socketIp;
408
- return this._resolveProxy().ip;
409
- }
410
-
411
- /**
412
- * Full proxy chain from X-Forwarded-For (client → proxy1 → proxy2 → socket).
413
- * Empty array when `trust proxy` is not enabled.
414
- * @type {string[]}
415
- */
416
- get ips()
417
- {
418
- if (!this.app) return [];
419
- const setting = this.app.set('trust proxy');
420
- if (!setting && setting !== 0) return [];
421
- return this._resolveProxy().ips;
422
- }
423
-
424
- /**
425
- * Request protocol (`'https'` or `'http'`).
426
- * Reads `X-Forwarded-Proto` when behind a trusted proxy.
427
- * @type {string}
428
- */
429
- get protocol()
430
- {
431
- if (this._socketSecure) return 'https';
432
- if (!this.app) return 'http';
433
- const setting = this.app.set('trust proxy');
434
- if (!setting && setting !== 0) return 'http';
435
-
436
- const trustFn = this._getTrustFn();
437
- const trusted = typeof setting === 'number'
438
- ? setting > 0
439
- : trustFn(this._socketIp, 0);
440
-
441
- if (trusted)
442
- {
443
- const proto = this.headers['x-forwarded-proto'];
444
- if (proto)
445
- {
446
- // X-Forwarded-Proto may be comma-separated; take the first (client's)
447
- const first = proto.split(',')[0].trim().toLowerCase();
448
- if (first === 'https' || first === 'http') return first;
449
- }
450
- }
451
- return 'http';
452
- }
453
-
454
- /**
455
- * `true` when the connection is over HTTPS.
456
- * Respects `X-Forwarded-Proto` when trust proxy is enabled.
457
- * @type {boolean}
458
- */
459
- get secure()
460
- {
461
- return this.protocol === 'https';
462
- }
463
-
464
- /**
465
- * Parse the query string from `this.url` into a plain object.
466
- *
467
- * @private
468
- * @returns {Object<string, string>} Parsed key-value pairs.
469
- */
470
- _parseQuery()
471
- {
472
- const idx = this.url.indexOf('?');
473
- if (idx === -1) return {};
474
- const query = Object.create(null);
475
- const raw = this.url.substring(idx + 1);
476
- const parts = raw.split('&');
477
- const limit = Math.min(parts.length, 100); // Max 100 query params to prevent DoS
478
- for (let i = 0; i < limit; i++)
479
- {
480
- const eqIdx = parts[i].indexOf('=');
481
- if (eqIdx === -1)
482
- {
483
- try {
484
- const key = decodeURIComponent(parts[i]);
485
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
486
- query[key] = '';
487
- } catch (e) { }
488
- }
489
- else
490
- {
491
- try
492
- {
493
- const key = decodeURIComponent(parts[i].substring(0, eqIdx));
494
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
495
- query[key] =
496
- decodeURIComponent(parts[i].substring(eqIdx + 1));
497
- } catch (e) { }
498
- }
499
- }
500
- return query;
501
- }
502
-
503
- /**
504
- * Get a specific request header (case-insensitive).
505
- * @param {string} name - Header name to look up.
506
- * @returns {string|undefined} Header value, or `undefined` if not present.
507
- */
508
- get(name)
509
- {
510
- return this.headers[name.toLowerCase()];
511
- }
512
-
513
- /**
514
- * Check if the request Content-Type matches the given type.
515
- * @param {string} type - MIME type or shorthand (e.g. `'json'`, `'html'`, `'application/json'`).
516
- * @returns {boolean} `true` if the Content-Type matches.
517
- */
518
- is(type)
519
- {
520
- const ct = this.headers['content-type'] || '';
521
- if (type.indexOf('/') === -1)
522
- {
523
- // shorthand: 'json' → 'application/json', 'html' → 'text/html'
524
- return ct.indexOf(type) !== -1;
525
- }
526
- return ct.indexOf(type) !== -1;
527
- }
528
-
529
- /**
530
- * Get the hostname from the Host header (without port).
531
- * Only reads `X-Forwarded-Host` when `trust proxy` is enabled.
532
- * On HTTP/2, falls back to the `:authority` pseudo-header.
533
- * @returns {string} Hostname string, or empty string if no Host header.
534
- */
535
- get hostname()
536
- {
537
- let host;
538
-
539
- // Only trust X-Forwarded-Host when proxy is trusted
540
- if (this.app)
541
- {
542
- const setting = this.app.set('trust proxy');
543
- if (setting && setting !== 0)
544
- {
545
- const trustFn = this._getTrustFn();
546
- const trusted = typeof setting === 'number'
547
- ? setting > 0
548
- : trustFn(this._socketIp, 0);
549
- if (trusted)
550
- {
551
- host = this.headers['x-forwarded-host'];
552
- }
553
- }
554
- }
555
-
556
- // Fallback chain: Host header → :authority (HTTP/2)
557
- if (!host) host = this.headers['host'] || this.headers[':authority'] || '';
558
-
559
- // Remove port if present (handle IPv6 bracket notation)
560
- if (host.charAt(0) === '[')
561
- {
562
- // IPv6: [::1]:3000
563
- const closeBracket = host.indexOf(']');
564
- return closeBracket !== -1 ? host.slice(0, closeBracket + 1) : host;
565
- }
566
- const idx = host.indexOf(':');
567
- return idx !== -1 ? host.slice(0, idx) : host;
568
- }
569
-
570
- /**
571
- * Get the subdomains as an array (e.g. `['api', 'v2']` for `'v2.api.example.com'`).
572
- * @param {number} [offset=2] - Number of dot-separated parts to remove from the right as TLD.
573
- * @returns {string[]} Array of subdomain strings in reverse order.
574
- */
575
- subdomains(offset = 2)
576
- {
577
- const host = this.hostname || '';
578
- const parts = host.split('.');
579
- return parts.slice(0, Math.max(0, parts.length - offset)).reverse();
580
- }
581
-
582
- /**
583
- * Content negotiation — check if the client accepts the given type(s).
584
- * Returns the best match, or `false` if none match.
585
- *
586
- * @param {...string} types - MIME types to check (e.g. 'json', 'html', 'text/plain').
587
- * @returns {string|false} Best matching type, or `false`.
588
- *
589
- * @example
590
- * req.accepts('json', 'html') // => 'json' or 'html' or false
591
- */
592
- accepts(...types)
593
- {
594
- const accept = this.headers['accept'] || '*/*';
595
- const mimeMap = {
596
- json: 'application/json',
597
- html: 'text/html',
598
- text: 'text/plain',
599
- xml: 'application/xml',
600
- css: 'text/css',
601
- js: 'application/javascript',
602
- };
603
-
604
- // Hoist wildcard check outside loop
605
- if (accept === '*/*' || accept.indexOf('*/*') !== -1) return types[0] || false;
606
-
607
- for (let i = 0; i < types.length; i++)
608
- {
609
- const t = types[i];
610
- const mime = mimeMap[t] || t;
611
- if (accept.indexOf(mime) !== -1) return t;
612
- const slashIdx = mime.indexOf('/');
613
- if (slashIdx !== -1 && accept.indexOf(mime.substring(0, slashIdx) + '/*') !== -1) return t;
614
- }
615
- return false;
616
- }
617
-
618
- /**
619
- * Check if the request is "fresh" (client cache is still valid).
620
- * Compares If-None-Match / If-Modified-Since with ETag / Last-Modified.
621
- * @returns {boolean} `true` if the client's cached copy is up to date.
622
- */
623
- get fresh()
624
- {
625
- const method = this.method;
626
- if (method !== 'GET' && method !== 'HEAD') return false;
627
-
628
- const noneMatch = this.headers['if-none-match'];
629
- const modifiedSince = this.headers['if-modified-since'];
630
-
631
- if (!noneMatch && !modifiedSince) return false;
632
-
633
- // Check against response ETag if available
634
- if (noneMatch && this._res)
635
- {
636
- const etag = this._res.get('ETag');
637
- if (etag && noneMatch === etag) return true;
638
- }
639
-
640
- // Check against response Last-Modified if available
641
- if (modifiedSince && this._res)
642
- {
643
- const lastMod = this._res.get('Last-Modified');
644
- if (lastMod)
645
- {
646
- const since = Date.parse(modifiedSince);
647
- const mod = Date.parse(lastMod);
648
- if (!isNaN(since) && !isNaN(mod) && mod <= since) return true;
649
- }
650
- }
651
-
652
- return false;
653
- }
654
-
655
- /**
656
- * Inverse of `fresh`.
657
- * @returns {boolean} `true` if the client's cache is outdated.
658
- */
659
- get stale()
660
- {
661
- return !this.fresh;
662
- }
663
-
664
- /**
665
- * Check whether this request was made with XMLHttpRequest.
666
- * @returns {boolean} `true` if the `X-Requested-With` header is `'XMLHttpRequest'`.
667
- */
668
- get xhr()
669
- {
670
- const val = this.headers['x-requested-with'] || '';
671
- return val.toLowerCase() === 'xmlhttprequest';
672
- }
673
-
674
- /**
675
- * Parse the Range header.
676
- * @param {number} size - Total size of the resource in bytes.
677
- * @returns {{ type: string, ranges: { start: number, end: number }[] } | -1 | -2}
678
- * Returns the parsed ranges, -1 for unsatisfiable ranges, or -2 for malformed header.
679
- */
680
- range(size)
681
- {
682
- const header = this.headers['range'];
683
- if (!header) return -2;
684
-
685
- const match = /^(\w+)=(.+)$/.exec(header);
686
- if (!match) return -2;
687
-
688
- const type = match[1];
689
- const ranges = [];
690
-
691
- for (const part of match[2].split(','))
692
- {
693
- const trimmed = part.trim();
694
- const dashIdx = trimmed.indexOf('-');
695
- if (dashIdx === -1) return -2;
696
-
697
- const startStr = trimmed.slice(0, dashIdx).trim();
698
- const endStr = trimmed.slice(dashIdx + 1).trim();
699
-
700
- let start, end;
701
- if (startStr === '')
702
- {
703
- // Suffix range: -500 means last 500 bytes
704
- const suffix = parseInt(endStr, 10);
705
- if (isNaN(suffix)) return -2;
706
- start = Math.max(0, size - suffix);
707
- end = size - 1;
708
- }
709
- else
710
- {
711
- start = parseInt(startStr, 10);
712
- end = endStr === '' ? size - 1 : parseInt(endStr, 10);
713
- if (isNaN(start) || isNaN(end)) return -2;
714
- }
715
-
716
- if (start > end || start >= size) return -1;
717
- end = Math.min(end, size - 1);
718
- ranges.push({ start, end });
719
- }
720
-
721
- if (ranges.length === 0) return -1;
722
- return { type, ranges };
723
- }
724
- }
725
-
726
- module.exports = Request;
727
- module.exports.compileTrust = compileTrust;
1
+ /**
2
+ * @module http/request
3
+ * @description Lightweight wrapper around Node's `IncomingMessage`.
4
+ * Provides parsed query string, params, body, and convenience helpers.
5
+ *
6
+ * Supports trust-proxy configuration via `app.set('trust proxy', value)`
7
+ * to correctly resolve `req.ip`, `req.ips`, `req.protocol`, `req.secure`,
8
+ * and `req.hostname` when behind reverse proxies.
9
+ *
10
+ * HTTP/2 compatible — detects pseudo-headers (`:method`, `:path`,
11
+ * `:authority`) from HTTP/2 requests automatically.
12
+ */
13
+ const net = require('net');
14
+
15
+ // -- Trust Proxy Helpers ------------------------------------------
16
+
17
+ /**
18
+ * Parse a CIDR notation string into address and prefix length.
19
+ *
20
+ * @param {string} cidr - CIDR string (e.g. `'10.0.0.0/8'`, `'::1/128'`).
21
+ * @returns {{ ip: string, prefixLen: number, isIPv6: boolean }|null}
22
+ * @private
23
+ */
24
+ function _parseCIDR(cidr)
25
+ {
26
+ const slash = cidr.indexOf('/');
27
+ if (slash === -1) return null;
28
+ const ip = cidr.substring(0, slash);
29
+ const prefixLen = parseInt(cidr.substring(slash + 1), 10);
30
+ if (!net.isIP(ip) || isNaN(prefixLen)) return null;
31
+ const isIPv6 = net.isIPv6(ip);
32
+ const maxBits = isIPv6 ? 128 : 32;
33
+ if (prefixLen < 0 || prefixLen > maxBits) return null;
34
+ return { ip, prefixLen, isIPv6 };
35
+ }
36
+
37
+ /**
38
+ * Convert an IPv4 address string to a 32-bit integer.
39
+ *
40
+ * @param {string} ip - IPv4 address.
41
+ * @returns {number}
42
+ * @private
43
+ */
44
+ function _ipv4ToInt(ip)
45
+ {
46
+ const parts = ip.split('.');
47
+ return ((parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]) >>> 0;
48
+ }
49
+
50
+ /**
51
+ * Convert an IPv6 address to a 16-byte Uint8Array.
52
+ *
53
+ * @param {string} ip - IPv6 address (full or abbreviated).
54
+ * @returns {Uint8Array}
55
+ * @private
56
+ */
57
+ function _ipv6ToBytes(ip)
58
+ {
59
+ // Handle IPv4-mapped IPv6
60
+ if (ip.startsWith('::ffff:') && net.isIPv4(ip.substring(7)))
61
+ {
62
+ const v4 = _ipv4ToInt(ip.substring(7));
63
+ const bytes = new Uint8Array(16);
64
+ bytes[10] = 0xff; bytes[11] = 0xff;
65
+ bytes[12] = (v4 >>> 24) & 0xff;
66
+ bytes[13] = (v4 >>> 16) & 0xff;
67
+ bytes[14] = (v4 >>> 8) & 0xff;
68
+ bytes[15] = v4 & 0xff;
69
+ return bytes;
70
+ }
71
+
72
+ const bytes = new Uint8Array(16);
73
+ const parts = ip.split('::');
74
+ let groups;
75
+
76
+ if (parts.length === 2)
77
+ {
78
+ const left = parts[0] ? parts[0].split(':') : [];
79
+ const right = parts[1] ? parts[1].split(':') : [];
80
+ const missing = 8 - left.length - right.length;
81
+ groups = [...left, ...Array(missing).fill('0'), ...right];
82
+ }
83
+ else
84
+ {
85
+ groups = ip.split(':');
86
+ }
87
+
88
+ for (let i = 0; i < 8; i++)
89
+ {
90
+ const val = parseInt(groups[i] || '0', 16);
91
+ bytes[i * 2] = (val >>> 8) & 0xff;
92
+ bytes[i * 2 + 1] = val & 0xff;
93
+ }
94
+ return bytes;
95
+ }
96
+
97
+ /**
98
+ * Check if an IP address is within a CIDR range.
99
+ *
100
+ * @param {string} addr - IP address to check.
101
+ * @param {object} cidr - Parsed CIDR from `_parseCIDR()`.
102
+ * @returns {boolean}
103
+ * @private
104
+ */
105
+ function _inCIDR(addr, cidr)
106
+ {
107
+ const addrIsV6 = net.isIPv6(addr);
108
+ const addrIsV4 = net.isIPv4(addr);
109
+
110
+ // Normalise IPv4-mapped IPv6 to plain IPv4 for comparison
111
+ let normAddr = addr;
112
+ if (addrIsV6 && addr.startsWith('::ffff:'))
113
+ {
114
+ const v4Part = addr.substring(7);
115
+ if (net.isIPv4(v4Part)) normAddr = v4Part;
116
+ }
117
+
118
+ if (cidr.isIPv6)
119
+ {
120
+ // Both must be IPv6 (or IPv4-mapped)
121
+ const addrBytes = addrIsV6 ? _ipv6ToBytes(addr) : _ipv6ToBytes('::ffff:' + addr);
122
+ const cidrBytes = _ipv6ToBytes(cidr.ip);
123
+ const fullBytes = Math.floor(cidr.prefixLen / 8);
124
+ const remainBits = cidr.prefixLen % 8;
125
+
126
+ for (let i = 0; i < fullBytes; i++)
127
+ {
128
+ if (addrBytes[i] !== cidrBytes[i]) return false;
129
+ }
130
+ if (remainBits > 0)
131
+ {
132
+ const mask = (0xff << (8 - remainBits)) & 0xff;
133
+ if ((addrBytes[fullBytes] & mask) !== (cidrBytes[fullBytes] & mask)) return false;
134
+ }
135
+ return true;
136
+ }
137
+
138
+ // IPv4 CIDR
139
+ if (!net.isIPv4(normAddr)) return false;
140
+ const addrInt = _ipv4ToInt(normAddr);
141
+ const cidrInt = _ipv4ToInt(cidr.ip);
142
+ const mask = cidr.prefixLen === 0 ? 0 : (~0 << (32 - cidr.prefixLen)) >>> 0;
143
+ return (addrInt & mask) === (cidrInt & mask);
144
+ }
145
+
146
+ /**
147
+ * Compile a `trust proxy` setting into a function `(addr, index) => boolean`.
148
+ *
149
+ * Supported values:
150
+ * - `true` / `'loopback'` — trust loopback IPs (127.0.0.0/8, ::1)
151
+ * - `false` — trust nothing
152
+ * - `number` — trust the first N hops (proxies)
153
+ * - `string` — comma-separated IPs or CIDR ranges
154
+ * - `string[]` — array of IPs or CIDR ranges
155
+ * - `function` — custom `(addr, index) => boolean`
156
+ *
157
+ * @param {*} val - The `trust proxy` setting value.
158
+ * @returns {Function} `(addr: string, hopIndex: number) => boolean`
159
+ * @private
160
+ */
161
+ function compileTrust(val)
162
+ {
163
+ if (typeof val === 'function') return val;
164
+ if (val === true || val === 'loopback')
165
+ {
166
+ return (addr) =>
167
+ {
168
+ // Trust loopback addresses
169
+ if (addr === '127.0.0.1' || addr === '::1') return true;
170
+ // IPv4-mapped IPv6 loopback
171
+ if (addr === '::ffff:127.0.0.1') return true;
172
+ // Full 127.0.0.0/8 range
173
+ if (net.isIPv4(addr) && addr.startsWith('127.')) return true;
174
+ return false;
175
+ };
176
+ }
177
+ if (val === false || val === undefined || val === null || val === 0) return () => false;
178
+ if (typeof val === 'number' && val > 0)
179
+ {
180
+ // Trust all addresses — the hop count is handled by _resolveProxyChain
181
+ return () => true;
182
+ }
183
+
184
+ // String or array of IPs / CIDRs
185
+ const entries = Array.isArray(val)
186
+ ? val
187
+ : typeof val === 'string' ? val.split(',').map(s => s.trim()) : [];
188
+
189
+ const cidrs = [];
190
+ const exact = new Set();
191
+
192
+ for (const entry of entries)
193
+ {
194
+ if (entry.indexOf('/') !== -1)
195
+ {
196
+ const parsed = _parseCIDR(entry);
197
+ if (parsed) cidrs.push(parsed);
198
+ }
199
+ else if (entry === 'loopback')
200
+ {
201
+ exact.add('127.0.0.1');
202
+ exact.add('::1');
203
+ exact.add('::ffff:127.0.0.1');
204
+ cidrs.push({ ip: '127.0.0.0', prefixLen: 8, isIPv6: false });
205
+ }
206
+ else if (entry === 'linklocal')
207
+ {
208
+ cidrs.push({ ip: '169.254.0.0', prefixLen: 16, isIPv6: false });
209
+ cidrs.push(_parseCIDR('fe80::/10'));
210
+ }
211
+ else if (entry === 'uniquelocal')
212
+ {
213
+ cidrs.push({ ip: '10.0.0.0', prefixLen: 8, isIPv6: false });
214
+ cidrs.push({ ip: '172.16.0.0', prefixLen: 12, isIPv6: false });
215
+ cidrs.push({ ip: '192.168.0.0', prefixLen: 16, isIPv6: false });
216
+ cidrs.push(_parseCIDR('fc00::/7'));
217
+ }
218
+ else
219
+ {
220
+ exact.add(entry);
221
+ }
222
+ }
223
+
224
+ return (addr) =>
225
+ {
226
+ if (exact.has(addr)) return true;
227
+ for (let i = 0; i < cidrs.length; i++)
228
+ {
229
+ if (cidrs[i] && _inCIDR(addr, cidrs[i])) return true;
230
+ }
231
+ return false;
232
+ };
233
+ }
234
+
235
+ /**
236
+ * Walk the X-Forwarded-For chain from right to left, stopping at the
237
+ * first untrusted address. Returns the client IP and the full chain.
238
+ *
239
+ * @param {string} socketAddr - Socket remote address.
240
+ * @param {string} [xffHeader] - X-Forwarded-For header value.
241
+ * @param {Function} trustFn - Compiled trust function.
242
+ * @param {*} trustSetting - Original trust proxy setting (for hop-count mode).
243
+ * @returns {{ ip: string, ips: string[] }}
244
+ * @private
245
+ */
246
+ function _resolveProxyChain(socketAddr, xffHeader, trustFn, trustSetting)
247
+ {
248
+ if (!xffHeader) return { ip: socketAddr, ips: [] };
249
+
250
+ const addrs = xffHeader.split(',').map(s => s.trim()).filter(Boolean);
251
+ // Full chain from client → proxy1 → proxy2 → socket
252
+ const chain = [...addrs, socketAddr];
253
+
254
+ // Hop-count mode: trust exactly N proxies from the right
255
+ if (typeof trustSetting === 'number' && trustSetting > 0)
256
+ {
257
+ const hops = Math.min(trustSetting, addrs.length);
258
+ const clientIdx = addrs.length - hops;
259
+ return {
260
+ ip: addrs[clientIdx] || socketAddr,
261
+ ips: chain,
262
+ };
263
+ }
264
+
265
+ // Walk from the rightmost (closest proxy) to left
266
+ // The socket address is the last proxy
267
+ if (!trustFn(socketAddr, 0)) return { ip: socketAddr, ips: [] };
268
+
269
+ for (let i = addrs.length - 1; i >= 0; i--)
270
+ {
271
+ if (!trustFn(addrs[i], addrs.length - i))
272
+ {
273
+ // This address is not trusted — it's the client
274
+ return { ip: addrs[i], ips: chain };
275
+ }
276
+ }
277
+
278
+ // All addresses are trusted — leftmost is the client
279
+ return { ip: addrs[0] || socketAddr, ips: chain };
280
+ }
281
+
282
+ /**
283
+ * Wrapped HTTP request.
284
+ *
285
+ * @property {import('http').IncomingMessage} raw - Original Node request.
286
+ * @property {string} method - HTTP method (e.g. 'GET').
287
+ * @property {string} url - Full request URL including query string.
288
+ * @property {object} headers - Lower-cased request headers.
289
+ * @property {object} query - Parsed query-string key/value pairs.
290
+ * @property {object} params - Route parameters populated by the router.
291
+ * @property {*} body - Request body (set by body-parsing middleware).
292
+ * @property {string|null} ip - Remote IP address.
293
+ */
294
+ class Request
295
+ {
296
+ /**
297
+ * @constructor
298
+ * @param {import('http').IncomingMessage} req - Raw Node incoming message.
299
+ */
300
+ constructor(req)
301
+ {
302
+ this.raw = req;
303
+
304
+ // HTTP/2 pseudo-headers take priority
305
+ this.method = req.headers?.[':method'] || req.method;
306
+ this.url = req.headers?.[':path'] || req.url;
307
+
308
+ this.headers = req.headers;
309
+ this.query = this._parseQuery();
310
+ this.params = {};
311
+ this.body = null;
312
+
313
+ /** Raw socket IP (before trust proxy resolution). @private */
314
+ this._socketIp = req.socket ? req.socket.remoteAddress : null;
315
+
316
+ /** HTTP version (e.g. '2.0' for HTTP/2). @type {string} */
317
+ this.httpVersion = req.httpVersion;
318
+
319
+ /** `true` when the connection is over TLS (HTTPS) — raw socket check. @private */
320
+ this._socketSecure = !!(req.socket && req.socket.encrypted);
321
+
322
+ /** ALPN protocol negotiated (e.g. 'h2', 'http/1.1'). @type {string|null} */
323
+ this.alpnProtocol = req.socket?.alpnProtocol || null;
324
+
325
+ /** `true` when the request was received over HTTP/2. @type {boolean} */
326
+ this.isHTTP2 = req.httpVersionMajor === 2 || this.httpVersion === '2.0';
327
+
328
+ /** URL path without query string. */
329
+ this.path = this.url.split('?')[0];
330
+
331
+ /** Cookies parsed by cookie-parser middleware (populated by middleware). */
332
+ this.cookies = {};
333
+
334
+ /** Request-scoped locals store, shared with response. */
335
+ this.locals = {};
336
+
337
+ /**
338
+ * The original URL as received — never rewritten by middleware.
339
+ * Set by `app.handle()`.
340
+ * @type {string}
341
+ */
342
+ this.originalUrl = req.url;
343
+
344
+ /**
345
+ * The URL path on which the current router was mounted.
346
+ * Empty string at the top level; set by nested routers.
347
+ * @type {string}
348
+ */
349
+ this.baseUrl = '';
350
+
351
+ /**
352
+ * Reference to the parent App instance.
353
+ * Set by `app.handle()`.
354
+ * @type {import('../app')|null}
355
+ */
356
+ this.app = null;
357
+
358
+ /** @private Cached compiled trust function. */
359
+ this._trustFn = null;
360
+ /** @private Cached trust proxy resolution. */
361
+ this._proxyResolved = null;
362
+ }
363
+
364
+ // -- Trust Proxy Resolution --------------------------------
365
+
366
+ /**
367
+ * Get or compile the trust function from `app.set('trust proxy')`.
368
+ * @private
369
+ * @returns {Function}
370
+ */
371
+ _getTrustFn()
372
+ {
373
+ if (this._trustFn) return this._trustFn;
374
+ if (!this.app) return () => false;
375
+ const setting = this.app.set('trust proxy');
376
+ this._trustFn = compileTrust(setting);
377
+ return this._trustFn;
378
+ }
379
+
380
+ /**
381
+ * Resolve proxy chain once (cached).
382
+ * @private
383
+ * @returns {{ ip: string, ips: string[] }}
384
+ */
385
+ _resolveProxy()
386
+ {
387
+ if (this._proxyResolved) return this._proxyResolved;
388
+ const trustFn = this._getTrustFn();
389
+ const setting = this.app ? this.app.set('trust proxy') : false;
390
+ // Only parse X-Forwarded-For when trust proxy is enabled
391
+ const xff = (setting !== false && setting !== undefined && setting !== null && setting !== 0)
392
+ ? this.headers['x-forwarded-for']
393
+ : undefined;
394
+ this._proxyResolved = _resolveProxyChain(this._socketIp, xff, trustFn, setting);
395
+ return this._proxyResolved;
396
+ }
397
+
398
+ /**
399
+ * Client IP address.
400
+ * When `trust proxy` is enabled, resolves through the X-Forwarded-For chain.
401
+ * @type {string|null}
402
+ */
403
+ get ip()
404
+ {
405
+ if (!this.app) return this._socketIp;
406
+ const setting = this.app.set('trust proxy');
407
+ if (!setting && setting !== 0) return this._socketIp;
408
+ return this._resolveProxy().ip;
409
+ }
410
+
411
+ /**
412
+ * Full proxy chain from X-Forwarded-For (client → proxy1 → proxy2 → socket).
413
+ * Empty array when `trust proxy` is not enabled.
414
+ * @type {string[]}
415
+ */
416
+ get ips()
417
+ {
418
+ if (!this.app) return [];
419
+ const setting = this.app.set('trust proxy');
420
+ if (!setting && setting !== 0) return [];
421
+ return this._resolveProxy().ips;
422
+ }
423
+
424
+ /**
425
+ * Request protocol (`'https'` or `'http'`).
426
+ * Reads `X-Forwarded-Proto` when behind a trusted proxy.
427
+ * @type {string}
428
+ */
429
+ get protocol()
430
+ {
431
+ if (this._socketSecure) return 'https';
432
+ if (!this.app) return 'http';
433
+ const setting = this.app.set('trust proxy');
434
+ if (!setting && setting !== 0) return 'http';
435
+
436
+ const trustFn = this._getTrustFn();
437
+ const trusted = typeof setting === 'number'
438
+ ? setting > 0
439
+ : trustFn(this._socketIp, 0);
440
+
441
+ if (trusted)
442
+ {
443
+ const proto = this.headers['x-forwarded-proto'];
444
+ if (proto)
445
+ {
446
+ // X-Forwarded-Proto may be comma-separated; take the first (client's)
447
+ const first = proto.split(',')[0].trim().toLowerCase();
448
+ if (first === 'https' || first === 'http') return first;
449
+ }
450
+ }
451
+ return 'http';
452
+ }
453
+
454
+ /**
455
+ * `true` when the connection is over HTTPS.
456
+ * Respects `X-Forwarded-Proto` when trust proxy is enabled.
457
+ * @type {boolean}
458
+ */
459
+ get secure()
460
+ {
461
+ return this.protocol === 'https';
462
+ }
463
+
464
+ /**
465
+ * Parse the query string from `this.url` into a plain object.
466
+ *
467
+ * @private
468
+ * @returns {Object<string, string>} Parsed key-value pairs.
469
+ */
470
+ _parseQuery()
471
+ {
472
+ const idx = this.url.indexOf('?');
473
+ if (idx === -1) return {};
474
+ const query = Object.create(null);
475
+ const raw = this.url.substring(idx + 1);
476
+ const parts = raw.split('&');
477
+ const limit = Math.min(parts.length, 100); // Max 100 query params to prevent DoS
478
+ for (let i = 0; i < limit; i++)
479
+ {
480
+ const eqIdx = parts[i].indexOf('=');
481
+ if (eqIdx === -1)
482
+ {
483
+ try {
484
+ const key = decodeURIComponent(parts[i]);
485
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
486
+ query[key] = '';
487
+ } catch (e) { }
488
+ }
489
+ else
490
+ {
491
+ try
492
+ {
493
+ const key = decodeURIComponent(parts[i].substring(0, eqIdx));
494
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
495
+ query[key] =
496
+ decodeURIComponent(parts[i].substring(eqIdx + 1));
497
+ } catch (e) { }
498
+ }
499
+ }
500
+ return query;
501
+ }
502
+
503
+ /**
504
+ * Get a specific request header (case-insensitive).
505
+ * @param {string} name - Header name to look up.
506
+ * @returns {string|undefined} Header value, or `undefined` if not present.
507
+ */
508
+ get(name)
509
+ {
510
+ return this.headers[name.toLowerCase()];
511
+ }
512
+
513
+ /**
514
+ * Check if the request Content-Type matches the given type.
515
+ * @param {string} type - MIME type or shorthand (e.g. `'json'`, `'html'`, `'application/json'`).
516
+ * @returns {boolean} `true` if the Content-Type matches.
517
+ */
518
+ is(type)
519
+ {
520
+ const ct = this.headers['content-type'] || '';
521
+ if (type.indexOf('/') === -1)
522
+ {
523
+ // shorthand: 'json' → 'application/json', 'html' → 'text/html'
524
+ return ct.indexOf(type) !== -1;
525
+ }
526
+ return ct.indexOf(type) !== -1;
527
+ }
528
+
529
+ /**
530
+ * Get the hostname from the Host header (without port).
531
+ * Only reads `X-Forwarded-Host` when `trust proxy` is enabled.
532
+ * On HTTP/2, falls back to the `:authority` pseudo-header.
533
+ * @returns {string} Hostname string, or empty string if no Host header.
534
+ */
535
+ get hostname()
536
+ {
537
+ let host;
538
+
539
+ // Only trust X-Forwarded-Host when proxy is trusted
540
+ if (this.app)
541
+ {
542
+ const setting = this.app.set('trust proxy');
543
+ if (setting && setting !== 0)
544
+ {
545
+ const trustFn = this._getTrustFn();
546
+ const trusted = typeof setting === 'number'
547
+ ? setting > 0
548
+ : trustFn(this._socketIp, 0);
549
+ if (trusted)
550
+ {
551
+ host = this.headers['x-forwarded-host'];
552
+ }
553
+ }
554
+ }
555
+
556
+ // Fallback chain: Host header → :authority (HTTP/2)
557
+ if (!host) host = this.headers['host'] || this.headers[':authority'] || '';
558
+
559
+ // Remove port if present (handle IPv6 bracket notation)
560
+ if (host.charAt(0) === '[')
561
+ {
562
+ // IPv6: [::1]:3000
563
+ const closeBracket = host.indexOf(']');
564
+ return closeBracket !== -1 ? host.slice(0, closeBracket + 1) : host;
565
+ }
566
+ const idx = host.indexOf(':');
567
+ return idx !== -1 ? host.slice(0, idx) : host;
568
+ }
569
+
570
+ /**
571
+ * Get the subdomains as an array (e.g. `['api', 'v2']` for `'v2.api.example.com'`).
572
+ * @param {number} [offset=2] - Number of dot-separated parts to remove from the right as TLD.
573
+ * @returns {string[]} Array of subdomain strings in reverse order.
574
+ */
575
+ subdomains(offset = 2)
576
+ {
577
+ const host = this.hostname || '';
578
+ const parts = host.split('.');
579
+ return parts.slice(0, Math.max(0, parts.length - offset)).reverse();
580
+ }
581
+
582
+ /**
583
+ * Content negotiation — check if the client accepts the given type(s).
584
+ * Returns the best match, or `false` if none match.
585
+ *
586
+ * @param {...string} types - MIME types to check (e.g. 'json', 'html', 'text/plain').
587
+ * @returns {string|false} Best matching type, or `false`.
588
+ *
589
+ * @example
590
+ * req.accepts('json', 'html') // => 'json' or 'html' or false
591
+ */
592
+ accepts(...types)
593
+ {
594
+ const accept = this.headers['accept'] || '*/*';
595
+ const mimeMap = {
596
+ json: 'application/json',
597
+ html: 'text/html',
598
+ text: 'text/plain',
599
+ xml: 'application/xml',
600
+ css: 'text/css',
601
+ js: 'application/javascript',
602
+ };
603
+
604
+ // Hoist wildcard check outside loop
605
+ if (accept === '*/*' || accept.indexOf('*/*') !== -1) return types[0] || false;
606
+
607
+ for (let i = 0; i < types.length; i++)
608
+ {
609
+ const t = types[i];
610
+ const mime = mimeMap[t] || t;
611
+ if (accept.indexOf(mime) !== -1) return t;
612
+ const slashIdx = mime.indexOf('/');
613
+ if (slashIdx !== -1 && accept.indexOf(mime.substring(0, slashIdx) + '/*') !== -1) return t;
614
+ }
615
+ return false;
616
+ }
617
+
618
+ /**
619
+ * Check if the request is "fresh" (client cache is still valid).
620
+ * Compares If-None-Match / If-Modified-Since with ETag / Last-Modified.
621
+ * @returns {boolean} `true` if the client's cached copy is up to date.
622
+ */
623
+ get fresh()
624
+ {
625
+ const method = this.method;
626
+ if (method !== 'GET' && method !== 'HEAD') return false;
627
+
628
+ const noneMatch = this.headers['if-none-match'];
629
+ const modifiedSince = this.headers['if-modified-since'];
630
+
631
+ if (!noneMatch && !modifiedSince) return false;
632
+
633
+ // Check against response ETag if available
634
+ if (noneMatch && this._res)
635
+ {
636
+ const etag = this._res.get('ETag');
637
+ if (etag && noneMatch === etag) return true;
638
+ }
639
+
640
+ // Check against response Last-Modified if available
641
+ if (modifiedSince && this._res)
642
+ {
643
+ const lastMod = this._res.get('Last-Modified');
644
+ if (lastMod)
645
+ {
646
+ const since = Date.parse(modifiedSince);
647
+ const mod = Date.parse(lastMod);
648
+ if (!isNaN(since) && !isNaN(mod) && mod <= since) return true;
649
+ }
650
+ }
651
+
652
+ return false;
653
+ }
654
+
655
+ /**
656
+ * Inverse of `fresh`.
657
+ * @returns {boolean} `true` if the client's cache is outdated.
658
+ */
659
+ get stale()
660
+ {
661
+ return !this.fresh;
662
+ }
663
+
664
+ /**
665
+ * Check whether this request was made with XMLHttpRequest.
666
+ * @returns {boolean} `true` if the `X-Requested-With` header is `'XMLHttpRequest'`.
667
+ */
668
+ get xhr()
669
+ {
670
+ const val = this.headers['x-requested-with'] || '';
671
+ return val.toLowerCase() === 'xmlhttprequest';
672
+ }
673
+
674
+ /**
675
+ * Parse the Range header.
676
+ * @param {number} size - Total size of the resource in bytes.
677
+ * @returns {{ type: string, ranges: { start: number, end: number }[] } | -1 | -2}
678
+ * Returns the parsed ranges, -1 for unsatisfiable ranges, or -2 for malformed header.
679
+ */
680
+ range(size)
681
+ {
682
+ const header = this.headers['range'];
683
+ if (!header) return -2;
684
+
685
+ const match = /^(\w+)=(.+)$/.exec(header);
686
+ if (!match) return -2;
687
+
688
+ const type = match[1];
689
+ const ranges = [];
690
+
691
+ for (const part of match[2].split(','))
692
+ {
693
+ const trimmed = part.trim();
694
+ const dashIdx = trimmed.indexOf('-');
695
+ if (dashIdx === -1) return -2;
696
+
697
+ const startStr = trimmed.slice(0, dashIdx).trim();
698
+ const endStr = trimmed.slice(dashIdx + 1).trim();
699
+
700
+ let start, end;
701
+ if (startStr === '')
702
+ {
703
+ // Suffix range: -500 means last 500 bytes
704
+ const suffix = parseInt(endStr, 10);
705
+ if (isNaN(suffix)) return -2;
706
+ start = Math.max(0, size - suffix);
707
+ end = size - 1;
708
+ }
709
+ else
710
+ {
711
+ start = parseInt(startStr, 10);
712
+ end = endStr === '' ? size - 1 : parseInt(endStr, 10);
713
+ if (isNaN(start) || isNaN(end)) return -2;
714
+ }
715
+
716
+ if (start > end || start >= size) return -1;
717
+ end = Math.min(end, size - 1);
718
+ ranges.push({ start, end });
719
+ }
720
+
721
+ if (ranges.length === 0) return -1;
722
+ return { type, ranges };
723
+ }
724
+ }
725
+
726
+ module.exports = Request;
727
+ module.exports.compileTrust = compileTrust;