@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,320 +1,320 @@
1
- import { Request } from './request';
2
- import { Response } from './response';
3
-
4
- // --- Core Types --------------------------------------------------
5
-
6
- export type NextFunction = (err?: any) => void;
7
- export type MiddlewareFunction = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
8
- export type ErrorHandlerFunction = (err: any, req: Request, res: Response, next: NextFunction) => void;
9
-
10
- // --- CORS --------------------------------------------------------
11
-
12
- export interface CorsOptions {
13
- origin?: string | string[];
14
- methods?: string;
15
- allowedHeaders?: string;
16
- exposedHeaders?: string;
17
- credentials?: boolean;
18
- maxAge?: number;
19
- }
20
-
21
- export function cors(options?: CorsOptions): MiddlewareFunction;
22
-
23
- // --- Body Parsers ------------------------------------------------
24
-
25
- export interface BodyParserOptions {
26
- /** Max body size (e.g. '10kb', '1mb'). Default: '1mb'. */
27
- limit?: string | number;
28
- /** Content-Type(s) to match. Accepts a string, an array of strings, or a predicate function. */
29
- type?: string | string[] | ((ct: string) => boolean);
30
- /** Reject non-HTTPS requests with 403. */
31
- requireSecure?: boolean;
32
- /**
33
- * Verification callback invoked with the raw buffer before parsing.
34
- * Throw an error to reject the request with 403.
35
- * Useful for webhook signature verification (e.g. Stripe, GitHub).
36
- */
37
- verify?: (req: import('./request').Request, res: import('./response').Response, buf: Buffer, encoding: string) => void;
38
- /** Decompress gzip/deflate/br request bodies. Default: true. When false, compressed bodies return 415. */
39
- inflate?: boolean;
40
- }
41
-
42
- export interface JsonParserOptions extends BodyParserOptions {
43
- /** JSON.parse reviver function. */
44
- reviver?: (key: string, value: any) => any;
45
- /** Reject non-object/array roots. Default: true. */
46
- strict?: boolean;
47
- }
48
-
49
- export interface UrlencodedParserOptions extends BodyParserOptions {
50
- /** Enable nested bracket parsing. Default: false. */
51
- extended?: boolean;
52
- /** Max number of parameters. Default: 1000. Prevents parameter flooding DoS. */
53
- parameterLimit?: number;
54
- /** Max nesting depth for bracket syntax. Default: 32. Prevents deep-nesting DoS. */
55
- depth?: number;
56
- }
57
-
58
- export interface TextParserOptions extends BodyParserOptions {
59
- /** Fallback character encoding when Content-Type has no charset. Default: 'utf8'. */
60
- encoding?: BufferEncoding;
61
- }
62
-
63
- export interface MultipartOptions {
64
- /** Upload directory (default: OS temp). */
65
- dir?: string;
66
- /** Maximum size per file in bytes. */
67
- maxFileSize?: number;
68
- /** Reject non-HTTPS requests with 403. */
69
- requireSecure?: boolean;
70
- /** Maximum number of non-file fields. Default: 1000. */
71
- maxFields?: number;
72
- /** Maximum number of uploaded files. Default: 10. */
73
- maxFiles?: number;
74
- /** Maximum size of a single field value in bytes. Default: 1 MB. */
75
- maxFieldSize?: number;
76
- /** Whitelist of allowed MIME types for uploaded files (e.g. ['image/png', 'image/jpeg']). */
77
- allowedMimeTypes?: string[];
78
- /** Maximum combined size of all uploaded files in bytes. */
79
- maxTotalSize?: number;
80
- }
81
-
82
- export interface MultipartFile {
83
- originalFilename: string;
84
- storedName: string;
85
- path: string;
86
- contentType: string;
87
- size: number;
88
- }
89
-
90
- export function json(options?: JsonParserOptions): MiddlewareFunction;
91
- export function urlencoded(options?: UrlencodedParserOptions): MiddlewareFunction;
92
- export function text(options?: TextParserOptions): MiddlewareFunction;
93
- export function raw(options?: BodyParserOptions): MiddlewareFunction;
94
- export function multipart(options?: MultipartOptions): MiddlewareFunction;
95
-
96
- // --- Rate Limiting -----------------------------------------------
97
-
98
- export interface RateLimitOptions {
99
- /** Time window in ms. Default: 60000. */
100
- windowMs?: number;
101
- /** Max requests per window per IP. Default: 100. */
102
- max?: number;
103
- /** Custom error message. */
104
- message?: string;
105
- /** HTTP status for rate-limited responses. Default: 429. */
106
- statusCode?: number;
107
- /** Custom key extraction function. */
108
- keyGenerator?: (req: Request) => string;
109
- /** Return true to skip rate limiting for this request. */
110
- skip?: (req: Request) => boolean;
111
- /** Custom handler for rate-limited requests (replaces default 429 JSON response). */
112
- handler?: (req: Request, res: Response) => void;
113
- }
114
-
115
- export function rateLimit(opts?: RateLimitOptions): MiddlewareFunction;
116
-
117
- // --- Logger ------------------------------------------------------
118
-
119
- export interface LoggerOptions {
120
- /** Custom log function. Default: console.log. */
121
- logger?: (...args: any[]) => void;
122
- /** Colorize output. Default: true when TTY. */
123
- colors?: boolean;
124
- /** Format: 'tiny' | 'short' | 'dev'. Default: 'dev'. */
125
- format?: 'tiny' | 'short' | 'dev';
126
- }
127
-
128
- export function logger(opts?: LoggerOptions): MiddlewareFunction;
129
-
130
- // --- Compression -------------------------------------------------
131
-
132
- export interface CompressOptions {
133
- /** Minimum body size to compress. Default: 1024. */
134
- threshold?: number;
135
- /** Compression level. */
136
- level?: number;
137
- /** Force specific encoding(s). */
138
- encoding?: string | string[];
139
- /** Filter function — return false to skip compression. */
140
- filter?: (req: Request, res: Response) => boolean;
141
- }
142
-
143
- export function compress(opts?: CompressOptions): MiddlewareFunction;
144
-
145
- // --- Helmet (Security Headers) ----------------------------------
146
-
147
- export interface HelmetOptions {
148
- /** CSP directive object or `false` to disable. */
149
- contentSecurityPolicy?: { directives?: Record<string, string[]> } | false;
150
- /** Set COEP header. Default: false. */
151
- crossOriginEmbedderPolicy?: boolean;
152
- /** COOP value. Default: 'same-origin'. */
153
- crossOriginOpenerPolicy?: string | false;
154
- /** CORP value. Default: 'same-origin'. */
155
- crossOriginResourcePolicy?: string | false;
156
- /** Set X-DNS-Prefetch-Control. Default: true. */
157
- dnsPrefetchControl?: boolean | false;
158
- /** X-Frame-Options value. Default: 'deny'. */
159
- frameguard?: 'deny' | 'sameorigin' | false;
160
- /** Remove X-Powered-By. Default: true. */
161
- hidePoweredBy?: boolean;
162
- /** Set HSTS. Default: true. */
163
- hsts?: boolean | false;
164
- /** HSTS max-age in seconds. Default: 15552000. */
165
- hstsMaxAge?: number;
166
- /** HSTS includeSubDomains. Default: true. */
167
- hstsIncludeSubDomains?: boolean;
168
- /** HSTS preload. Default: false. */
169
- hstsPreload?: boolean;
170
- /** Set X-Download-Options. Default: true. */
171
- ieNoOpen?: boolean;
172
- /** Set X-Content-Type-Options: nosniff. Default: true. */
173
- noSniff?: boolean;
174
- /** X-Permitted-Cross-Domain-Policies. Default: 'none'. */
175
- permittedCrossDomainPolicies?: string | false;
176
- /** Referrer-Policy value. Default: 'no-referrer'. */
177
- referrerPolicy?: string | false;
178
- /** Set legacy X-XSS-Protection. Default: false. */
179
- xssFilter?: boolean;
180
- }
181
-
182
- export function helmet(opts?: HelmetOptions): MiddlewareFunction;
183
-
184
- // --- Timeout -----------------------------------------------------
185
-
186
- export interface TimeoutOptions {
187
- /** HTTP status code for timeout responses. Default: 408. */
188
- status?: number;
189
- /** Error message body. Default: 'Request Timeout'. */
190
- message?: string;
191
- }
192
-
193
- export function timeout(ms?: number, opts?: TimeoutOptions): MiddlewareFunction;
194
-
195
- // --- Request ID --------------------------------------------------
196
-
197
- export interface RequestIdOptions {
198
- /** Response header name. Default: 'X-Request-Id'. */
199
- header?: string;
200
- /** Custom ID generator. */
201
- generator?: () => string;
202
- /** Trust incoming X-Request-Id. Default: false. */
203
- trustProxy?: boolean;
204
- }
205
-
206
- export function requestId(opts?: RequestIdOptions): MiddlewareFunction;
207
-
208
- // --- Cookie Parser -----------------------------------------------
209
-
210
- export interface CookieParserStatic {
211
- (secret?: string | string[], opts?: { decode?: boolean }): MiddlewareFunction;
212
- /** Sign a value with a secret. */
213
- sign(val: string, secret: string): string;
214
- /** Unsign a signed value against one or more secrets. Returns the original value or false. */
215
- unsign(val: string, secrets: string | string[]): string | false;
216
- /** Serialize a value as a JSON cookie string (j: prefix). */
217
- jsonCookie(val: any): string;
218
- /** Parse a JSON cookie string (j: prefix). Returns parsed value or original string. */
219
- parseJSON(str: string): any;
220
- }
221
-
222
- export const cookieParser: CookieParserStatic;
223
-
224
- // --- Static File Serving -----------------------------------------
225
-
226
- export interface StaticOptions {
227
- /** Default file for directories. Default: 'index.html'. */
228
- index?: string | false;
229
- /** Cache-Control max-age in ms. Default: 0. */
230
- maxAge?: number;
231
- /** Dotfile policy: 'allow' | 'deny' | 'ignore'. Default: 'ignore'. */
232
- dotfiles?: 'allow' | 'deny' | 'ignore';
233
- /** Fallback extensions. */
234
- extensions?: string[];
235
- /** Custom header hook. */
236
- setHeaders?: (res: Response, filePath: string) => void;
237
- /** HTTP/2 push: list of asset paths or function returning them. Only triggers for HTML responses on HTTP/2 connections. */
238
- pushAssets?: string[] | ((filePath: string) => string[]);
239
- }
240
-
241
- declare function serveStatic(root: string, options?: StaticOptions): MiddlewareFunction;
242
- export { serveStatic as static };
243
-
244
- // --- CSRF Protection ---------------------------------------------
245
-
246
- export interface CsrfOptions {
247
- /** Double-submit cookie name. Default: '_csrf'. */
248
- cookie?: string;
249
- /** Request header name for the token. Default: 'x-csrf-token'. */
250
- header?: string;
251
- /** Bytes of randomness for token generation. Default: 18. */
252
- saltLength?: number;
253
- /** HMAC secret. Auto-generated if not provided. */
254
- secret?: string;
255
- /** HTTP methods to skip CSRF checks. Default: ['GET', 'HEAD', 'OPTIONS']. */
256
- ignoreMethods?: string[];
257
- /** Path prefixes to skip CSRF checks. */
258
- ignorePaths?: string[];
259
- /** Custom error handler. Default: sends 403 JSON. */
260
- onError?: (req: Request, res: Response) => void;
261
- }
262
-
263
- export function csrf(options?: CsrfOptions): MiddlewareFunction;
264
-
265
- // --- Request Validator -------------------------------------------
266
-
267
- export interface ValidationRule {
268
- /** Type with coercion. */
269
- type?: 'string' | 'integer' | 'number' | 'float' | 'boolean' | 'array' | 'json' | 'date' | 'uuid' | 'email' | 'url';
270
- /** Field is required. */
271
- required?: boolean;
272
- /** Default value or factory function. */
273
- default?: any | (() => any);
274
- /** Minimum string length. */
275
- minLength?: number;
276
- /** Maximum string length. */
277
- maxLength?: number;
278
- /** Minimum numeric value. */
279
- min?: number;
280
- /** Maximum numeric value. */
281
- max?: number;
282
- /** Pattern match constraint. */
283
- match?: RegExp;
284
- /** Allowed values. */
285
- enum?: any[];
286
- /** Minimum array length. */
287
- minItems?: number;
288
- /** Maximum array length. */
289
- maxItems?: number;
290
- /** Custom validation function. Return a string to indicate an error. */
291
- validate?: (value: any) => string | void;
292
- }
293
-
294
- export interface ValidatorSchema {
295
- /** Rules for `req.body` fields. */
296
- body?: Record<string, ValidationRule>;
297
- /** Rules for `req.query` fields. */
298
- query?: Record<string, ValidationRule>;
299
- /** Rules for `req.params` fields. */
300
- params?: Record<string, ValidationRule>;
301
- }
302
-
303
- export interface ValidatorOptions {
304
- /** Remove fields not in schema. Default: true. */
305
- stripUnknown?: boolean;
306
- /** Custom error handler. Default: sends 422 JSON. */
307
- onError?: (errors: string[], req: Request, res: Response) => void;
308
- }
309
-
310
- export interface ValidateFunction {
311
- (schema: ValidatorSchema, options?: ValidatorOptions): MiddlewareFunction;
312
-
313
- /** Validate a single field value against a rule. */
314
- field(value: any, rule: ValidationRule, field: string): { value: any; error: string | null };
315
-
316
- /** Validate an object against a schema. */
317
- object(data: object, schema: Record<string, ValidationRule>, opts?: { stripUnknown?: boolean }): { sanitized: object; errors: string[] };
318
- }
319
-
320
- export const validate: ValidateFunction;
1
+ import { Request } from './request';
2
+ import { Response } from './response';
3
+
4
+ // --- Core Types --------------------------------------------------
5
+
6
+ export type NextFunction = (err?: any) => void;
7
+ export type MiddlewareFunction = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
8
+ export type ErrorHandlerFunction = (err: any, req: Request, res: Response, next: NextFunction) => void;
9
+
10
+ // --- CORS --------------------------------------------------------
11
+
12
+ export interface CorsOptions {
13
+ origin?: string | string[];
14
+ methods?: string;
15
+ allowedHeaders?: string;
16
+ exposedHeaders?: string;
17
+ credentials?: boolean;
18
+ maxAge?: number;
19
+ }
20
+
21
+ export function cors(options?: CorsOptions): MiddlewareFunction;
22
+
23
+ // --- Body Parsers ------------------------------------------------
24
+
25
+ export interface BodyParserOptions {
26
+ /** Max body size (e.g. '10kb', '1mb'). Default: '1mb'. */
27
+ limit?: string | number;
28
+ /** Content-Type(s) to match. Accepts a string, an array of strings, or a predicate function. */
29
+ type?: string | string[] | ((ct: string) => boolean);
30
+ /** Reject non-HTTPS requests with 403. */
31
+ requireSecure?: boolean;
32
+ /**
33
+ * Verification callback invoked with the raw buffer before parsing.
34
+ * Throw an error to reject the request with 403.
35
+ * Useful for webhook signature verification (e.g. Stripe, GitHub).
36
+ */
37
+ verify?: (req: import('./request').Request, res: import('./response').Response, buf: Buffer, encoding: string) => void;
38
+ /** Decompress gzip/deflate/br request bodies. Default: true. When false, compressed bodies return 415. */
39
+ inflate?: boolean;
40
+ }
41
+
42
+ export interface JsonParserOptions extends BodyParserOptions {
43
+ /** JSON.parse reviver function. */
44
+ reviver?: (key: string, value: any) => any;
45
+ /** Reject non-object/array roots. Default: true. */
46
+ strict?: boolean;
47
+ }
48
+
49
+ export interface UrlencodedParserOptions extends BodyParserOptions {
50
+ /** Enable nested bracket parsing. Default: false. */
51
+ extended?: boolean;
52
+ /** Max number of parameters. Default: 1000. Prevents parameter flooding DoS. */
53
+ parameterLimit?: number;
54
+ /** Max nesting depth for bracket syntax. Default: 32. Prevents deep-nesting DoS. */
55
+ depth?: number;
56
+ }
57
+
58
+ export interface TextParserOptions extends BodyParserOptions {
59
+ /** Fallback character encoding when Content-Type has no charset. Default: 'utf8'. */
60
+ encoding?: BufferEncoding;
61
+ }
62
+
63
+ export interface MultipartOptions {
64
+ /** Upload directory (default: OS temp). */
65
+ dir?: string;
66
+ /** Maximum size per file in bytes. */
67
+ maxFileSize?: number;
68
+ /** Reject non-HTTPS requests with 403. */
69
+ requireSecure?: boolean;
70
+ /** Maximum number of non-file fields. Default: 1000. */
71
+ maxFields?: number;
72
+ /** Maximum number of uploaded files. Default: 10. */
73
+ maxFiles?: number;
74
+ /** Maximum size of a single field value in bytes. Default: 1 MB. */
75
+ maxFieldSize?: number;
76
+ /** Whitelist of allowed MIME types for uploaded files (e.g. ['image/png', 'image/jpeg']). */
77
+ allowedMimeTypes?: string[];
78
+ /** Maximum combined size of all uploaded files in bytes. */
79
+ maxTotalSize?: number;
80
+ }
81
+
82
+ export interface MultipartFile {
83
+ originalFilename: string;
84
+ storedName: string;
85
+ path: string;
86
+ contentType: string;
87
+ size: number;
88
+ }
89
+
90
+ export function json(options?: JsonParserOptions): MiddlewareFunction;
91
+ export function urlencoded(options?: UrlencodedParserOptions): MiddlewareFunction;
92
+ export function text(options?: TextParserOptions): MiddlewareFunction;
93
+ export function raw(options?: BodyParserOptions): MiddlewareFunction;
94
+ export function multipart(options?: MultipartOptions): MiddlewareFunction;
95
+
96
+ // --- Rate Limiting -----------------------------------------------
97
+
98
+ export interface RateLimitOptions {
99
+ /** Time window in ms. Default: 60000. */
100
+ windowMs?: number;
101
+ /** Max requests per window per IP. Default: 100. */
102
+ max?: number;
103
+ /** Custom error message. */
104
+ message?: string;
105
+ /** HTTP status for rate-limited responses. Default: 429. */
106
+ statusCode?: number;
107
+ /** Custom key extraction function. */
108
+ keyGenerator?: (req: Request) => string;
109
+ /** Return true to skip rate limiting for this request. */
110
+ skip?: (req: Request) => boolean;
111
+ /** Custom handler for rate-limited requests (replaces default 429 JSON response). */
112
+ handler?: (req: Request, res: Response) => void;
113
+ }
114
+
115
+ export function rateLimit(opts?: RateLimitOptions): MiddlewareFunction;
116
+
117
+ // --- Logger ------------------------------------------------------
118
+
119
+ export interface LoggerOptions {
120
+ /** Custom log function. Default: console.log. */
121
+ logger?: (...args: any[]) => void;
122
+ /** Colorize output. Default: true when TTY. */
123
+ colors?: boolean;
124
+ /** Format: 'tiny' | 'short' | 'dev'. Default: 'dev'. */
125
+ format?: 'tiny' | 'short' | 'dev';
126
+ }
127
+
128
+ export function logger(opts?: LoggerOptions): MiddlewareFunction;
129
+
130
+ // --- Compression -------------------------------------------------
131
+
132
+ export interface CompressOptions {
133
+ /** Minimum body size to compress. Default: 1024. */
134
+ threshold?: number;
135
+ /** Compression level. */
136
+ level?: number;
137
+ /** Force specific encoding(s). */
138
+ encoding?: string | string[];
139
+ /** Filter function — return false to skip compression. */
140
+ filter?: (req: Request, res: Response) => boolean;
141
+ }
142
+
143
+ export function compress(opts?: CompressOptions): MiddlewareFunction;
144
+
145
+ // --- Helmet (Security Headers) ----------------------------------
146
+
147
+ export interface HelmetOptions {
148
+ /** CSP directive object or `false` to disable. */
149
+ contentSecurityPolicy?: { directives?: Record<string, string[]> } | false;
150
+ /** Set COEP header. Default: false. */
151
+ crossOriginEmbedderPolicy?: boolean;
152
+ /** COOP value. Default: 'same-origin'. */
153
+ crossOriginOpenerPolicy?: string | false;
154
+ /** CORP value. Default: 'same-origin'. */
155
+ crossOriginResourcePolicy?: string | false;
156
+ /** Set X-DNS-Prefetch-Control. Default: true. */
157
+ dnsPrefetchControl?: boolean | false;
158
+ /** X-Frame-Options value. Default: 'deny'. */
159
+ frameguard?: 'deny' | 'sameorigin' | false;
160
+ /** Remove X-Powered-By. Default: true. */
161
+ hidePoweredBy?: boolean;
162
+ /** Set HSTS. Default: true. */
163
+ hsts?: boolean | false;
164
+ /** HSTS max-age in seconds. Default: 15552000. */
165
+ hstsMaxAge?: number;
166
+ /** HSTS includeSubDomains. Default: true. */
167
+ hstsIncludeSubDomains?: boolean;
168
+ /** HSTS preload. Default: false. */
169
+ hstsPreload?: boolean;
170
+ /** Set X-Download-Options. Default: true. */
171
+ ieNoOpen?: boolean;
172
+ /** Set X-Content-Type-Options: nosniff. Default: true. */
173
+ noSniff?: boolean;
174
+ /** X-Permitted-Cross-Domain-Policies. Default: 'none'. */
175
+ permittedCrossDomainPolicies?: string | false;
176
+ /** Referrer-Policy value. Default: 'no-referrer'. */
177
+ referrerPolicy?: string | false;
178
+ /** Set legacy X-XSS-Protection. Default: false. */
179
+ xssFilter?: boolean;
180
+ }
181
+
182
+ export function helmet(opts?: HelmetOptions): MiddlewareFunction;
183
+
184
+ // --- Timeout -----------------------------------------------------
185
+
186
+ export interface TimeoutOptions {
187
+ /** HTTP status code for timeout responses. Default: 408. */
188
+ status?: number;
189
+ /** Error message body. Default: 'Request Timeout'. */
190
+ message?: string;
191
+ }
192
+
193
+ export function timeout(ms?: number, opts?: TimeoutOptions): MiddlewareFunction;
194
+
195
+ // --- Request ID --------------------------------------------------
196
+
197
+ export interface RequestIdOptions {
198
+ /** Response header name. Default: 'X-Request-Id'. */
199
+ header?: string;
200
+ /** Custom ID generator. */
201
+ generator?: () => string;
202
+ /** Trust incoming X-Request-Id. Default: false. */
203
+ trustProxy?: boolean;
204
+ }
205
+
206
+ export function requestId(opts?: RequestIdOptions): MiddlewareFunction;
207
+
208
+ // --- Cookie Parser -----------------------------------------------
209
+
210
+ export interface CookieParserStatic {
211
+ (secret?: string | string[], opts?: { decode?: boolean }): MiddlewareFunction;
212
+ /** Sign a value with a secret. */
213
+ sign(val: string, secret: string): string;
214
+ /** Unsign a signed value against one or more secrets. Returns the original value or false. */
215
+ unsign(val: string, secrets: string | string[]): string | false;
216
+ /** Serialize a value as a JSON cookie string (j: prefix). */
217
+ jsonCookie(val: any): string;
218
+ /** Parse a JSON cookie string (j: prefix). Returns parsed value or original string. */
219
+ parseJSON(str: string): any;
220
+ }
221
+
222
+ export const cookieParser: CookieParserStatic;
223
+
224
+ // --- Static File Serving -----------------------------------------
225
+
226
+ export interface StaticOptions {
227
+ /** Default file for directories. Default: 'index.html'. */
228
+ index?: string | false;
229
+ /** Cache-Control max-age in ms. Default: 0. */
230
+ maxAge?: number;
231
+ /** Dotfile policy: 'allow' | 'deny' | 'ignore'. Default: 'ignore'. */
232
+ dotfiles?: 'allow' | 'deny' | 'ignore';
233
+ /** Fallback extensions. */
234
+ extensions?: string[];
235
+ /** Custom header hook. */
236
+ setHeaders?: (res: Response, filePath: string) => void;
237
+ /** HTTP/2 push: list of asset paths or function returning them. Only triggers for HTML responses on HTTP/2 connections. */
238
+ pushAssets?: string[] | ((filePath: string) => string[]);
239
+ }
240
+
241
+ declare function serveStatic(root: string, options?: StaticOptions): MiddlewareFunction;
242
+ export { serveStatic as static };
243
+
244
+ // --- CSRF Protection ---------------------------------------------
245
+
246
+ export interface CsrfOptions {
247
+ /** Double-submit cookie name. Default: '_csrf'. */
248
+ cookie?: string;
249
+ /** Request header name for the token. Default: 'x-csrf-token'. */
250
+ header?: string;
251
+ /** Bytes of randomness for token generation. Default: 18. */
252
+ saltLength?: number;
253
+ /** HMAC secret. Auto-generated if not provided. */
254
+ secret?: string;
255
+ /** HTTP methods to skip CSRF checks. Default: ['GET', 'HEAD', 'OPTIONS']. */
256
+ ignoreMethods?: string[];
257
+ /** Path prefixes to skip CSRF checks. */
258
+ ignorePaths?: string[];
259
+ /** Custom error handler. Default: sends 403 JSON. */
260
+ onError?: (req: Request, res: Response) => void;
261
+ }
262
+
263
+ export function csrf(options?: CsrfOptions): MiddlewareFunction;
264
+
265
+ // --- Request Validator -------------------------------------------
266
+
267
+ export interface ValidationRule {
268
+ /** Type with coercion. */
269
+ type?: 'string' | 'integer' | 'number' | 'float' | 'boolean' | 'array' | 'json' | 'date' | 'uuid' | 'email' | 'url';
270
+ /** Field is required. */
271
+ required?: boolean;
272
+ /** Default value or factory function. */
273
+ default?: any | (() => any);
274
+ /** Minimum string length. */
275
+ minLength?: number;
276
+ /** Maximum string length. */
277
+ maxLength?: number;
278
+ /** Minimum numeric value. */
279
+ min?: number;
280
+ /** Maximum numeric value. */
281
+ max?: number;
282
+ /** Pattern match constraint. */
283
+ match?: RegExp;
284
+ /** Allowed values. */
285
+ enum?: any[];
286
+ /** Minimum array length. */
287
+ minItems?: number;
288
+ /** Maximum array length. */
289
+ maxItems?: number;
290
+ /** Custom validation function. Return a string to indicate an error. */
291
+ validate?: (value: any) => string | void;
292
+ }
293
+
294
+ export interface ValidatorSchema {
295
+ /** Rules for `req.body` fields. */
296
+ body?: Record<string, ValidationRule>;
297
+ /** Rules for `req.query` fields. */
298
+ query?: Record<string, ValidationRule>;
299
+ /** Rules for `req.params` fields. */
300
+ params?: Record<string, ValidationRule>;
301
+ }
302
+
303
+ export interface ValidatorOptions {
304
+ /** Remove fields not in schema. Default: true. */
305
+ stripUnknown?: boolean;
306
+ /** Custom error handler. Default: sends 422 JSON. */
307
+ onError?: (errors: string[], req: Request, res: Response) => void;
308
+ }
309
+
310
+ export interface ValidateFunction {
311
+ (schema: ValidatorSchema, options?: ValidatorOptions): MiddlewareFunction;
312
+
313
+ /** Validate a single field value against a rule. */
314
+ field(value: any, rule: ValidationRule, field: string): { value: any; error: string | null };
315
+
316
+ /** Validate an object against a schema. */
317
+ object(data: object, schema: Record<string, ValidationRule>, opts?: { stripUnknown?: boolean }): { sanitized: object; errors: string[] };
318
+ }
319
+
320
+ export const validate: ValidateFunction;