@zero-server/auth 0.9.6 → 0.9.8

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.
package/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- // AUTO-GENERATED by .tools/generate-package-stubs.js edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
1
+ // AUTO-GENERATED by .tools/generate-package-stubs.js - edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
2
2
  export * from './types/auth';
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // AUTO-GENERATED by .tools/generate-package-stubs.js edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
1
+ // AUTO-GENERATED by .tools/generate-package-stubs.js - edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
2
2
  'use strict';
3
3
  const lib = require("./lib/auth");
4
4
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @module auth/authorize
3
- * @description Authorization helpers role-based access control (RBAC),
3
+ * @description Authorization helpers - role-based access control (RBAC),
4
4
  * permission-based access, and policy classes.
5
5
  *
6
6
  * Works with any authentication middleware that sets `req.user`.
@@ -13,22 +13,22 @@
13
13
  * app.use(jwt({ secret: process.env.JWT_SECRET }));
14
14
  * app.use(attachUserHelpers());
15
15
  *
16
- * // Role-based only admins and editors can modify posts
16
+ * // Role-based - only admins and editors can modify posts
17
17
  * app.put('/posts/:id', authorize('admin', 'editor'), (req, res) => {
18
18
  * res.json({ updated: true });
19
19
  * });
20
20
  *
21
- * // Permission-based require ALL listed permissions
21
+ * // Permission-based - require ALL listed permissions
22
22
  * app.delete('/users/:id', can('users:read', 'users:delete'), (req, res) => {
23
23
  * res.json({ deleted: true });
24
24
  * });
25
25
  *
26
- * // ANY permission useful for overlapping access
26
+ * // ANY permission - useful for overlapping access
27
27
  * app.get('/reports', canAny('reports:read', 'admin:read'), (req, res) => {
28
28
  * res.json({ reports: [] });
29
29
  * });
30
30
  *
31
- * // Policy class resource-level authorization
31
+ * // Policy class - resource-level authorization
32
32
  * class PostPolicy extends Policy {
33
33
  * before(user) { if (user.role === 'superadmin') return true; }
34
34
  * update(user, post) { return user.id === post.authorId || user.role === 'admin'; }
@@ -114,9 +114,9 @@ function authorize(...roles)
114
114
  * Checks `req.user.permissions` (array or Set) for the required permission(s).
115
115
  *
116
116
  * Permission strings follow a `resource:action` convention:
117
- * - `'posts:write'` write access to posts
118
- * - `'users:delete'` delete users
119
- * - `'*'` superuser wildcard
117
+ * - `'posts:write'` - write access to posts
118
+ * - `'users:delete'` - delete users
119
+ * - `'*'` - superuser wildcard
120
120
  *
121
121
  * @param {...string} permissions - Required permissions (ALL must be present unless `opts.any` is true).
122
122
  * @returns {Function} Middleware `(req, res, next) => void`.
@@ -293,7 +293,7 @@ function gate(policy, action, getResource)
293
293
  });
294
294
  }
295
295
 
296
- // Attach resource if loaded saves a redundant DB query in the handler
296
+ // Attach resource if loaded - saves a redundant DB query in the handler
297
297
  if (resource && !req.resource) req.resource = resource;
298
298
  next();
299
299
  };
@@ -306,8 +306,8 @@ function gate(policy, action, getResource)
306
306
  * Call this middleware after JWT/session middleware.
307
307
  *
308
308
  * Adds:
309
- * - `req.user.is(...roles)` check roles
310
- * - `req.user.can(...perms)` check permissions
309
+ * - `req.user.is(...roles)` - check roles
310
+ * - `req.user.can(...perms)` - check permissions
311
311
  *
312
312
  * @returns {Function} Middleware.
313
313
  *
@@ -5,10 +5,10 @@
5
5
  * for TOTP-based two-factor authentication.
6
6
  *
7
7
  * Steps:
8
- * 1. `start()` Generate secret + backup codes, store in session
9
- * 2. `verify()` Confirm user can produce a valid TOTP code
10
- * 3. `complete()` Persist the verified secret to the database
11
- * 4. `disable()` Remove 2FA from the account
8
+ * 1. `start()` - Generate secret + backup codes, store in session
9
+ * 2. `verify()` - Confirm user can produce a valid TOTP code
10
+ * 3. `complete()` - Persist the verified secret to the database
11
+ * 4. `disable()` - Remove 2FA from the account
12
12
  *
13
13
  * @example | Full enrollment flow
14
14
  * const { enrollment } = require('@zero-server/sdk');
@@ -356,7 +356,7 @@ function enrollment(opts = {})
356
356
 
357
357
  function _defaultGetAccount(req)
358
358
  {
359
- if (!req.user) throw new Error('No user on request authentication middleware required');
359
+ if (!req.user) throw new Error('No user on request - authentication middleware required');
360
360
  return req.user.email || req.user.id || req.user.sub;
361
361
  }
362
362
 
package/lib/auth/jwt.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * const app = createApp();
14
14
  * const SECRET = process.env.JWT_SECRET;
15
15
  *
16
- * // Public issue tokens
16
+ * // Public - issue tokens
17
17
  * app.post('/login', json(), async (req, res) => {
18
18
  * const { email, password } = req.body;
19
19
  * const user = await db.users.findOne({ email });
@@ -24,7 +24,7 @@
24
24
  * res.json({ token });
25
25
  * });
26
26
  *
27
- * // Protected everything under /api requires a valid token
27
+ * // Protected - everything under /api requires a valid token
28
28
  * const api = Router();
29
29
  * api.use(jwt({ secret: SECRET }));
30
30
  * api.get('/me', (req, res) => res.json({ id: req.user.sub, role: req.user.role }));
@@ -79,7 +79,7 @@ function _base64urlDecode(str)
79
79
 
80
80
  /**
81
81
  * Decode a JWT without verifying the signature.
82
- * Returns `null` for malformed tokens never throws.
82
+ * Returns `null` for malformed tokens - never throws.
83
83
  *
84
84
  * @param {string} token - Raw JWT string.
85
85
  * @returns {{ header: object, payload: object, signature: string }|null}
@@ -268,7 +268,7 @@ function verify(token, secretOrKey, opts = {})
268
268
  * @param {Function} [opts.fetcher] - Custom fetch function (default: built-in fetch).
269
269
  * @param {number} [opts.cacheTtl=600000] - Cache TTL in ms (default 10 minutes).
270
270
  * @param {number} [opts.requestTimeout=5000] - Request timeout in ms.
271
- * @returns {Function} `async (header) => publicKey` resolves the signing key for a JWT header.
271
+ * @returns {Function} `async (header) => publicKey` - resolves the signing key for a JWT header.
272
272
  *
273
273
  * @example
274
274
  * const getKey = jwks('https://auth.example.com/.well-known/jwks.json');
@@ -330,7 +330,7 @@ function jwks(jwksUri, opts = {})
330
330
  return pem;
331
331
  }
332
332
 
333
- // No kid return the first RSA key
333
+ // No kid - return the first RSA key
334
334
  const first = keys.values().next().value;
335
335
  if (!first) throw _jwtError('No suitable key in JWKS', 'JWKS_NO_KEY');
336
336
  return first;
@@ -347,9 +347,9 @@ function jwks(jwksUri, opts = {})
347
347
  * Create JWT authentication middleware.
348
348
  *
349
349
  * On success, populates:
350
- * - `req.user` decoded payload
351
- * - `req.auth` `{ header, payload, token }` full decode info
352
- * - `req.token` raw JWT string
350
+ * - `req.user` - decoded payload
351
+ * - `req.auth` - `{ header, payload, token }` full decode info
352
+ * - `req.token` - raw JWT string
353
353
  *
354
354
  * @param {object} opts - Configuration.
355
355
  * @param {string|Buffer} [opts.secret] - HMAC secret for HS* algorithms.
@@ -367,7 +367,7 @@ function jwks(jwksUri, opts = {})
367
367
  * @param {number} [opts.clockTolerance=0] - Clock skew tolerance in seconds.
368
368
  * @param {number} [opts.maxAge] - Maximum token age in seconds.
369
369
  * @param {boolean} [opts.credentialsRequired=true] - Return 401 if no token found (false = optional auth).
370
- * @param {Function} [opts.isRevoked] - `async (payload) => boolean` check token revocation.
370
+ * @param {Function} [opts.isRevoked] - `async (payload) => boolean` - check token revocation.
371
371
  * @param {Function} [opts.onError] - Custom error handler `(err, req, res) => void`.
372
372
  * @returns {Function} Middleware `(req, res, next) => void`.
373
373
  *
package/lib/auth/oauth.js CHANGED
@@ -224,7 +224,7 @@ function oauth(opts = {})
224
224
  // Validate state (CSRF prevention)
225
225
  if (verify.state && query.state !== verify.state)
226
226
  {
227
- throw _oauthError('State mismatch possible CSRF attack', 'OAUTH_STATE_MISMATCH');
227
+ throw _oauthError('State mismatch - possible CSRF attack', 'OAUTH_STATE_MISMATCH');
228
228
  }
229
229
 
230
230
  const body = {
@@ -263,7 +263,7 @@ class Session
263
263
  return { ...this._flash };
264
264
  }
265
265
 
266
- /** @private serialize to JSON for cookie/store */
266
+ /** @private - serialize to JSON for cookie/store */
267
267
  _serialize()
268
268
  {
269
269
  const obj = { d: this._data };
@@ -271,7 +271,7 @@ class Session
271
271
  return JSON.stringify(obj);
272
272
  }
273
273
 
274
- /** @private deserialize from JSON */
274
+ /** @private - deserialize from JSON */
275
275
  static _deserialize(json, id)
276
276
  {
277
277
  try
@@ -472,7 +472,7 @@ function session(opts = {})
472
472
  req.session = sess;
473
473
 
474
474
  // Intercept response to persist session
475
- // Hook into res.raw.end (Node ServerResponse) the Response wrapper
475
+ // Hook into res.raw.end (Node ServerResponse) - the Response wrapper
476
476
  // has no .end() method; its .send()/.json() helpers call raw.end().
477
477
  const raw = res.raw;
478
478
  const origEnd = raw.end.bind(raw);
@@ -481,7 +481,7 @@ function session(opts = {})
481
481
  try
482
482
  {
483
483
  // _saveSession calls res.cookie() / res.clearCookie() which set
484
- // Set-Cookie headers on raw via raw.setHeader safe because
484
+ // Set-Cookie headers on raw via raw.setHeader - safe because
485
485
  // headers aren't flushed until the original end() runs.
486
486
  // NOTE: store-based sessions are sync-compatible because
487
487
  // MemoryStore.set/get return resolved promises synchronously
@@ -574,7 +574,7 @@ function _saveSession(req, res, sess, ctx)
574
574
  const encrypted = _encrypt(payload, ctx.keys[0]);
575
575
  if (encrypted.length > MAX_COOKIE_SIZE)
576
576
  {
577
- log.warn('session cookie exceeds %d bytes consider using a store', MAX_COOKIE_SIZE);
577
+ log.warn('session cookie exceeds %d bytes - consider using a store', MAX_COOKIE_SIZE);
578
578
  }
579
579
  res.cookie(ctx.cookieName, encrypted, cOpts);
580
580
  log.debug('cookie session saved');
@@ -7,7 +7,7 @@
7
7
  * Subsequent requests skip the 2FA prompt if the trust token is valid.
8
8
  * Supports secret rotation, IP binding, and revocation.
9
9
  *
10
- * Uses AES-256-GCM encryption tokens are encrypted, not just signed,
10
+ * Uses AES-256-GCM encryption - tokens are encrypted, not just signed,
11
11
  * preventing information leakage.
12
12
  *
13
13
  * @example
@@ -370,7 +370,7 @@ function _defaultFingerprint(req)
370
370
  */
371
371
  function _defaultGetUserId(req)
372
372
  {
373
- if (!req.user) throw new Error('No user on request authentication middleware required');
373
+ if (!req.user) throw new Error('No user on request - authentication middleware required');
374
374
  return req.user.id || req.user.sub || req.user._id;
375
375
  }
376
376
 
@@ -4,7 +4,7 @@
4
4
  * Implements TOTP (RFC 6238 / RFC 4226), backup codes,
5
5
  * and composable middleware for step-up verification.
6
6
  *
7
- * Uses only Node.js built-in `crypto` no external packages.
7
+ * Uses only Node.js built-in `crypto` - no external packages.
8
8
  *
9
9
  * @example | Setup 2FA for a user
10
10
  * const { twoFactor } = require('@zero-server/sdk');
@@ -228,7 +228,7 @@ function _base32Decode(str)
228
228
 
229
229
  /**
230
230
  * Generate an HOTP code for a given counter value.
231
- * Implements RFC 4226 §5 HMAC-based One-Time Password.
231
+ * Implements RFC 4226 §5 - HMAC-based One-Time Password.
232
232
  *
233
233
  * @param {Buffer} secret - Shared secret key.
234
234
  * @param {number} counter - 8-byte counter value.
@@ -498,13 +498,13 @@ function verifyBackupCode(code, hashes)
498
498
 
499
499
  /**
500
500
  * Middleware that requires completed 2FA verification on the session.
501
- * Checks `req.session.get('twoFactorVerified')` returns 403 if not set.
501
+ * Checks `req.session.get('twoFactorVerified')` - returns 403 if not set.
502
502
  *
503
503
  * Designed to compose with `jwt()` or `session()` middleware:
504
504
  *
505
505
  * app.use(jwt({ secret }));
506
506
  * app.use(require2FA());
507
- * // or
507
+ * // - or -
508
508
  * app.use(session({ secret }));
509
509
  * app.use(require2FA());
510
510
  *
@@ -517,7 +517,7 @@ function verifyBackupCode(code, hashes)
517
517
  * Defaults to always requiring 2FA.
518
518
  * @returns {Function} Middleware `(req, res, next) => void`.
519
519
  *
520
- * @example | Basic all authenticated users must complete 2FA
520
+ * @example | Basic - all authenticated users must complete 2FA
521
521
  * app.use(require2FA());
522
522
  *
523
523
  * @example | Only enforce for users who have enrolled
@@ -548,7 +548,7 @@ function require2FA(opts = {})
548
548
  const enabled = await isEnabled(req);
549
549
  if (!enabled)
550
550
  {
551
- log('2FA not enabled for user skipping');
551
+ log('2FA not enabled for user - skipping');
552
552
  return next();
553
553
  }
554
554
  }
@@ -568,7 +568,7 @@ function require2FA(opts = {})
568
568
  const session = req.session;
569
569
  if (!session || typeof session.get !== 'function')
570
570
  {
571
- log.warn('require2FA: no session found is session() middleware active?');
571
+ log.warn('require2FA: no session found - is session() middleware active?');
572
572
  const raw = res.raw || res;
573
573
  if (raw.headersSent) return;
574
574
  raw.statusCode = 500;
@@ -583,7 +583,7 @@ function require2FA(opts = {})
583
583
  return next();
584
584
  }
585
585
 
586
- log.warn('2FA not completed blocking request');
586
+ log.warn('2FA not completed - blocking request');
587
587
  const raw = res.raw || res;
588
588
  if (raw.headersSent) return;
589
589
  raw.statusCode = statusCode;
@@ -690,7 +690,7 @@ function verifyTOTPMiddleware(opts = {})
690
690
  raw.end(JSON.stringify({ error: 'Too many attempts. Try again later.', retryAfter }));
691
691
  return;
692
692
  }
693
- // Lockout expired reset
693
+ // Lockout expired - reset
694
694
  attempts.delete(ip);
695
695
  }
696
696
 
@@ -735,7 +735,7 @@ function verifyTOTPMiddleware(opts = {})
735
735
 
736
736
  if (result.valid)
737
737
  {
738
- // Replay prevention (RFC 6238 §5.2) check AFTER signature
738
+ // Replay prevention (RFC 6238 §5.2) - check AFTER signature
739
739
  // verification to avoid leaking timing information about whether
740
740
  // a code was previously used.
741
741
  if (opts.replayStore)
@@ -775,7 +775,7 @@ function verifyTOTPMiddleware(opts = {})
775
775
  catch (err)
776
776
  {
777
777
  log.error('replay store error: %s', err.message);
778
- // Fail open for store errors don't block legitimate users
778
+ // Fail open for store errors - don't block legitimate users
779
779
  }
780
780
  }
781
781
 
@@ -145,7 +145,7 @@ const cbor = {
145
145
  if (additionalInfo === 23) return undefined;
146
146
  if (additionalInfo === 25)
147
147
  {
148
- // float16 not commonly used in WebAuthn but handle it
148
+ // float16 - not commonly used in WebAuthn but handle it
149
149
  offset -= 0; // already read
150
150
  return readArgument(additionalInfo);
151
151
  }
@@ -593,7 +593,7 @@ function verifyRegistration(opts)
593
593
  if (clientData.type !== 'webauthn.create')
594
594
  return { verified: false, credential: null, error: `Invalid type: ${clientData.type}` };
595
595
 
596
- // Strict origin validation exact match, no regex
596
+ // Strict origin validation - exact match, no regex
597
597
  if (clientData.origin !== expectedOrigin)
598
598
  return { verified: false, credential: null, error: `Origin mismatch: ${clientData.origin}` };
599
599
 
@@ -627,7 +627,7 @@ function verifyRegistration(opts)
627
627
 
628
628
  if (fmt === 'none')
629
629
  {
630
- // No attestation acceptable for 'none' conveyance
630
+ // No attestation - acceptable for 'none' conveyance
631
631
  log.debug('registration with "none" attestation format');
632
632
  }
633
633
  else if (fmt === 'packed')
@@ -644,7 +644,7 @@ function verifyRegistration(opts)
644
644
  }
645
645
  else
646
646
  {
647
- log.warn('unknown attestation format: %s treating as none', fmt);
647
+ log.warn('unknown attestation format: %s - treating as none', fmt);
648
648
  }
649
649
 
650
650
  // 8. Extract public key from COSE format
@@ -703,7 +703,7 @@ function _verifyPackedAttestation(attStmt, parsedAuthData, rawAuthData, clientDa
703
703
  }
704
704
  else
705
705
  {
706
- // Self-attestation verify with the credential public key
706
+ // Self-attestation - verify with the credential public key
707
707
  const { key } = _coseToPublicKey(parsedAuthData.credentialPublicKey);
708
708
  const algName = _coseAlgToNodeAlg(alg);
709
709
  return crypto.verify(algName, signedData, key, sig);
@@ -881,7 +881,7 @@ function verifyAuthentication(opts)
881
881
  if (!authData.userPresent)
882
882
  return { verified: false, newCounter: null, error: 'User not present' };
883
883
 
884
- // 5. Counter validation detect cloned authenticators
884
+ // 5. Counter validation - detect cloned authenticators
885
885
  if (authData.signCount > 0 || credential.counter > 0)
886
886
  {
887
887
  if (authData.signCount <= credential.counter)
package/lib/debug.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * log.error('failed to connect', err);
17
17
  * log('shorthand for debug level');
18
18
  *
19
- * // Set minimum level anything below is silenced
19
+ * // Set minimum level - anything below is silenced
20
20
  * debug.level('warn'); // only warn, error, fatal
21
21
  * debug.level('silent'); // suppress all output
22
22
  * debug.level('trace'); // show everything
@@ -81,7 +81,7 @@ _enabledPatterns = _parsePatterns();
81
81
  */
82
82
  function _isEnabled(ns)
83
83
  {
84
- if (!_enabledPatterns) return true; // No DEBUG set enable all
84
+ if (!_enabledPatterns) return true; // No DEBUG set - enable all
85
85
  let enabled = false;
86
86
  for (const { neg, re } of _enabledPatterns)
87
87
  {
@@ -116,7 +116,7 @@ function _ts()
116
116
  }
117
117
 
118
118
  /**
119
- * Format arguments (like console.log supports %s, %d, %j, %o).
119
+ * Format arguments (like console.log - supports %s, %d, %j, %o).
120
120
  * @private
121
121
  */
122
122
  function _format(args)
@@ -278,13 +278,13 @@ function debug(namespace)
278
278
  * Messages below this level are silenced.
279
279
  *
280
280
  * @param {string|number} level - Level name or number.
281
- * `'trace'` (0) all output
282
- * `'debug'` (1) debug and above
283
- * `'info'` (2) info and above
284
- * `'warn'` (3) warn and above
285
- * `'error'` (4) error and fatal only
286
- * `'fatal'` (5) fatal only
287
- * `'silent'` (6) nothing
281
+ * `'trace'` (0) - all output
282
+ * `'debug'` (1) - debug and above
283
+ * `'info'` (2) - info and above
284
+ * `'warn'` (3) - warn and above
285
+ * `'error'` (4) - error and fatal only
286
+ * `'fatal'` (5) - fatal only
287
+ * `'silent'` (6) - nothing
288
288
  */
289
289
  debug.level = function(level)
290
290
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero-server/auth",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "description": "JWT, sessions, OAuth, authorize, MFA stack.",
5
5
  "keywords": [
6
6
  "zero-server",
@@ -45,10 +45,10 @@
45
45
  },
46
46
  "sideEffects": false,
47
47
  "dependencies": {
48
- "@zero-server/fetch": "0.9.6"
48
+ "@zero-server/fetch": "0.9.8"
49
49
  },
50
50
  "peerDependencies": {
51
- "@zero-server/sdk": ">=0.9.6"
51
+ "@zero-server/sdk": ">=0.9.8"
52
52
  },
53
53
  "peerDependenciesMeta": {
54
54
  "@zero-server/sdk": {
package/types/body.d.ts CHANGED
@@ -1,14 +1,82 @@
1
- // Re-exports for @zero-server/body body parser types
2
- export {
3
- BodyParserOptions,
4
- JsonParserOptions,
5
- UrlencodedParserOptions,
6
- TextParserOptions,
7
- MultipartOptions,
8
- MultipartFile,
9
- json,
10
- urlencoded,
11
- text,
12
- raw,
13
- multipart,
14
- } from './middleware';
1
+ // TypeScript declarations for the bundled body parsers
2
+ // (`json`, `urlencoded`, `text`, `raw`, `multipart`).
3
+ //
4
+ // These live in `lib/body/*` at runtime and are surfaced both via the
5
+ // top-level SDK and the standalone `@zero-server/body` scope. They are
6
+ // declared here (not in `./middleware`) so the body-parser package has
7
+ // a self-contained declaration file.
8
+
9
+ import { MiddlewareFunction } from './middleware';
10
+ import { Request } from './request';
11
+ import { Response } from './response';
12
+
13
+ export interface BodyParserOptions {
14
+ /** Max body size (e.g. '10kb', '1mb'). Default: '1mb'. */
15
+ limit?: string | number;
16
+ /** Content-Type(s) to match. Accepts a string, an array of strings, or a predicate function. */
17
+ type?: string | string[] | ((ct: string) => boolean);
18
+ /** Reject non-HTTPS requests with 403. */
19
+ requireSecure?: boolean;
20
+ /**
21
+ * Verification callback invoked with the raw buffer before parsing.
22
+ * Throw an error to reject the request with 403.
23
+ * Useful for webhook signature verification (e.g. Stripe, GitHub).
24
+ */
25
+ verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void;
26
+ /** Decompress gzip/deflate/br request bodies. Default: true. When false, compressed bodies return 415. */
27
+ inflate?: boolean;
28
+ }
29
+
30
+ export interface JsonParserOptions extends BodyParserOptions {
31
+ /** JSON.parse reviver function. */
32
+ reviver?: (key: string, value: any) => any;
33
+ /** Reject non-object/array roots. Default: true. */
34
+ strict?: boolean;
35
+ }
36
+
37
+ export interface UrlencodedParserOptions extends BodyParserOptions {
38
+ /** Enable nested bracket parsing. Default: false. */
39
+ extended?: boolean;
40
+ /** Max number of parameters. Default: 1000. Prevents parameter flooding DoS. */
41
+ parameterLimit?: number;
42
+ /** Max nesting depth for bracket syntax. Default: 32. Prevents deep-nesting DoS. */
43
+ depth?: number;
44
+ }
45
+
46
+ export interface TextParserOptions extends BodyParserOptions {
47
+ /** Fallback character encoding when Content-Type has no charset. Default: 'utf8'. */
48
+ encoding?: BufferEncoding;
49
+ }
50
+
51
+ export interface MultipartOptions {
52
+ /** Upload directory (default: OS temp). */
53
+ dir?: string;
54
+ /** Maximum size per file in bytes. */
55
+ maxFileSize?: number;
56
+ /** Reject non-HTTPS requests with 403. */
57
+ requireSecure?: boolean;
58
+ /** Maximum number of non-file fields. Default: 1000. */
59
+ maxFields?: number;
60
+ /** Maximum number of uploaded files. Default: 10. */
61
+ maxFiles?: number;
62
+ /** Maximum size of a single field value in bytes. Default: 1 MB. */
63
+ maxFieldSize?: number;
64
+ /** Whitelist of allowed MIME types for uploaded files (e.g. ['image/png', 'image/jpeg']). */
65
+ allowedMimeTypes?: string[];
66
+ /** Maximum combined size of all uploaded files in bytes. */
67
+ maxTotalSize?: number;
68
+ }
69
+
70
+ export interface MultipartFile {
71
+ originalFilename: string;
72
+ storedName: string;
73
+ path: string;
74
+ contentType: string;
75
+ size: number;
76
+ }
77
+
78
+ export function json(options?: JsonParserOptions): MiddlewareFunction;
79
+ export function urlencoded(options?: UrlencodedParserOptions): MiddlewareFunction;
80
+ export function text(options?: TextParserOptions): MiddlewareFunction;
81
+ export function raw(options?: BodyParserOptions): MiddlewareFunction;
82
+ export function multipart(options?: MultipartOptions): MiddlewareFunction;
package/types/cli.d.ts CHANGED
@@ -1,2 +1,40 @@
1
- // Re-exports for @zero-server/cli CLI runner types
2
- export { CLI, runCLI } from './orm';
1
+ // TypeScript declarations for the bundled CLI runner (`zs` / `zh`).
2
+ //
3
+ // The CLI lives in `lib/cli.js` and is published both as the `zs` /
4
+ // `zh` bin scripts and as a programmatic API on the SDK. It dispatches
5
+ // ORM subcommands (`migrate`, `seed`, `make:*`) to `@zero-server/orm`
6
+ // and `webrtc:*` subcommands to `@zero-server/webrtc`, but the runner
7
+ // itself is scope-neutral - hence its own declaration file.
8
+
9
+ /**
10
+ * CLI runner for the bundled `zs` command.
11
+ *
12
+ * Parses `process.argv`-style input, resolves a config file
13
+ * (`zero.config.js` / `.zero-server.js` / `.zero-http.js`), and
14
+ * dispatches to the matching subcommand handler.
15
+ */
16
+ export class CLI {
17
+ constructor(argv?: string[]);
18
+
19
+ /** The first positional argument (subcommand name). Defaults to `"help"`. */
20
+ readonly command: string;
21
+
22
+ /** Remaining positional arguments after the subcommand. */
23
+ readonly args: string[];
24
+
25
+ /** Parsed `--flag=value` and `-f value` pairs. */
26
+ readonly flags: Map<string, string>;
27
+
28
+ /** Execute the parsed command. Sets `process.exitCode` on failure. */
29
+ run(): Promise<void>;
30
+ }
31
+
32
+ /**
33
+ * One-shot helper: `new CLI(argv).run()`.
34
+ *
35
+ * @example
36
+ * const { runCLI } = require('@zero-server/sdk');
37
+ * await runCLI(['migrate']);
38
+ * await runCLI(['make:model', 'User', '--dir=src/models']);
39
+ */
40
+ export function runCLI(argv?: string[]): Promise<void>;