@tylix/core 0.5.3 → 0.7.0

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -17
  3. package/package.json +38 -7
  4. package/src/cache/Cache.d.ts +4 -2
  5. package/src/cache/Cache.js +46 -58
  6. package/src/channels/ChannelServer.d.ts +5 -0
  7. package/src/channels/ChannelServer.js +24 -0
  8. package/src/channels/broadcast.d.ts +3 -0
  9. package/src/channels/broadcast.js +15 -0
  10. package/src/discovery/loadCustomRoutes.d.ts +5 -1
  11. package/src/discovery/loadCustomRoutes.js +84 -3
  12. package/src/discovery/registerRouteFiles.js +6 -2
  13. package/src/http/Server.d.ts +86 -6
  14. package/src/http/Server.js +229 -26
  15. package/src/http/enhanceResponse.js +78 -34
  16. package/src/http/parseBody.d.ts +22 -1
  17. package/src/http/parseBody.js +54 -24
  18. package/src/http/rateLimit.d.ts +9 -1
  19. package/src/http/rateLimit.js +36 -8
  20. package/src/http/requireAuth.d.ts +13 -1
  21. package/src/http/requireAuth.js +8 -1
  22. package/src/index.d.ts +4 -1
  23. package/src/index.js +7 -1
  24. package/src/observability/context.js +12 -0
  25. package/src/observability/health.js +38 -0
  26. package/src/observability/index.d.ts +68 -0
  27. package/src/observability/logger.js +127 -0
  28. package/src/observability/metrics.js +127 -0
  29. package/src/router/Router.d.ts +2 -1
  30. package/src/router/Router.js +117 -46
  31. package/src/store/database.js +209 -0
  32. package/src/store/index.d.ts +31 -0
  33. package/src/store/index.js +52 -0
  34. package/src/store/memory.js +72 -0
  35. package/src/store/redis.js +77 -0
  36. package/src/http/Server.test.js +0 -99
  37. package/src/http/enhanceResponse.test.js +0 -45
  38. package/src/http/parseBody.test.js +0 -33
  39. package/src/http/parseQuery.test.js +0 -15
  40. package/src/http/requireAuth.test.js +0 -76
  41. package/src/providers/createProvider.js +0 -16
  42. package/src/router/Router.test.js +0 -128
  43. package/src/runtime/useApi.js +0 -405
  44. package/tsconfig.json +0 -13
@@ -1,5 +1,10 @@
1
1
  import http from 'node:http'
2
- import { enhanceResponse } from './enhanceResponse.js'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { monitorEventLoopDelay } from 'node:perf_hooks'
4
+ import { TylixResponse, enhanceResponse } from './enhanceResponse.js'
5
+ import { requestContext } from '../observability/context.js'
6
+ import { logger as defaultLogger } from '../observability/logger.js'
7
+ import { metrics as defaultMetrics } from '../observability/metrics.js'
3
8
  import { readBody } from './parseBody.js'
4
9
  import { parseQuery } from './parseQuery.js'
5
10
  import { parseCookies } from './parseCookies.js'
@@ -7,6 +12,8 @@ import { buildDebugPayload } from './debug/buildDebugPayload.js'
7
12
  import { renderDebugPage } from './debug/renderDebugPage.js'
8
13
 
9
14
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
15
+ const DEFAULT_MAX_BODY_BYTES = 1024 * 1024 // 1 MB
16
+ const DEFAULT_PORT_ATTEMPTS = 10
10
17
 
11
18
  // Pages inline their scripts, so script-src needs 'unsafe-inline'. The rest
12
19
  // still blocks framing, base-tag and form hijacking, plugins, and data being
@@ -78,6 +85,53 @@ function isSecure(req, trustProxy) {
78
85
  // link click, reload). fetch()/useApi sends "empty", so API calls from
79
86
  // the app keep getting JSON. Clients without the header (curl) fall
80
87
  // back to the Accept check.
88
+ function pathOf(url) {
89
+ const queryAt = String(url).indexOf('?')
90
+ return queryAt === -1 ? String(url) : String(url).slice(0, queryAt)
91
+ }
92
+
93
+ // HTTP/1.1: a request has a body only when it says so with
94
+ // Content-Length or Transfer-Encoding.
95
+ function hasBody(req) {
96
+ const length = req.headers['content-length']
97
+ if (length !== undefined) return length !== '0'
98
+ return req.headers['transfer-encoding'] !== undefined
99
+ }
100
+
101
+ // A client-sent X-Request-Id is kept (it ties the request to the
102
+ // caller's logs) when it looks like an id; otherwise a new one is made.
103
+ const REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/
104
+ const QUIET_PATHS = new Set(['/health', '/ready', '/metrics'])
105
+
106
+ function requestIdOf(req) {
107
+ const given = req.headers['x-request-id']
108
+ return typeof given === 'string' && REQUEST_ID.test(given) ? given : randomUUID()
109
+ }
110
+
111
+ // HTTP and process metrics, defined once per registry.
112
+ const httpMetricsByRegistry = new WeakMap()
113
+
114
+ function httpMetrics(registry) {
115
+ let defined = httpMetricsByRegistry.get(registry)
116
+ if (defined) return defined
117
+ const loopDelay = monitorEventLoopDelay({ resolution: 20 })
118
+ loopDelay.enable()
119
+ defined = {
120
+ requests: registry.counter('http_requests_total', 'HTTP requests by method, route and status'),
121
+ duration: registry.histogram('http_request_duration_seconds', 'HTTP request duration by method and route'),
122
+ }
123
+ registry.gauge('process_resident_memory_bytes', 'Resident memory', () => process.memoryUsage.rss())
124
+ registry.gauge('nodejs_heap_used_bytes', 'V8 heap in use', () => process.memoryUsage().heapUsed)
125
+ registry.gauge('process_uptime_seconds', 'Seconds since the process started', () => Math.round(process.uptime()))
126
+ registry.gauge('nodejs_eventloop_lag_p99_seconds', 'Event loop delay, 99th percentile', () => {
127
+ const p99 = loopDelay.percentile(99) / 1e9
128
+ loopDelay.reset()
129
+ return p99
130
+ })
131
+ httpMetricsByRegistry.set(registry, defined)
132
+ return defined
133
+ }
134
+
81
135
  function wantsHtml(req) {
82
136
  if (req.method !== 'GET') return false
83
137
  const dest = req.headers['sec-fetch-dest']
@@ -90,7 +144,26 @@ function wantsHtml(req) {
90
144
  }
91
145
 
92
146
  export class Server {
93
- constructor(router, { notFoundHandler = null, trustProxy, debug } = {}) {
147
+ constructor(
148
+ router,
149
+ {
150
+ notFoundHandler = null,
151
+ trustProxy,
152
+ debug,
153
+ maxBodyBytes,
154
+ autoPort,
155
+ maxPortAttempts,
156
+ trustedOrigins,
157
+ appUrl,
158
+ cspMode,
159
+ csp,
160
+ logger,
161
+ accessLog,
162
+ slowRequestMs,
163
+ metrics,
164
+ compression,
165
+ } = {},
166
+ ) {
94
167
  this.router = router
95
168
  // Optional fallback called when no route matches, before the
96
169
  // default 404 JSON response -- e.g. tylix dev uses this to serve
@@ -105,11 +178,30 @@ export class Server {
105
178
  // Show real error details (debug page, SQL, stack) instead of a
106
179
  // generic 500. Defaults to the APP_DEBUG=true env var.
107
180
  this.debug = debug ?? process.env.APP_DEBUG === 'true'
181
+ // Largest request body accepted, in bytes. Bigger bodies get a 413.
182
+ // Defaults to the MAX_BODY_BYTES env var, then 1 MB.
183
+ this.maxBodyBytes =
184
+ maxBodyBytes ??
185
+ (Number(process.env.MAX_BODY_BYTES) || DEFAULT_MAX_BODY_BYTES)
186
+
187
+ // When the port is already taken, try the next one instead of
188
+ // crashing. On by default outside production (a proxy or process
189
+ // manager expects a fixed port there). Override with AUTO_PORT=true
190
+ // or AUTO_PORT=false.
191
+ this.autoPort =
192
+ autoPort ??
193
+ (process.env.AUTO_PORT !== undefined
194
+ ? process.env.AUTO_PORT === 'true'
195
+ : !this.production)
196
+ // How many following ports to try (PORT_ATTEMPTS, default 10).
197
+ this.maxPortAttempts =
198
+ maxPortAttempts ??
199
+ (Number(process.env.PORT_ATTEMPTS) || DEFAULT_PORT_ATTEMPTS)
108
200
 
109
201
  // Origins allowed to make browser write requests from elsewhere
110
202
  // (TRUSTED_ORIGINS=https://a.example,https://b.example). APP_URL counts too.
111
203
  this.trustedOrigins = new Set(
112
- [...parseList(process.env.TRUSTED_ORIGINS), process.env.APP_URL]
204
+ [...(trustedOrigins ?? parseList(process.env.TRUSTED_ORIGINS)), appUrl ?? process.env.APP_URL]
113
205
  .filter(Boolean)
114
206
  .map(originOf)
115
207
  .filter(Boolean),
@@ -118,9 +210,22 @@ export class Server {
118
210
  // CSP_MODE: off | report-only | enforce. Production defaults to
119
211
  // report-only: violations show in the browser console, nothing breaks.
120
212
  this.cspMode = String(
121
- process.env.CSP_MODE || (this.production ? 'report-only' : 'off'),
213
+ cspMode ?? (process.env.CSP_MODE || (this.production ? 'report-only' : 'off')),
122
214
  ).toLowerCase()
123
- this.csp = process.env.CSP_POLICY || DEFAULT_CSP
215
+ this.csp = csp ?? (process.env.CSP_POLICY || DEFAULT_CSP)
216
+
217
+ this.logger = logger ?? defaultLogger
218
+ // One line per request: true, false, or "api" (only /api/ requests,
219
+ // the development default, so asset and page requests stay quiet).
220
+ this.accessLog = accessLog ?? (this.production ? true : 'api')
221
+ // Requests slower than this are logged as warnings (0 turns it off).
222
+ this.slowRequestMs = slowRequestMs ?? 1000
223
+ // A metrics registry (or true for the shared one) to record HTTP
224
+ // metrics in; off by default.
225
+ this.metrics = metrics === true ? defaultMetrics : metrics || null
226
+ this.httpMetrics = this.metrics ? httpMetrics(this.metrics) : null
227
+ // Compress JSON responses of at least this many bytes (false: never).
228
+ this.compressMinBytes = compression === false ? 0 : (compression?.minBytes ?? 1024)
124
229
 
125
230
  if (this.debug && this.production) {
126
231
  console.warn(
@@ -131,13 +236,46 @@ export class Server {
131
236
  }
132
237
 
133
238
  createHandler() {
134
- return async (req, res) => {
135
- enhanceResponse(res)
136
- try {
137
- await this.handle(req, res)
138
- } catch (err) {
139
- this.fail(req, res, err)
140
- }
239
+ return (req, res) => {
240
+ const startedAt = performance.now()
241
+ const requestId = requestIdOf(req)
242
+ req.id = requestId
243
+ res.setHeader('X-Request-Id', requestId)
244
+ res.once('finish', () => this.finishRequest(req, res, startedAt))
245
+ // Everything the request awaits runs inside its context, so logs
246
+ // anywhere below carry its id.
247
+ res.compressMinBytes = this.compressMinBytes
248
+ return requestContext.run({ requestId, method: req.method, path: pathOf(req.url) }, async () => {
249
+ enhanceResponse(res)
250
+ try {
251
+ await this.handle(req, res)
252
+ } catch (err) {
253
+ this.fail(req, res, err)
254
+ }
255
+ })
256
+ }
257
+ }
258
+
259
+ // Access log, slow-request warning and metrics, once the response is sent.
260
+ finishRequest(req, res, startedAt) {
261
+ const durationMs = performance.now() - startedAt
262
+ const path = pathOf(req.url)
263
+ // The route's pattern, not the URL: /posts/:id stays one series.
264
+ const route = req.route?.pattern ?? (res.statusCode === 404 ? 'not_found' : 'other')
265
+ if (this.httpMetrics) {
266
+ this.httpMetrics.requests.inc({ method: req.method, route, status: res.statusCode })
267
+ this.httpMetrics.duration.observe(durationMs / 1000, { method: req.method, route })
268
+ }
269
+ const fields = { method: req.method, path, status: res.statusCode, ms: Math.round(durationMs), requestId: req.id }
270
+ if (this.slowRequestMs > 0 && durationMs > this.slowRequestMs) {
271
+ this.logger.warn('Slow request', { ...fields, route })
272
+ return
273
+ }
274
+ // Health checks and metrics scrapes arrive every few seconds; logging
275
+ // them would bury everything else.
276
+ if (QUIET_PATHS.has(path)) return
277
+ if (this.accessLog === true || (this.accessLog === 'api' && path.startsWith('/api/'))) {
278
+ if (this.logger.isLevelEnabled('info')) this.logger.info(`${req.method} ${path} ${res.statusCode} ${fields.ms}ms`, this.production ? fields : undefined)
141
279
  }
142
280
  }
143
281
 
@@ -212,17 +350,31 @@ export class Server {
212
350
  }
213
351
 
214
352
  req.params = match.params
353
+ req.route = match.route
215
354
  req.query = parseQuery(req.url)
216
355
  req.cookies = parseCookies(req)
217
356
 
357
+ // Nothing to read on a request without a body (most GETs): skip
358
+ // waiting for the stream to end.
359
+ if (!hasBody(req)) {
360
+ req.rawBody = ''
361
+ req.body = {}
362
+ await match.handler(req, res)
363
+ return
364
+ }
365
+
218
366
  try {
219
- const { raw, body } = await readBody(req)
367
+ const { raw, body } = await readBody(req, { maxBytes: this.maxBodyBytes })
220
368
  // The exact text the client sent. Webhook signatures are computed
221
369
  // over these bytes, so they must not be re-serialised from req.body.
222
370
  req.rawBody = raw
223
371
  req.body = body
224
372
  } catch (err) {
225
- res.status(400).json({ error: err.message })
373
+ const status = err.status ?? 400
374
+ // After an oversized upload, don't reuse the connection: the rest of
375
+ // the body may still be on the wire.
376
+ if (status === 413) res.setHeader('Connection', 'close')
377
+ res.status(status).json({ error: err.message })
226
378
  return
227
379
  }
228
380
 
@@ -231,20 +383,18 @@ export class Server {
231
383
 
232
384
  logFailure(req, err) {
233
385
  // Log the path only: query strings can carry tokens.
234
- const where = `${req.method} ${String(req.url).split('?')[0]}`
386
+ const fields = { method: req.method, path: pathOf(req.url), requestId: req.id }
235
387
 
236
388
  if (err?.name === 'DatabaseError') {
237
- const lines = [
238
- `[tylix] ${where} failed: ${err.title || 'Database error'}` +
239
- ` (${err.driver}/${err.kind})`,
240
- ` ${err.message}`,
241
- ]
242
- if (err.sql) lines.push(` SQL: ${err.sql}`)
243
- if (err.hint) lines.push(` Fix: ${err.hint}`)
244
- console.error(lines.join('\n'))
389
+ this.logger.error(`${err.title || 'Database error'} (${err.driver}/${err.kind})`, {
390
+ ...fields,
391
+ detail: err.message,
392
+ ...(err.sql ? { sql: err.sql } : {}),
393
+ ...(err.hint ? { fix: err.hint } : {}),
394
+ })
245
395
  }
246
396
 
247
- console.error(`[tylix] ${where} failed:`, err)
397
+ this.logger.error(`${fields.method} ${fields.path} failed`, { ...fields, error: err })
248
398
  }
249
399
 
250
400
  sendDebug(req, res, err) {
@@ -298,8 +448,61 @@ export class Server {
298
448
  })
299
449
  }
300
450
 
451
+ // Starts listening on `port`. If that port is taken and autoPort is on,
452
+ // tries port + 1, port + 2, ... up to maxPortAttempts times.
453
+ //
454
+ // `callback` receives the port actually bound, which may differ from
455
+ // the one requested, so print THAT in your "running at" message.
456
+ // Port 0 (let the OS pick) never retries.
301
457
  listen(port, callback) {
302
- const server = http.createServer(this.createHandler())
303
- return server.listen(port, callback)
458
+ const server = http.createServer({ ServerResponse: TylixResponse }, this.createHandler())
459
+ const requested = Number(port)
460
+ let attempt = 0
461
+
462
+ const tryPort = (candidate) => {
463
+ const onError = (err) => {
464
+ const canRetry =
465
+ err.code === 'EADDRINUSE' &&
466
+ this.autoPort &&
467
+ requested !== 0 &&
468
+ attempt < this.maxPortAttempts
469
+
470
+ if (canRetry) {
471
+ attempt++
472
+ console.warn(
473
+ `[tylix] Port ${candidate} is already in use, trying ${candidate + 1}...`,
474
+ )
475
+ tryPort(candidate + 1)
476
+ return
477
+ }
478
+
479
+ if (err.code === 'EADDRINUSE') {
480
+ console.error(
481
+ `[tylix] Port ${candidate} is already in use.` +
482
+ (this.autoPort
483
+ ? ` Tried ${attempt + 1} port(s) starting at ${requested}.`
484
+ : ' Set AUTO_PORT=true to use the next free port, or change PORT.'),
485
+ )
486
+ }
487
+ // Same behaviour as before: with no 'error' listener this throws.
488
+ server.emit('error', err)
489
+ }
490
+
491
+ server.once('error', onError)
492
+ server.listen(candidate, () => {
493
+ server.removeListener('error', onError)
494
+ const bound = server.address()
495
+ const actual = typeof bound === 'object' && bound ? bound.port : candidate
496
+ if (actual !== requested && requested !== 0) {
497
+ console.warn(
498
+ `[tylix] Listening on port ${actual} instead of ${requested}.`,
499
+ )
500
+ }
501
+ if (callback) callback(actual)
502
+ })
503
+ }
504
+
505
+ tryPort(requested)
506
+ return server
304
507
  }
305
508
  }
@@ -1,3 +1,6 @@
1
+ import http from 'node:http'
2
+ import zlib from 'node:zlib'
3
+
1
4
  function serializeCookie(name, value, options = {}) {
2
5
  const parts = [`${name}=${encodeURIComponent(value)}`]
3
6
 
@@ -22,60 +25,101 @@ function serializeCookie(name, value, options = {}) {
22
25
  return parts.join('; ')
23
26
  }
24
27
 
25
- export function enhanceResponse(res) {
26
- res.status = function (code) {
27
- res.statusCode = code
28
- return res
28
+ // The response helpers (res.status, res.json, res.send, res.cookie,
29
+ // res.clearCookie). The Tylix server defines them once on its response
30
+ // class; enhanceResponse() adds them to any other response object.
31
+ // JSON bodies at least this big are compressed when the client accepts
32
+ // it (the server turns this on per response; see Server's compression).
33
+ // Brotli at a low quality and gzip at level 5 compress well at a small
34
+ // CPU cost, since this runs on every such response.
35
+ function compress(res, text) {
36
+ const minBytes = res.compressMinBytes
37
+ if (!minBytes || text.length < minBytes || res.getHeader('Content-Encoding')) return null
38
+ const accepted = String(res.req?.headers['accept-encoding'] ?? '')
39
+ res.setHeader('Vary', 'Accept-Encoding')
40
+ if (/\bbr\b/.test(accepted)) {
41
+ return {
42
+ encoding: 'br',
43
+ body: zlib.brotliCompressSync(text, {
44
+ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: text.length },
45
+ }),
46
+ }
29
47
  }
48
+ if (/\bgzip\b/.test(accepted)) return { encoding: 'gzip', body: zlib.gzipSync(text, { level: 5 }) }
49
+ return null
50
+ }
30
51
 
31
- res.json = function (data) {
32
- res.setHeader('Content-Type', 'application/json')
33
- res.end(JSON.stringify(data))
34
- return res
35
- }
52
+ const helpers = {
53
+ status(code) {
54
+ this.statusCode = code
55
+ return this
56
+ },
57
+
58
+ // Sent with a Content-Length, so Node needn't fall back to chunked
59
+ // encoding.
60
+ json(data) {
61
+ const text = JSON.stringify(data)
62
+ this.setHeader('Content-Type', 'application/json')
63
+ if (text === undefined) {
64
+ this.end()
65
+ return this
66
+ }
67
+ const compressed = compress(this, text)
68
+ if (compressed) {
69
+ this.setHeader('Content-Encoding', compressed.encoding)
70
+ this.setHeader('Content-Length', compressed.body.length)
71
+ this.end(this.req?.method === 'HEAD' ? undefined : compressed.body)
72
+ return this
73
+ }
74
+ this.setHeader('Content-Length', Buffer.byteLength(text))
75
+ this.end(text)
76
+ return this
77
+ },
36
78
 
37
- res.send = function (data) {
79
+ send(data) {
38
80
  if (data === undefined) {
39
- res.end()
40
- return res
81
+ this.end()
82
+ return this
41
83
  }
42
84
  if (typeof data === 'string' || Buffer.isBuffer(data)) {
43
- res.end(data)
44
- return res
85
+ this.end(data)
86
+ return this
45
87
  }
46
88
  // Objects, numbers, booleans: send as JSON with the right Content-Type.
47
- return res.json(data)
48
- }
89
+ return this.json(data)
90
+ },
49
91
 
50
92
  // Set-Cookie can legitimately appear more than once (access + refresh
51
93
  // tokens in the same response), so this appends rather than overwrites.
52
94
  // Secure defaults to on for HTTPS requests and in production, and is
53
95
  // forced on for SameSite=None (browsers reject it otherwise). Pass
54
96
  // secure: false explicitly to opt out.
55
- res.cookie = function (name, value, options = {}) {
97
+ cookie(name, value, options = {}) {
56
98
  const secureByDefault =
57
- Boolean(res.req && res.req.secure) ||
58
- process.env.NODE_ENV === 'production' ||
59
- options.sameSite === 'None'
99
+ Boolean(this.req && this.req.secure) || process.env.NODE_ENV === 'production' || options.sameSite === 'None'
60
100
  const serialized = serializeCookie(name, value, {
61
101
  ...options,
62
102
  secure: options.secure ?? secureByDefault,
63
103
  })
64
- const existing = res.getHeader('Set-Cookie')
65
- const cookies = existing
66
- ? Array.isArray(existing)
67
- ? existing.slice()
68
- : [existing]
69
- : []
104
+ const existing = this.getHeader('Set-Cookie')
105
+ const cookies = existing ? (Array.isArray(existing) ? existing.slice() : [existing]) : []
70
106
  cookies.push(serialized)
71
- res.setHeader('Set-Cookie', cookies)
72
- return res
73
- }
107
+ this.setHeader('Set-Cookie', cookies)
108
+ return this
109
+ },
74
110
 
75
- res.clearCookie = function (name, options = {}) {
76
- res.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
77
- return res
78
- }
111
+ clearCookie(name, options = {}) {
112
+ this.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
113
+ return this
114
+ },
115
+ }
79
116
 
117
+ // The response class the Tylix server creates its responses with.
118
+ export class TylixResponse extends http.ServerResponse {}
119
+ Object.assign(TylixResponse.prototype, helpers)
120
+
121
+ export function enhanceResponse(res) {
122
+ if (res instanceof TylixResponse) return res
123
+ for (const [name, fn] of Object.entries(helpers)) res[name] = fn.bind(res)
80
124
  return res
81
- }
125
+ }
@@ -1 +1,22 @@
1
- export declare function parseBody(req: import('node:http').IncomingMessage): Promise<Record<string, unknown>>
1
+ import type { IncomingMessage } from 'node:http'
2
+
3
+ export interface ReadBodyOptions {
4
+ /** Maximum body size in bytes. Defaults to 1 MB. Larger bodies reject with status 413. */
5
+ maxBytes?: number
6
+ }
7
+
8
+ /**
9
+ * Reads the whole request body once. `raw` is the exact UTF-8 text the
10
+ * client sent (use it for webhook signatures). `body` is the parsed JSON,
11
+ * or {} for empty and non-JSON bodies. Rejects with an Error carrying
12
+ * `status` (413 too large, 400 invalid JSON).
13
+ */
14
+ export declare function readBody(
15
+ req: IncomingMessage,
16
+ options?: ReadBodyOptions,
17
+ ): Promise<{ raw: string; body: any }>
18
+
19
+ export declare function parseBody(
20
+ req: IncomingMessage,
21
+ options?: ReadBodyOptions,
22
+ ): Promise<any>
@@ -1,3 +1,16 @@
1
+ const DEFAULT_MAX_BYTES = 1024 * 1024 // 1 MB
2
+
3
+ function isJson(contentType) {
4
+ const type = String(contentType).split(';')[0].trim().toLowerCase()
5
+ return type === 'application/json' || type.endsWith('+json')
6
+ }
7
+
8
+ function httpError(message, status) {
9
+ const err = new Error(message)
10
+ err.status = status
11
+ return err
12
+ }
13
+
1
14
  /**
2
15
  * Reads the whole request body once.
3
16
  * Returns { raw, body }: raw is the exact UTF-8 text the client sent,
@@ -6,41 +19,58 @@
6
19
  * Chunks are collected as Buffers and decoded once at the end. Joining
7
20
  * them as strings can split a multi-byte character across two chunks,
8
21
  * which would change the text and break webhook signature checks.
22
+ *
23
+ * Bodies larger than `maxBytes` (default 1 MB) are rejected with an error
24
+ * whose `status` is 413. Invalid JSON is rejected with status 400.
9
25
  */
10
- export function readBody(req) {
26
+ export function readBody(req, { maxBytes = DEFAULT_MAX_BYTES } = {}) {
11
27
  return new Promise((resolve, reject) => {
12
- const chunks = [];
13
-
14
- req.on("data", (chunk) => {
15
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
16
- });
28
+ const chunks = []
29
+ let size = 0
30
+ let tooLarge = false
17
31
 
18
- req.on("end", () => {
19
- const raw = Buffer.concat(chunks).toString("utf8");
32
+ // Reject early when the client announces a size that is already too big.
33
+ const declared = Number(req.headers['content-length'])
34
+ if (declared > maxBytes) {
35
+ req.resume() // drain so the response can still be sent
36
+ return reject(httpError('Request body too large', 413))
37
+ }
20
38
 
21
- if (!raw) {
22
- resolve({ raw: "", body: {} });
23
- return;
39
+ req.on('data', (chunk) => {
40
+ if (tooLarge) return // keep draining, stop buffering
41
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
42
+ size += buf.length
43
+ if (size > maxBytes) {
44
+ tooLarge = true
45
+ chunks.length = 0
46
+ reject(httpError('Request body too large', 413))
47
+ return
24
48
  }
49
+ chunks.push(buf)
50
+ })
51
+
52
+ req.on('end', () => {
53
+ if (tooLarge) return
54
+ const raw = Buffer.concat(chunks).toString('utf8')
55
+
56
+ if (!raw) return resolve({ raw: '', body: {} })
25
57
 
26
- const contentType = req.headers["content-type"] || "";
27
- if (!contentType.includes("application/json")) {
28
- resolve({ raw, body: {} });
29
- return;
58
+ if (!isJson(req.headers['content-type'] || '')) {
59
+ return resolve({ raw, body: {} })
30
60
  }
31
61
 
32
62
  try {
33
- resolve({ raw, body: JSON.parse(raw) });
34
- } catch (err) {
35
- reject(new Error("Invalid JSON body"));
63
+ resolve({ raw, body: JSON.parse(raw) })
64
+ } catch {
65
+ reject(httpError('Invalid JSON body', 400))
36
66
  }
37
- });
67
+ })
38
68
 
39
- req.on("error", reject);
40
- });
69
+ req.on('error', reject)
70
+ })
41
71
  }
42
72
 
43
- export async function parseBody(req) {
44
- const { body } = await readBody(req);
45
- return body;
73
+ export async function parseBody(req, options) {
74
+ const { body } = await readBody(req, options)
75
+ return body
46
76
  }
@@ -1,9 +1,17 @@
1
+ import type { Store } from '../store/index.js'
2
+
1
3
  export interface RateLimitResult {
2
4
  allowed: boolean
3
5
  retryAfterSeconds: number
4
6
  }
5
7
 
8
+ /** Counts in this process; answers synchronously. */
9
+ export declare function createRateLimiter(options: { max: number; windowMs: number }): (key: string) => RateLimitResult
10
+ /** Counts in the app's store ('shared') or the given store, across every process; answers with a Promise. */
6
11
  export declare function createRateLimiter(options: {
7
12
  max: number
8
13
  windowMs: number
9
- }): (key: string) => RateLimitResult
14
+ store: 'shared' | Store
15
+ /** Names the counter, so every process counts under the same key. */
16
+ name: string
17
+ }): (key: string) => Promise<RateLimitResult>