@maroonedsoftware/koa 2.1.21 → 2.2.1

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/README.md CHANGED
@@ -23,7 +23,7 @@ Peer dependencies: `koa`, `@koa/router`, `@koa/cors`.
23
23
  - **bodyParserMiddleware** — Parses JSON, form, text, multipart, or raw body by allowed content types
24
24
  - **defaultParserMappings** — Pre-built MIME-type-to-parser map for use with `bodyParserMiddleware`
25
25
  - **requireSignature** — Router middleware that verifies a request HMAC signature against `ctx.rawBody`
26
- - **requireSecurity** — Router middleware that enforces a valid authentication session, with optional MFA enforcement
26
+ - **requirePolicy** — Router middleware that enforces a valid authentication session and a named policy (defaults to `auth.session.mfa.satisfied`); pluggable via `PolicyService`
27
27
 
28
28
  ## Usage
29
29
 
@@ -124,20 +124,28 @@ router.get('/api/me', async ctx => {
124
124
 
125
125
  ### Authorization
126
126
 
127
- `requireSecurity` is router middleware that runs after `authenticationMiddleware`. It throws 401 when the request is unauthenticated and, by default, when multi-factor authentication has not been satisfied.
127
+ `requirePolicy` is router middleware that runs after `authenticationMiddleware`. It throws **401** with `WWW-Authenticate: Bearer error="invalid_token"` when the request is unauthenticated, and **403** when the named policy denies. The policy's own deny shape carries the response details and any `WWW-Authenticate` value (e.g. `Bearer error="mfa_required"`).
128
128
 
129
- A session satisfies MFA when it carries at least two factors and at least one factor is not of `kind: 'knowledge'` (i.e. a `possession` or `biometric` factor was also satisfied). MFA failures emit `WWW-Authenticate: Bearer error="mfa_required"`; missing/invalid sessions emit `Bearer error="invalid_token"`.
129
+ By default, `requirePolicy()` enforces the `'auth.session.mfa.satisfied'` policy bundled with `@maroonedsoftware/authentication` as `DefaultMfaSatisfiedPolicy`. It allows when the session carries at least two factors and at least one is not of `kind: 'knowledge'`. Override by registering your own class against the same name in `PolicyRegistryMap` (e.g. to grant MFA credit to `oidc` sessions when your IdP enforces 2FA upstream).
130
130
 
131
131
  ```typescript
132
- import { requireSecurity } from '@maroonedsoftware/koa';
132
+ import { requirePolicy } from '@maroonedsoftware/koa';
133
133
 
134
- // Require any authenticated user with MFA (default)
135
- router.get('/api/profile', requireSecurity(), handler);
134
+ // Default MFA gate
135
+ router.get('/api/profile', requirePolicy(), handler);
136
136
 
137
- // Authentication only — useful for step-up routes such as MFA enrollment
138
- router.post('/api/mfa/enroll', requireSecurity({ requireMfa: false }), handler);
137
+ // AAL2 step-up gate (uses 'auth.session.assurance.level')
138
+ router.post('/api/admin/dangerous', requirePolicy({ policy: 'auth.session.assurance.level' }), handler);
139
+
140
+ // Recent-factor step-up gate (uses 'auth.session.recent.factor')
141
+ router.post('/api/billing/update', requirePolicy({ policy: 'auth.session.recent.factor' }), handler);
142
+
143
+ // Authenticated-only — useful for step-up routes such as MFA enrollment
144
+ router.post('/api/mfa/enroll', requirePolicy({ policy: false }), handler);
139
145
  ```
140
146
 
147
+ The middleware resolves `PolicyService` from `ctx.container` per request and calls `policyService.assert(name, { session })`. Headers, details, and internal log context come from the policy's deny payload — see `@maroonedsoftware/policies` and `@maroonedsoftware/authentication` for the policy authoring API.
148
+
141
149
  ### CORS
142
150
 
143
151
  ```typescript
@@ -279,7 +287,7 @@ The default mappings are:
279
287
  | `authenticationMiddleware()` | Resolves `Authorization` header via `AuthenticationSchemeHandler`; populates `ctx.authenticationSession` |
280
288
  | `bodyParserMiddleware(contentTypes)` | Parses body by allowed MIME types; throws 400/411/415/422 on invalid input |
281
289
  | `requireSignature(optionsKey)` | Verifies HMAC of `ctx.rawBody` against a request header; throws 401 on mismatch |
282
- | `requireSecurity(options?)` | Throws 401 when the session is invalid; with default `{ requireMfa: true }` also throws 401 (`mfa_required`) unless MFA is satisfied |
290
+ | `requirePolicy(options?)` | Throws 401 when the session is invalid; otherwise asserts `options.policy` (default `'auth.session.mfa.satisfied'`) via `PolicyService`, which throws 403 with policy-supplied details/headers on deny. Pass `{ policy: false }` to skip the policy check. |
283
291
 
284
292
  ### Parser options
285
293
 
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export * from './middleware/server/rate.limiter.middleware.js';
7
7
  export * from './middleware/server/serverkit.context.middleware.js';
8
8
  export * from './middleware/server/authentication.middleware.js';
9
9
  export * from './middleware/router/body.parser.middleware.js';
10
- export * from './middleware/router/require.security.middleware.js';
10
+ export * from './middleware/router/require.policy.middleware.js';
11
11
  export * from './middleware/router/require.signature.middleware.js';
12
12
  export * from './parsers/serverkit.parser.js';
13
13
  export * from './serverkit.bodyparser.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,wCAAwC,CAAC;AACvD,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,qDAAqD,CAAC;AACpE,cAAc,kDAAkD,CAAC;AACjE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,oDAAoD,CAAC;AACnE,cAAc,qDAAqD,CAAC;AACpE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wCAAwC,CAAC;AACvD,cAAc,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,wCAAwC,CAAC;AACvD,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,qDAAqD,CAAC;AACpE,cAAc,kDAAkD,CAAC;AACjE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,kDAAkD,CAAC;AACjE,cAAc,qDAAqD,CAAC;AACpE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wCAAwC,CAAC;AACvD,cAAc,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -274,23 +274,27 @@ var bodyParserMiddleware = /* @__PURE__ */ __name((contentTypes) => {
274
274
  };
275
275
  }, "bodyParserMiddleware");
276
276
 
277
- // src/middleware/router/require.security.middleware.ts
277
+ // src/middleware/router/require.policy.middleware.ts
278
278
  import { invalidAuthenticationSession as invalidAuthenticationSession2 } from "@maroonedsoftware/authentication";
279
+ import { PolicyService } from "@maroonedsoftware/policies";
279
280
  import { unauthorizedError } from "@maroonedsoftware/errors";
280
- var requireSecurity = /* @__PURE__ */ __name((options = {
281
- requireMfa: true
282
- }) => {
281
+ var DEFAULT_POLICY = "auth.session.mfa.satisfied";
282
+ var requirePolicy = /* @__PURE__ */ __name((options = {}) => {
283
+ const policy = options.policy === void 0 ? DEFAULT_POLICY : options.policy;
283
284
  return async (ctx, next) => {
284
- const authenticationSession = ctx.authenticationSession;
285
- if (authenticationSession === invalidAuthenticationSession2) {
285
+ const session = ctx.authenticationSession;
286
+ if (session === invalidAuthenticationSession2) {
286
287
  throw unauthorizedError('Bearer error="invalid_token"');
287
288
  }
288
- if (options.requireMfa && (authenticationSession.factors.length < 2 || authenticationSession.factors.every((factor) => factor.kind === "knowledge"))) {
289
- throw unauthorizedError('Bearer error="mfa_required"');
289
+ if (policy !== false) {
290
+ const policyService = ctx.container.get(PolicyService);
291
+ await policyService.assert(policy, {
292
+ session
293
+ });
290
294
  }
291
295
  await next();
292
296
  };
293
- }, "requireSecurity");
297
+ }, "requirePolicy");
294
298
 
295
299
  // src/middleware/router/require.signature.middleware.ts
296
300
  import { createHmac } from "crypto";
@@ -669,7 +673,7 @@ export {
669
673
  defaultParserMappings,
670
674
  errorMiddleware,
671
675
  rateLimiterMiddleware,
672
- requireSecurity,
676
+ requirePolicy,
673
677
  requireSignature,
674
678
  serverKitContextMiddleware
675
679
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/serverkit.context.ts","../src/serverkit.router.ts","../src/middleware/server/cors.middleware.ts","../src/middleware/server/error.middleware.ts","../src/middleware/server/rate.limiter.middleware.ts","../src/middleware/server/serverkit.context.middleware.ts","../src/middleware/server/authentication.middleware.ts","../src/middleware/router/body.parser.middleware.ts","../src/serverkit.bodyparser.ts","../src/middleware/router/require.security.middleware.ts","../src/middleware/router/require.signature.middleware.ts","../src/parsers/serverkit.parser.ts","../src/parsers/json.parser.ts","../src/parsers/text.parser.ts","../src/parsers/form.parser.ts","../src/parsers/multipart.parser.ts","../src/parsers/binary.parser.ts","../src/parsers/serverkit.default.parsers.ts"],"sourcesContent":["import { Context } from 'koa';\nimport { Container, Injectable } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { AuthenticationSession } from '@maroonedsoftware/authentication';\nimport { BinaryLike } from 'node:crypto';\n\n/**\n * Koa context extended with ServerKit request-scoped services and metadata.\n * Populated by {@link serverKitContextMiddleware}.\n * Use this as the context type for route handlers to get full typing of `ctx.container`, `ctx.logger`, and request IDs.\n *\n * @extends Context\n * @see {@link serverKitContextMiddleware} – middleware that populates this context on each request\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport interface ServerKitContext extends Context {\n /** Scoped injectkit container for this request; use for request-scoped DI. */\n container: Container;\n /** Request-scoped logger instance. */\n logger: Logger;\n /** Logger name for this request (e.g. request path or route identifier). */\n loggerName: string;\n /** Value of the `User-Agent` request header, or empty string if absent. */\n userAgent: string;\n /** IP address of the client. */\n ipAddress: string;\n /** Correlation ID for tracing; from `X-Correlation-Id` header or generated. */\n correlationId: string;\n /** Request ID; from `X-Request-Id` header or generated. */\n requestId: string;\n /** Raw body for this request. */\n rawBody: BinaryLike;\n /** Authentication session. */\n authenticationSession: AuthenticationSession;\n}\n\n/**\n * Abstract class merged with the {@link ServerKitContext} interface so it can serve as an\n * injectkit injection token. {@link serverKitContextMiddleware} registers the live `ctx`\n * against this token in the request-scoped container, allowing services to declare\n * `ServerKitContext` as a constructor dependency and receive the current Koa context.\n */\n@Injectable()\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport abstract class ServerKitContext implements ServerKitContext {}\n","import { DefaultState } from 'koa';\nimport Router, { RouterOptions } from '@koa/router';\nimport { ServerKitContext } from './serverkit.context.js';\n\n/**\n * Creates a new Koa router typed for ServerKit state and context.\n * Use with {@link ServerKitContext} for full typing of `ctx` in route handlers.\n *\n * @typeParam StateT - Koa state type (defaults to `DefaultState`).\n * @typeParam ContextT - Context type (defaults to `ServerKitContext`).\n * @param options - Router options (defaults to `undefined`).\n * @returns A new {@link Router} instance with the given options.\n */\nexport const ServerKitRouter = <StateT = DefaultState, ContextT = ServerKitContext>(options?: RouterOptions) => new Router<StateT, ContextT>(options);\n","import cors from '@koa/cors';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { Context } from 'koa';\n\n/**\n * CORS options for {@link corsMiddleware}.\n * Extends `@koa/cors` options with an `origin` that may be a string or array of strings/RegExps.\n */\nexport interface CorsOptions extends Omit<cors.Options, 'origin'> {\n /** Allowed origin(s): `'*'`, a single origin string, or an array of strings/RegExps to match. */\n origin?: string | (string | RegExp)[];\n}\n\n/**\n * Adds CORS headers to responses using `@koa/cors` with ServerKit-compatible origin matching.\n * Supports `'*'`, exact string origins, and RegExp patterns.\n *\n * @param options - Optional {@link CorsOptions}; defaults to `GET,HEAD,PUT,POST,DELETE,PATCH` methods.\n * @returns {@link ServerKitMiddleware} that applies CORS headers.\n */\nexport const corsMiddleware = (options?: CorsOptions): ServerKitMiddleware => {\n // return the request origin as its own matcher to support RegExp\n const originMatcher = (ctx: Context): string => {\n const origin = ctx.get('origin');\n const matchers = options?.origin ?? ['*'];\n for (const matcher of matchers) {\n if (matcher === '*') {\n return origin;\n }\n\n if (typeof matcher === 'string') {\n if (matcher === origin) {\n return origin;\n }\n continue;\n }\n\n if (matcher.test(origin)) {\n return origin;\n }\n }\n\n // return the zero value to prevent matches\n return '';\n };\n\n return cors({\n ...options,\n origin: originMatcher,\n allowMethods: options?.allowMethods ?? 'GET,HEAD,PUT,POST,DELETE,PATCH',\n secureContext: options?.secureContext ?? false,\n keepHeadersOnError: options?.keepHeadersOnError ?? false,\n privateNetworkAccess: options?.privateNetworkAccess ?? false,\n });\n};\n","import { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { IsHttpError, IsServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Central error handler: catches thrown errors, sets status/body from HTTP errors,\n * returns 404 for unmatched routes, and 500 for unknown errors.\n * Emits `error` or `warn` on the app for logging.\n *\n * @returns {@link ServerKitMiddleware} that wraps the stack in try/catch and normalizes responses.\n */\nexport const errorMiddleware = (): ServerKitMiddleware => {\n return async (ctx, next) => {\n try {\n await next();\n if (ctx.status === 404 && !ctx.body) {\n const body = {\n statusCode: 404,\n message: 'Not Found',\n details: { url: ctx.URL.toString() },\n };\n ctx.status = 404;\n ctx.body = body;\n ctx.app.emit('warn', body, ctx);\n }\n } catch (error) {\n if (IsHttpError(error)) {\n ctx.status = error.statusCode;\n ctx.body = {\n statusCode: error.statusCode,\n message: error.message,\n details: error.details,\n };\n if (error.headers) {\n for (const entry of Object.entries(error.headers)) {\n ctx.set(entry[0], entry[1]);\n }\n }\n } else if (IsServerkitError(error)) {\n ctx.status = 500;\n ctx.body = {\n statusCode: 500,\n message: error.message,\n details: error.details,\n };\n } else {\n ctx.status = 500;\n ctx.body = {\n statusCode: 500,\n message: 'Internal Server Error',\n };\n }\n\n ctx.app.emit('error', error, ctx);\n }\n };\n};\n","import { RateLimiterAbstract, RateLimiterRes } from 'rate-limiter-flexible';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\n\n/** Type guard that narrows `error` to a `RateLimiterRes` (i.e. a rate-limit exceeded response). */\nconst isRateLimiterError = (error: unknown): error is RateLimiterRes => {\n return error instanceof RateLimiterRes || ('msBeforeNext' in (error as object) && 'remainingPoints' in (error as object));\n};\n\n/**\n * Enforces rate limiting per client IP using a `rate-limiter-flexible` instance.\n * Consumes one token per request; throws HTTP 429 when the limit is exceeded.\n *\n * @param rateLimiter - A {@link RateLimiterAbstract} instance (e.g. `RateLimiterMemory`, `RateLimiterRedis`).\n * @returns {@link ServerKitMiddleware} that consumes a token and continues or throws 429.\n */\nexport const rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract): ServerKitMiddleware => {\n return async (ctx, next) => {\n try {\n await rateLimiter.consume(ctx.ip);\n } catch (error: unknown) {\n let headers: Record<string, string> = {};\n if (isRateLimiterError(error)) {\n headers = {\n 'retry-after': (error.msBeforeNext / 1000).toString(),\n 'x-ratelimit-limit': rateLimiter.points.toString(),\n 'x-ratelimit-remaining': error.remainingPoints.toString(),\n 'x-ratelimit-reset': Math.ceil((Date.now() + error.msBeforeNext) / 1000).toString(),\n };\n }\n\n throw httpError(429)\n .withCause(error as Error)\n .withHeaders(headers);\n }\n\n await next();\n };\n};\n","import crypto from 'crypto';\nimport { Container } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { ServerKitContext } from '../../serverkit.context.js';\n\n/**\n * Populates {@link ServerKitContext} for each request: scoped container, logger,\n * logger name, user-agent, correlation ID, and request ID.\n * Reads or generates `X-Correlation-Id` and `X-Request-Id` and sets response headers.\n * Registers the live `ctx` against the {@link ServerKitContext} injection token in the\n * request-scoped container so downstream services can inject the current context.\n * Should be applied early so downstream middleware and routes can use `ctx.container` and `ctx.logger`.\n *\n * @param container - Root injectkit {@link Container} used to create a scoped container and resolve {@link Logger}.\n * @returns {@link ServerKitMiddleware} that attaches ServerKit context to `ctx`.\n */\nexport const serverKitContextMiddleware = (container: Container): ServerKitMiddleware => {\n return async (ctx, next) => {\n const scopedContainer = container.createScopedContainer();\n ctx.container = scopedContainer;\n\n scopedContainer.override(ServerKitContext, ctx);\n\n ctx.logger = ctx.container.get(Logger);\n ctx.loggerName = ctx.path;\n\n ctx.userAgent = ctx.get('user-agent');\n ctx.ipAddress = ctx.ip;\n\n const correlationId = ctx.headers['x-correlation-id'];\n ctx.correlationId = Array.isArray(correlationId) ? (correlationId[0] ?? crypto.randomUUID()) : (correlationId ?? crypto.randomUUID());\n\n ctx.requestId = crypto.randomUUID();\n\n ctx.headers['x-correlation-id'] = ctx.correlationId;\n ctx.set('x-correlation-id', ctx.correlationId);\n\n ctx.headers['x-request-id'] = ctx.requestId;\n ctx.set('x-request-id', ctx.requestId);\n\n await next();\n };\n};\n","import { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { AuthenticationSchemeHandler, invalidAuthenticationSession } from '@maroonedsoftware/authentication';\n\n/**\n * Resolves the `Authorization` request header into an {@link AuthenticationSession}\n * and attaches it to `ctx.authenticationSession`.\n *\n * The header is immediately removed from `ctx.req.headers` after being read so it\n * cannot be accidentally captured by downstream logging or serialization.\n *\n * Resolution is delegated to the {@link AuthenticationSchemeHandler} registered in\n * the DI container. `ctx.authenticationSession` is initialised to\n * {@link invalidAuthenticationSession} before delegation, ensuring that any error\n * thrown by the scheme handler leaves the context in a safe, unauthenticated state.\n *\n * @returns A {@link ServerKitMiddleware} that populates `ctx.authenticationSession`.\n *\n * @example\n * ```typescript\n * app.use(authenticationMiddleware());\n * ```\n */\nexport const authenticationMiddleware = (): ServerKitMiddleware => {\n return async (ctx, next) => {\n ctx.authenticationSession = invalidAuthenticationSession; // bad initial state so it will fail verification\n\n // NOTE: we delete the auth headers on the request here to ensure we don't accidentally log it\n const authorizationHeader = ctx.req.headers.authorization;\n delete ctx.req.headers.authorization;\n\n const schemeHandler = ctx.container.get(AuthenticationSchemeHandler);\n\n ctx.authenticationSession = await schemeHandler.handle(authorizationHeader);\n\n await next();\n };\n};\n","import { httpError, IsHttpError } from '@maroonedsoftware/errors';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { ServerKitBodyParser } from '../../serverkit.bodyparser.js';\n\n/**\n * Parses the request body based on `Content-Type` and assigns it to `ctx.body`.\n * Rejects requests with unexpected or unsupported content types.\n *\n * Supported types: JSON, URL-encoded form, text, multipart, PDF (raw buffer).\n * Requires a body when `contentTypes` is non-empty; otherwise rejects bodies.\n *\n * @param contentTypes - Allowed MIME types (e.g. `['application/json', 'application/x-www-form-urlencoded']`).\n * Use an empty array to disallow any request body.\n * @returns {@link ServerKitRouterMiddleware} that parses the body and sets `ctx.body`.\n * @throws HTTP 400 if body is present when no content types are allowed.\n * @throws HTTP 411 if body is required but missing.\n * @throws HTTP 415 if `Content-Type` is not in `contentTypes`.\n * @throws HTTP 422 if body is invalid or media type is unsupported.\n */\nexport const bodyParserMiddleware = (contentTypes: string[]): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n if (contentTypes.length === 0) {\n if (ctx.request.length > 0) {\n throw httpError(400).withDetails({ body: 'Unexpected body' });\n }\n } else {\n if (ctx.request.length > 0) {\n if (!ctx.request.is(contentTypes)) {\n throw httpError(415).withDetails({\n 'content-type': `must be ${contentTypes.length > 1 ? 'one of ' : ''}${contentTypes.join(', ')}`,\n value: ctx.request.type,\n });\n }\n\n try {\n const parser = ctx.container.get(ServerKitBodyParser);\n const result = await parser.parse(ctx);\n ctx.body = result.parsed;\n ctx.rawBody = result.raw;\n } catch (error) {\n if (IsHttpError(error)) {\n throw error;\n }\n throw httpError(422)\n .withCause(error as Error)\n .withDetails({ body: 'Invalid request body format' });\n }\n } else {\n throw httpError(411);\n }\n }\n await next();\n };\n};\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './parsers/serverkit.parser.js';\nimport { ServerKitContext } from './serverkit.context.js';\nimport { unique } from '@maroonedsoftware/utilities';\nimport { httpError } from '@maroonedsoftware/errors';\n\n/**\n * DI-injectable map of MIME subtypes to {@link ServerKitParser} instances.\n *\n * Register parser instances against their MIME subtypes, then bind this map\n * in the InjectKit container so {@link ServerKitBodyParser} can resolve them.\n *\n * @example\n * ```typescript\n * registry\n * .register(ServerKitParserMappings)\n * .useMap()\n * .add('json', JsonParser)\n * .add('urlencoded', FormParser);\n * ```\n */\n@Injectable()\nexport class ServerKitParserMappings extends Map<string, ServerKitParser> {}\n\n/**\n * Selects and invokes the appropriate {@link ServerKitParser} for the incoming request\n * based on its `Content-Type` header.\n *\n * The set of supported MIME types is derived from the keys of the injected\n * {@link ServerKitParserMappings}. Duplicate keys are deduplicated automatically.\n *\n * @throws HTTP 415 if the request's `Content-Type` does not match any registered parser.\n *\n * @see {@link defaultParserMappings} – convenience map for the standard parsers\n * @see {@link bodyParserMiddleware} – the middleware that invokes this class\n */\n@Injectable()\nexport class ServerKitBodyParser {\n private readonly mimeTypes: string[];\n constructor(private readonly parsers: ServerKitParserMappings) {\n this.mimeTypes = unique(Array.from(this.parsers.keys()));\n }\n\n /**\n * Matches the request's `Content-Type` to a registered parser and delegates parsing.\n *\n * @param ctx - The current {@link ServerKitContext}; used to inspect `Content-Type` and access `ctx.req`.\n * @returns The {@link ServerKitParserResult} from the matched parser.\n * @throws HTTP 415 if no parser is registered for the request's content type.\n */\n async parse(ctx: ServerKitContext): Promise<ServerKitParserResult> {\n const mimeType = ctx.request.is(this.mimeTypes);\n if (!mimeType) {\n throw httpError(415).withDetails({ body: 'Unsupported media type' });\n }\n const parser = this.parsers.get(mimeType);\n if (!parser) {\n throw httpError(415).withDetails({ body: 'Unsupported media type' });\n }\n return parser.parse(ctx.req);\n }\n}\n","import { invalidAuthenticationSession } from '@maroonedsoftware/authentication';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { unauthorizedError } from '@maroonedsoftware/errors';\n\n/**\n * Options for {@link requireSecurity}.\n *\n * Enforces that an authentication session is present and optionally that\n * multi-factor authentication has been completed.\n */\ntype SecurityOptions = {\n /** Whether to require multi-factor authentication. */\n requireMfa: boolean;\n};\n\n/**\n * Router middleware that enforces a valid authentication session and, by\n * default, multi-factor authentication.\n *\n * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and:\n *\n * - Throws HTTP 401 with `WWW-Authenticate: Bearer error=\"invalid_token\"`\n * when the session is `invalidAuthenticationSession`.\n * - When `requireMfa` is true (the default), throws HTTP 401 with\n * `WWW-Authenticate: Bearer error=\"mfa_required\"` if the session has fewer\n * than two factors or every factor is of `kind: 'knowledge'` (i.e. no\n * `possession` or `biometric` factor was satisfied).\n * - Otherwise calls `next()`.\n *\n * @param options - Security requirements for the route. Defaults to\n * `{ requireMfa: true }`.\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n * @throws {HttpError} 401 when the session is invalid or MFA is required but\n * not satisfied.\n *\n * @example\n * ```typescript\n * // Require an authenticated user with MFA\n * router.get('/profile', requireSecurity(), handler);\n *\n * // Require authentication only (e.g. for a step-up MFA enrollment route)\n * router.post('/mfa/enroll', requireSecurity({ requireMfa: false }), handler);\n * ```\n */\nexport const requireSecurity = (options: SecurityOptions = { requireMfa: true }): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n const authenticationSession = ctx.authenticationSession;\n\n if (authenticationSession === invalidAuthenticationSession) {\n throw unauthorizedError('Bearer error=\"invalid_token\"');\n }\n\n if (\n options.requireMfa &&\n (authenticationSession.factors.length < 2 || authenticationSession.factors.every(factor => factor.kind === 'knowledge'))\n ) {\n throw unauthorizedError('Bearer error=\"mfa_required\"');\n }\n\n await next();\n };\n};\n","import { createHmac, BinaryToTextEncoding } from 'node:crypto';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\nimport { AppConfig } from '@maroonedsoftware/appconfig';\n\n/**\n * Configuration for {@link requireSignature}.\n *\n * Stored in `AppConfig` and retrieved by key at request time, so the values\n * can be loaded from any AppConfig source (JSON, `.env`, GCP secrets, etc.).\n */\nexport type SignatureOptions = {\n /** Name of the request header that carries the HMAC signature (e.g. `'X-Signature'`). */\n header: string;\n /** Secret key used to compute the HMAC. */\n secret: string;\n /** HMAC algorithm passed to `crypto.createHmac` (e.g. `'sha256'`, `'sha512'`). */\n algorithm: string;\n /** Output encoding for `hmac.digest()` (e.g. `'hex'`, `'base64'`). */\n digest: BinaryToTextEncoding;\n};\n\n/**\n * Router middleware that verifies a request signature against an HMAC of `ctx.rawBody`.\n *\n * Reads {@link SignatureOptions} from `AppConfig` using `optionsKey`, then:\n * - Computes `HMAC(algorithm, secret).update(ctx.rawBody).digest(digest)`\n * - Reads the expected signature from the request header named `options.header`\n * - Throws HTTP 401 (with internal diagnostics) if the signatures do not match\n * - Calls `next()` otherwise\n *\n * Requires `ctx.rawBody` to be populated before this middleware runs — use\n * {@link bodyParserMiddleware} upstream to ensure the raw bytes are captured.\n *\n * @param optionsKey - Key used to retrieve {@link SignatureOptions} from `AppConfig` via `getAs`.\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n *\n * @example\n * ```typescript\n * // config.json\n * // { \"webhook\": { \"header\": \"X-Hub-Signature-256\", \"secret\": \"${env:WEBHOOK_SECRET}\", \"algorithm\": \"sha256\", \"digest\": \"hex\" } }\n *\n * router.post('/webhooks/github', requireSignature('webhook'), handler);\n * ```\n */\nexport const requireSignature = (optionsKey: string): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n const options = ctx.container.get(AppConfig).getAs<SignatureOptions>(optionsKey);\n\n const { header, secret, algorithm, digest } = options;\n\n const hmac = createHmac(algorithm, secret).update(ctx.rawBody);\n\n const signature = ctx.get(header);\n const computedSignature = hmac.digest(digest);\n if (computedSignature !== signature) {\n throw httpError(401).withInternalDetails({\n message: 'Invalid signature',\n header,\n computedSignature,\n signature,\n algorithm,\n digest,\n });\n }\n\n await next();\n };\n};\n","import { BinaryLike } from 'node:crypto';\nimport { IncomingMessage } from 'http';\nimport { Injectable } from 'injectkit';\n\n/**\n * The result returned by every {@link ServerKitParser}.\n *\n * @property parsed - The structured/deserialized value derived from the body (e.g. a plain object for JSON).\n * @property raw - The unprocessed body bytes as read from the stream. Parsers that do not retain a raw\n * representation (e.g. binary, multipart) return an empty `Buffer`.\n */\nexport type ServerKitParserResult = {\n parsed: unknown;\n raw: BinaryLike;\n};\n\n/**\n * Abstract base class for all ServerKit body parsers.\n *\n * Implementations read from an {@link IncomingMessage} stream and return a\n * {@link ServerKitParserResult} containing both the parsed value and the raw body.\n * Each parser is registered in the DI container and selected by MIME type via\n * {@link ServerKitBodyParser}.\n *\n * @see {@link ServerKitBodyParser} – dispatcher that selects the right parser by MIME type\n * @see {@link defaultParserMappings} – built-in MIME-type-to-parser map\n */\n@Injectable()\nexport abstract class ServerKitParser {\n /**\n * Reads and parses the body from the given request stream.\n *\n * @param req - The incoming HTTP request whose body should be consumed.\n * @returns A promise resolving to a {@link ServerKitParserResult}.\n */\n abstract parse(req: IncomingMessage): Promise<ServerKitParserResult>;\n}\n","import { parse, Reviver } from '@hapi/bourne';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\nimport { httpError } from '@maroonedsoftware/errors';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { Injectable } from 'injectkit';\n\n/**\n * Configuration options for {@link JsonParser}.\n *\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property strict - When `true` (default), only JSON objects `{}` and arrays `[]` are accepted.\n * When `false`, any valid JSON value (string, number, etc.) is allowed.\n * @property protoAction - How `@hapi/bourne` handles `__proto__` keys. Defaults to `'error'`.\n * @property reviver - Optional JSON reviver function passed to `@hapi/bourne`.\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'1mb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n */\n@Injectable()\nexport class JsonParserOptions implements raw.Options {\n strict?: boolean;\n protoAction?: 'error' | 'remove' | 'ignore';\n reviver?: Reviver;\n encoding?: string;\n limit?: string;\n length?: number;\n}\n\n// Allowed whitespace is defined in RFC 7159\n// http://www.rfc-editor.org/rfc/rfc7159.txt\n/* eslint-disable-next-line no-control-regex */\nconst strictJSONReg = /^[\\x20\\x09\\x0a\\x0d]*(\\[|\\{)/;\n\n/**\n * Parses a JSON request body using `@hapi/bourne` for prototype-pollution protection.\n *\n * In strict mode (default), only top-level objects `{}` and arrays `[]` are accepted;\n * any other value throws HTTP 400. In non-strict mode, any valid JSON value is accepted.\n * An empty body always resolves to `{ parsed: undefined }`.\n *\n * @throws HTTP 400 if the body is not valid JSON or fails the strict-mode check.\n *\n * @example\n * ```typescript\n * // Default strict mode (injectable)\n * const parser = new JsonParser(new JsonParserOptions());\n *\n * // Custom options\n * const lenient = new JsonParser({ strict: false, protoAction: 'remove' });\n * ```\n */\n@Injectable()\nexport class JsonParser extends ServerKitParser {\n constructor(private readonly options: JsonParserOptions) {\n super();\n }\n\n /**\n * Reads, decompresses, and JSON-parses the request body.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <object|array|undefined>, raw: <original string> }`.\n * @throws HTTP 400 on malformed JSON or strict-mode violation.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '1mb';\n\n const strict = this.options.strict ?? true;\n const protoAction = this.options.protoAction ?? 'error';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n const doParse = (str: string) => {\n try {\n if (this.options.reviver) {\n return parse(str, this.options.reviver, { protoAction });\n }\n return parse(str, { protoAction });\n } catch (err) {\n throw httpError(400).withCause(err as Error);\n }\n };\n\n if (!strict) {\n return str ? { parsed: doParse(str), raw: str } : { parsed: undefined, raw: str };\n } else if (!str) {\n return { parsed: undefined, raw: str };\n } else if (!strictJSONReg.test(str)) {\n throw httpError(400).withDetails({ body: 'Invalid JSON, only supports object and array' });\n }\n return { parsed: doParse(str), raw: str };\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Configuration options for {@link TextParser}.\n *\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'1mb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n */\nexport class TextParserOptions implements raw.Options {\n encoding?: string;\n limit?: string;\n length?: number;\n}\n\n/**\n * Reads the request body as a plain string.\n *\n * No structural parsing is performed; the raw text is returned as both `parsed` and `raw`.\n * Suitable for `text/plain` and similar content types. Decompresses the stream via `inflation`\n * before buffering.\n *\n * @example\n * ```typescript\n * const parser = new TextParser(new TextParserOptions());\n * const { parsed } = await parser.parse(req); // parsed is a string\n * ```\n */\n@Injectable()\nexport class TextParser extends ServerKitParser {\n constructor(private readonly options: TextParserOptions) {\n super();\n }\n\n /**\n * Reads and decompresses the request body into a string.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <string>, raw: <same string> }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '1mb';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n return { parsed: str, raw: str };\n }\n}\n","import { httpError } from '@maroonedsoftware/errors';\nimport { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport { parse, IParseOptions } from 'qs';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Configuration options for {@link FormParser}.\n *\n * Combines `raw-body` read options with `qs` parse options.\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'56kb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n * @property allowDots - When `true`, `qs` interprets dot notation (`user.name`) as nested objects.\n * @property depth - Maximum nesting depth for parsed objects (default: `qs` default of `5`).\n * @property parameterLimit - Maximum number of parameters to parse (default: `qs` default of `1000`).\n */\n@Injectable()\nexport class FormParserOptions implements raw.Options, IParseOptions {\n encoding?: string;\n limit?: string;\n length?: number;\n allowDots?: boolean;\n depth?: number;\n parameterLimit?: number;\n}\n\n/**\n * Parses a URL-encoded (`application/x-www-form-urlencoded`) request body using `qs`.\n *\n * Supports nested objects via bracket notation (`user[name]=alice`) by default.\n * Dot notation (`user.name=alice`) requires `allowDots: true` in the options.\n * An empty body resolves to `{ parsed: {} }`.\n *\n * @throws HTTP 400 if `qs.parse` throws unexpectedly.\n *\n * @example\n * ```typescript\n * // Default options (injectable)\n * const parser = new FormParser(new FormParserOptions());\n *\n * // Enable dot notation\n * const parser = new FormParser({ allowDots: true });\n * ```\n */\n@Injectable()\nexport class FormParser extends ServerKitParser {\n constructor(private readonly options: FormParserOptions) {\n super();\n }\n\n /**\n * Reads, decompresses, and URL-decodes the request body.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <object>, raw: <original url-encoded string> }`.\n * @throws HTTP 400 if parsing fails.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '56kb';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n try {\n return { parsed: parse(str, this.options), raw: str };\n } catch (err) {\n throw httpError(400).withCause(err as Error);\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport { MultipartBody } from '@maroonedsoftware/multipart';\n\n/**\n * Wraps the request stream in a {@link MultipartBody} for lazy multipart/form-data parsing.\n *\n * The body is **not** eagerly consumed; fields and files are read on-demand through the\n * `MultipartBody` API. `raw` is always `undefined` because the stream cannot be replayed\n * once consumed.\n */\n@Injectable()\nexport class MultipartParser extends ServerKitParser {\n /**\n * Creates a {@link MultipartBody} around the request stream.\n *\n * @param req - Incoming HTTP request containing the multipart body.\n * @returns `{ parsed: MultipartBody, raw: Buffer(0) }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: new MultipartBody(req), raw: Buffer.from('') };\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Reads the request body as a raw `Buffer` without any text decoding or structural parsing.\n *\n * Useful for binary payloads (e.g. PDFs, images, protobuf) where the caller needs the\n * untransformed bytes. Decompresses the stream via `inflation` before buffering.\n *\n * `raw` is always `undefined` because the `Buffer` itself is both the parsed and raw form.\n */\n@Injectable()\nexport class BinaryParser extends ServerKitParser {\n /**\n * Buffers the (optionally compressed) request body into a `Buffer`.\n *\n * @param req - Incoming HTTP request to read.\n * @returns `{ parsed: Buffer, raw: Buffer(0) }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: await raw(inflate(req)), raw: Buffer.from('') };\n }\n}\n","import { Identifier } from 'injectkit';\nimport { FormParser } from './form.parser.js';\nimport { JsonParser } from './json.parser.js';\nimport { MultipartParser } from './multipart.parser.js';\nimport { ServerKitParser } from './serverkit.parser.js';\nimport { TextParser } from './text.parser.js';\n\n/**\n * Built-in MIME-subtype-to-parser mappings used by {@link bodyParserMiddleware}.\n *\n * Each key is a MIME subtype (matched against `Content-Type` via Koa's `ctx.request.is()`)\n * and the value is the InjectKit {@link Identifier} for the corresponding {@link ServerKitParser}.\n *\n * | MIME subtype | Parser |\n * | --------------------- | ----------------- |\n * | `json` | {@link JsonParser} |\n * | `application/*+json` | {@link JsonParser} |\n * | `urlencoded` | {@link FormParser} |\n * | `text` | {@link TextParser} |\n * | `multipart` | {@link MultipartParser} |\n *\n * Extend by spreading into a new object and registering the result in the DI container:\n * ```typescript\n * const myMappings = { ...defaultParserMappings, pdf: BinaryParser };\n * ```\n */\nexport const defaultParserMappings: Record<string, Identifier<ServerKitParser>> = {\n json: JsonParser,\n 'application/*+json': JsonParser,\n urlencoded: FormParser,\n text: TextParser,\n multipart: MultipartParser,\n} as const;\n"],"mappings":";;;;AACA,SAAoBA,kBAAkB;;;;;;;;AA2C/B,IAAeC,mBAAf,MAAeA;SAAAA;;;AAA8C;;;;;;AC3CpE,OAAOC,YAA+B;AAY/B,IAAMC,kBAAkB,wBAAqDC,YAA4B,IAAIC,OAAyBD,OAAAA,GAA9G;;;ACb/B,OAAOE,UAAU;AAoBV,IAAMC,iBAAiB,wBAACC,YAAAA;AAE7B,QAAMC,gBAAgB,wBAACC,QAAAA;AACrB,UAAMC,SAASD,IAAIE,IAAI,QAAA;AACvB,UAAMC,WAAWL,SAASG,UAAU;MAAC;;AACrC,eAAWG,WAAWD,UAAU;AAC9B,UAAIC,YAAY,KAAK;AACnB,eAAOH;MACT;AAEA,UAAI,OAAOG,YAAY,UAAU;AAC/B,YAAIA,YAAYH,QAAQ;AACtB,iBAAOA;QACT;AACA;MACF;AAEA,UAAIG,QAAQC,KAAKJ,MAAAA,GAAS;AACxB,eAAOA;MACT;IACF;AAGA,WAAO;EACT,GAtBsB;AAwBtB,SAAOK,KAAK;IACV,GAAGR;IACHG,QAAQF;IACRQ,cAAcT,SAASS,gBAAgB;IACvCC,eAAeV,SAASU,iBAAiB;I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AO;QAAEgB,QAAQT,OAAMM,KAAK,KAAKP,OAAO;QAAGQ,KAAKD;MAAI;IACtD,SAASI,KAAK;AACZ,YAAMC,WAAU,GAAA,EAAKC,UAAUF,GAAAA;IACjC;EACF;AACF;;;;;;;;;;AC7EA,SAASG,cAAAA,mBAAkB;AAG3B,SAASC,qBAAqB;;;;;;;;AAUvB,IAAMC,kBAAN,cAA8BC,gBAAAA;SAAAA;;;;;;;;;EAOnC,MAAMC,MAAMC,KAAsD;AAChE,WAAO;MAAEC,QAAQ,IAAIC,cAAcF,GAAAA;MAAMG,KAAKC,OAAOC,KAAK,EAAA;IAAI;EAChE;AACF;;;;;;ACvBA,SAASC,cAAAA,mBAAkB;AAG3B,OAAOC,UAAS;AAChB,OAAOC,cAAa;;;;;;;;AAWb,IAAMC,eAAN,cAA2BC,gBAAAA;SAAAA;;;;;;;;;EAOhC,MAAMC,MAAMC,KAAsD;AAChE,WAAO;MAAEC,QAAQ,MAAMC,KAAIC,SAAQH,GAAAA,CAAAA;MAAOE,KAAKE,OAAOC,KAAK,EAAA;IAAI;EACjE;AACF;;;;;;ACCO,IAAMC,wBAAqE;EAChFC,MAAMC;EACN,sBAAsBA;EACtBC,YAAYC;EACZC,MAAMC;EACNC,WAAWC;AACb;","names":["Injectable","ServerKitContext","Router","ServerKitRouter","options","Router","cors","corsMiddleware","options","originMatcher","ctx","origin","get","matchers","matcher","test","cors","allowMethods","secureContext","keepHeadersOnError","privateNetworkAccess","IsHttpError","IsServerkitError","errorMiddleware","ctx","next","status","body","statusCode","message","details","url","URL","toString","app","emit","error","IsHttpError","headers","entry","Object","entries","set","IsServerkitError","RateLimiterRes","httpError","isRateLimiterError","error","RateLimiterRes","rateLimiterMiddleware","rateLimiter","ctx","next","consume","ip","headers","msBeforeNext","toString","points","remainingPoints","Math","ceil","Date","now","httpError","withCause","withHeaders","crypto","Logger","serverKitContextMiddleware","container","ctx","next","scopedContainer","createScopedContainer","override","ServerKitContext","logger","get","Logger","loggerName","path","userAgent","ipAddress","ip","correlationId","headers","Array","isArray","crypto","randomUUID","requestId","set","AuthenticationSchemeHandler","invalidAuthenticationSession","authenticationMiddleware","ctx","next","authenticationSession","invalidAuthenticationSession","authorizationHeader","req","headers","authorization","schemeHandler","container","get","AuthenticationSchemeHandler","handle","httpError","IsHttpError","Injectable","unique","httpError","ServerKitParserMappings","Map","ServerKitBodyParser","mimeTypes","parsers","unique","Array","from","keys","parse","ctx","mimeType","request","is","httpError","withDetails","body","parser","get","req","bodyParserMiddleware","contentTypes","ctx","next","length","request","httpError","withDetails","body","is","join","value","type","parser","container","get","ServerKitBodyParser","result","parse","parsed","rawBody","raw","error","IsHttpError","withCause","invalidAuthenticationSession","unauthorizedError","requireSecurity","options","requireMfa","ctx","next","authenticationSession","invalidAuthenticationSession","unauthorizedError","factors","length","every","factor","kind","createHmac","httpError","AppConfig","requireSignature","optionsKey","ctx","next","options","container","get","AppConfig","getAs","header","secret","algorithm","digest","hmac","createHmac","update","rawBody","signature","computedSignature","httpError","withInternalDetails","message","Injectable","ServerKitParser","parse","raw","inflate","httpError","Injectable","JsonParserOptions","strict","protoAction","reviver","encoding","limit","length","strictJSONReg","JsonParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","doParse","err","httpError","withCause","parsed","test","withDetails","body","Injectable","raw","inflate","TextParserOptions","encoding","limit","length","TextParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","parsed","httpError","Injectable","parse","raw","inflate","FormParserOptions","encoding","limit","length","allowDots","depth","parameterLimit","FormParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","parsed","err","httpError","withCause","Injectable","MultipartBody","MultipartParser","ServerKitParser","parse","req","parsed","MultipartBody","raw","Buffer","from","Injectable","raw","inflate","BinaryParser","ServerKitParser","parse","req","parsed","raw","inflate","Buffer","from","defaultParserMappings","json","JsonParser","urlencoded","FormParser","text","TextParser","multipart","MultipartParser"]}
1
+ {"version":3,"sources":["../src/serverkit.context.ts","../src/serverkit.router.ts","../src/middleware/server/cors.middleware.ts","../src/middleware/server/error.middleware.ts","../src/middleware/server/rate.limiter.middleware.ts","../src/middleware/server/serverkit.context.middleware.ts","../src/middleware/server/authentication.middleware.ts","../src/middleware/router/body.parser.middleware.ts","../src/serverkit.bodyparser.ts","../src/middleware/router/require.policy.middleware.ts","../src/middleware/router/require.signature.middleware.ts","../src/parsers/serverkit.parser.ts","../src/parsers/json.parser.ts","../src/parsers/text.parser.ts","../src/parsers/form.parser.ts","../src/parsers/multipart.parser.ts","../src/parsers/binary.parser.ts","../src/parsers/serverkit.default.parsers.ts"],"sourcesContent":["import { Context } from 'koa';\nimport { Container, Injectable } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { AuthenticationSession } from '@maroonedsoftware/authentication';\nimport { BinaryLike } from 'node:crypto';\n\n/**\n * Koa context extended with ServerKit request-scoped services and metadata.\n * Populated by {@link serverKitContextMiddleware}.\n * Use this as the context type for route handlers to get full typing of `ctx.container`, `ctx.logger`, and request IDs.\n *\n * @extends Context\n * @see {@link serverKitContextMiddleware} – middleware that populates this context on each request\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport interface ServerKitContext extends Context {\n /** Scoped injectkit container for this request; use for request-scoped DI. */\n container: Container;\n /** Request-scoped logger instance. */\n logger: Logger;\n /** Logger name for this request (e.g. request path or route identifier). */\n loggerName: string;\n /** Value of the `User-Agent` request header, or empty string if absent. */\n userAgent: string;\n /** IP address of the client. */\n ipAddress: string;\n /** Correlation ID for tracing; from `X-Correlation-Id` header or generated. */\n correlationId: string;\n /** Request ID; from `X-Request-Id` header or generated. */\n requestId: string;\n /** Raw body for this request. */\n rawBody: BinaryLike;\n /** Authentication session. */\n authenticationSession: AuthenticationSession;\n}\n\n/**\n * Abstract class merged with the {@link ServerKitContext} interface so it can serve as an\n * injectkit injection token. {@link serverKitContextMiddleware} registers the live `ctx`\n * against this token in the request-scoped container, allowing services to declare\n * `ServerKitContext` as a constructor dependency and receive the current Koa context.\n */\n@Injectable()\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nexport abstract class ServerKitContext implements ServerKitContext {}\n","import { DefaultState } from 'koa';\nimport Router, { RouterOptions } from '@koa/router';\nimport { ServerKitContext } from './serverkit.context.js';\n\n/**\n * Creates a new Koa router typed for ServerKit state and context.\n * Use with {@link ServerKitContext} for full typing of `ctx` in route handlers.\n *\n * @typeParam StateT - Koa state type (defaults to `DefaultState`).\n * @typeParam ContextT - Context type (defaults to `ServerKitContext`).\n * @param options - Router options (defaults to `undefined`).\n * @returns A new {@link Router} instance with the given options.\n */\nexport const ServerKitRouter = <StateT = DefaultState, ContextT = ServerKitContext>(options?: RouterOptions) => new Router<StateT, ContextT>(options);\n","import cors from '@koa/cors';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { Context } from 'koa';\n\n/**\n * CORS options for {@link corsMiddleware}.\n * Extends `@koa/cors` options with an `origin` that may be a string or array of strings/RegExps.\n */\nexport interface CorsOptions extends Omit<cors.Options, 'origin'> {\n /** Allowed origin(s): `'*'`, a single origin string, or an array of strings/RegExps to match. */\n origin?: string | (string | RegExp)[];\n}\n\n/**\n * Adds CORS headers to responses using `@koa/cors` with ServerKit-compatible origin matching.\n * Supports `'*'`, exact string origins, and RegExp patterns.\n *\n * @param options - Optional {@link CorsOptions}; defaults to `GET,HEAD,PUT,POST,DELETE,PATCH` methods.\n * @returns {@link ServerKitMiddleware} that applies CORS headers.\n */\nexport const corsMiddleware = (options?: CorsOptions): ServerKitMiddleware => {\n // return the request origin as its own matcher to support RegExp\n const originMatcher = (ctx: Context): string => {\n const origin = ctx.get('origin');\n const matchers = options?.origin ?? ['*'];\n for (const matcher of matchers) {\n if (matcher === '*') {\n return origin;\n }\n\n if (typeof matcher === 'string') {\n if (matcher === origin) {\n return origin;\n }\n continue;\n }\n\n if (matcher.test(origin)) {\n return origin;\n }\n }\n\n // return the zero value to prevent matches\n return '';\n };\n\n return cors({\n ...options,\n origin: originMatcher,\n allowMethods: options?.allowMethods ?? 'GET,HEAD,PUT,POST,DELETE,PATCH',\n secureContext: options?.secureContext ?? false,\n keepHeadersOnError: options?.keepHeadersOnError ?? false,\n privateNetworkAccess: options?.privateNetworkAccess ?? false,\n });\n};\n","import { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { IsHttpError, IsServerkitError } from '@maroonedsoftware/errors';\n\n/**\n * Central error handler: catches thrown errors, sets status/body from HTTP errors,\n * returns 404 for unmatched routes, and 500 for unknown errors.\n * Emits `error` or `warn` on the app for logging.\n *\n * @returns {@link ServerKitMiddleware} that wraps the stack in try/catch and normalizes responses.\n */\nexport const errorMiddleware = (): ServerKitMiddleware => {\n return async (ctx, next) => {\n try {\n await next();\n if (ctx.status === 404 && !ctx.body) {\n const body = {\n statusCode: 404,\n message: 'Not Found',\n details: { url: ctx.URL.toString() },\n };\n ctx.status = 404;\n ctx.body = body;\n ctx.app.emit('warn', body, ctx);\n }\n } catch (error) {\n if (IsHttpError(error)) {\n ctx.status = error.statusCode;\n ctx.body = {\n statusCode: error.statusCode,\n message: error.message,\n details: error.details,\n };\n if (error.headers) {\n for (const entry of Object.entries(error.headers)) {\n ctx.set(entry[0], entry[1]);\n }\n }\n } else if (IsServerkitError(error)) {\n ctx.status = 500;\n ctx.body = {\n statusCode: 500,\n message: error.message,\n details: error.details,\n };\n } else {\n ctx.status = 500;\n ctx.body = {\n statusCode: 500,\n message: 'Internal Server Error',\n };\n }\n\n ctx.app.emit('error', error, ctx);\n }\n };\n};\n","import { RateLimiterAbstract, RateLimiterRes } from 'rate-limiter-flexible';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\n\n/** Type guard that narrows `error` to a `RateLimiterRes` (i.e. a rate-limit exceeded response). */\nconst isRateLimiterError = (error: unknown): error is RateLimiterRes => {\n return error instanceof RateLimiterRes || ('msBeforeNext' in (error as object) && 'remainingPoints' in (error as object));\n};\n\n/**\n * Enforces rate limiting per client IP using a `rate-limiter-flexible` instance.\n * Consumes one token per request; throws HTTP 429 when the limit is exceeded.\n *\n * @param rateLimiter - A {@link RateLimiterAbstract} instance (e.g. `RateLimiterMemory`, `RateLimiterRedis`).\n * @returns {@link ServerKitMiddleware} that consumes a token and continues or throws 429.\n */\nexport const rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract): ServerKitMiddleware => {\n return async (ctx, next) => {\n try {\n await rateLimiter.consume(ctx.ip);\n } catch (error: unknown) {\n let headers: Record<string, string> = {};\n if (isRateLimiterError(error)) {\n headers = {\n 'retry-after': (error.msBeforeNext / 1000).toString(),\n 'x-ratelimit-limit': rateLimiter.points.toString(),\n 'x-ratelimit-remaining': error.remainingPoints.toString(),\n 'x-ratelimit-reset': Math.ceil((Date.now() + error.msBeforeNext) / 1000).toString(),\n };\n }\n\n throw httpError(429)\n .withCause(error as Error)\n .withHeaders(headers);\n }\n\n await next();\n };\n};\n","import crypto from 'crypto';\nimport { Container } from 'injectkit';\nimport { Logger } from '@maroonedsoftware/logger';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { ServerKitContext } from '../../serverkit.context.js';\n\n/**\n * Populates {@link ServerKitContext} for each request: scoped container, logger,\n * logger name, user-agent, correlation ID, and request ID.\n * Reads or generates `X-Correlation-Id` and `X-Request-Id` and sets response headers.\n * Registers the live `ctx` against the {@link ServerKitContext} injection token in the\n * request-scoped container so downstream services can inject the current context.\n * Should be applied early so downstream middleware and routes can use `ctx.container` and `ctx.logger`.\n *\n * @param container - Root injectkit {@link Container} used to create a scoped container and resolve {@link Logger}.\n * @returns {@link ServerKitMiddleware} that attaches ServerKit context to `ctx`.\n */\nexport const serverKitContextMiddleware = (container: Container): ServerKitMiddleware => {\n return async (ctx, next) => {\n const scopedContainer = container.createScopedContainer();\n ctx.container = scopedContainer;\n\n scopedContainer.override(ServerKitContext, ctx);\n\n ctx.logger = ctx.container.get(Logger);\n ctx.loggerName = ctx.path;\n\n ctx.userAgent = ctx.get('user-agent');\n ctx.ipAddress = ctx.ip;\n\n const correlationId = ctx.headers['x-correlation-id'];\n ctx.correlationId = Array.isArray(correlationId) ? (correlationId[0] ?? crypto.randomUUID()) : (correlationId ?? crypto.randomUUID());\n\n ctx.requestId = crypto.randomUUID();\n\n ctx.headers['x-correlation-id'] = ctx.correlationId;\n ctx.set('x-correlation-id', ctx.correlationId);\n\n ctx.headers['x-request-id'] = ctx.requestId;\n ctx.set('x-request-id', ctx.requestId);\n\n await next();\n };\n};\n","import { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { AuthenticationSchemeHandler, invalidAuthenticationSession } from '@maroonedsoftware/authentication';\n\n/**\n * Resolves the `Authorization` request header into an {@link AuthenticationSession}\n * and attaches it to `ctx.authenticationSession`.\n *\n * The header is immediately removed from `ctx.req.headers` after being read so it\n * cannot be accidentally captured by downstream logging or serialization.\n *\n * Resolution is delegated to the {@link AuthenticationSchemeHandler} registered in\n * the DI container. `ctx.authenticationSession` is initialised to\n * {@link invalidAuthenticationSession} before delegation, ensuring that any error\n * thrown by the scheme handler leaves the context in a safe, unauthenticated state.\n *\n * @returns A {@link ServerKitMiddleware} that populates `ctx.authenticationSession`.\n *\n * @example\n * ```typescript\n * app.use(authenticationMiddleware());\n * ```\n */\nexport const authenticationMiddleware = (): ServerKitMiddleware => {\n return async (ctx, next) => {\n ctx.authenticationSession = invalidAuthenticationSession; // bad initial state so it will fail verification\n\n // NOTE: we delete the auth headers on the request here to ensure we don't accidentally log it\n const authorizationHeader = ctx.req.headers.authorization;\n delete ctx.req.headers.authorization;\n\n const schemeHandler = ctx.container.get(AuthenticationSchemeHandler);\n\n ctx.authenticationSession = await schemeHandler.handle(authorizationHeader);\n\n await next();\n };\n};\n","import { httpError, IsHttpError } from '@maroonedsoftware/errors';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { ServerKitBodyParser } from '../../serverkit.bodyparser.js';\n\n/**\n * Parses the request body based on `Content-Type` and assigns it to `ctx.body`.\n * Rejects requests with unexpected or unsupported content types.\n *\n * Supported types: JSON, URL-encoded form, text, multipart, PDF (raw buffer).\n * Requires a body when `contentTypes` is non-empty; otherwise rejects bodies.\n *\n * @param contentTypes - Allowed MIME types (e.g. `['application/json', 'application/x-www-form-urlencoded']`).\n * Use an empty array to disallow any request body.\n * @returns {@link ServerKitRouterMiddleware} that parses the body and sets `ctx.body`.\n * @throws HTTP 400 if body is present when no content types are allowed.\n * @throws HTTP 411 if body is required but missing.\n * @throws HTTP 415 if `Content-Type` is not in `contentTypes`.\n * @throws HTTP 422 if body is invalid or media type is unsupported.\n */\nexport const bodyParserMiddleware = (contentTypes: string[]): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n if (contentTypes.length === 0) {\n if (ctx.request.length > 0) {\n throw httpError(400).withDetails({ body: 'Unexpected body' });\n }\n } else {\n if (ctx.request.length > 0) {\n if (!ctx.request.is(contentTypes)) {\n throw httpError(415).withDetails({\n 'content-type': `must be ${contentTypes.length > 1 ? 'one of ' : ''}${contentTypes.join(', ')}`,\n value: ctx.request.type,\n });\n }\n\n try {\n const parser = ctx.container.get(ServerKitBodyParser);\n const result = await parser.parse(ctx);\n ctx.body = result.parsed;\n ctx.rawBody = result.raw;\n } catch (error) {\n if (IsHttpError(error)) {\n throw error;\n }\n throw httpError(422)\n .withCause(error as Error)\n .withDetails({ body: 'Invalid request body format' });\n }\n } else {\n throw httpError(411);\n }\n }\n await next();\n };\n};\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './parsers/serverkit.parser.js';\nimport { ServerKitContext } from './serverkit.context.js';\nimport { unique } from '@maroonedsoftware/utilities';\nimport { httpError } from '@maroonedsoftware/errors';\n\n/**\n * DI-injectable map of MIME subtypes to {@link ServerKitParser} instances.\n *\n * Register parser instances against their MIME subtypes, then bind this map\n * in the InjectKit container so {@link ServerKitBodyParser} can resolve them.\n *\n * @example\n * ```typescript\n * registry\n * .register(ServerKitParserMappings)\n * .useMap()\n * .add('json', JsonParser)\n * .add('urlencoded', FormParser);\n * ```\n */\n@Injectable()\nexport class ServerKitParserMappings extends Map<string, ServerKitParser> {}\n\n/**\n * Selects and invokes the appropriate {@link ServerKitParser} for the incoming request\n * based on its `Content-Type` header.\n *\n * The set of supported MIME types is derived from the keys of the injected\n * {@link ServerKitParserMappings}. Duplicate keys are deduplicated automatically.\n *\n * @throws HTTP 415 if the request's `Content-Type` does not match any registered parser.\n *\n * @see {@link defaultParserMappings} – convenience map for the standard parsers\n * @see {@link bodyParserMiddleware} – the middleware that invokes this class\n */\n@Injectable()\nexport class ServerKitBodyParser {\n private readonly mimeTypes: string[];\n constructor(private readonly parsers: ServerKitParserMappings) {\n this.mimeTypes = unique(Array.from(this.parsers.keys()));\n }\n\n /**\n * Matches the request's `Content-Type` to a registered parser and delegates parsing.\n *\n * @param ctx - The current {@link ServerKitContext}; used to inspect `Content-Type` and access `ctx.req`.\n * @returns The {@link ServerKitParserResult} from the matched parser.\n * @throws HTTP 415 if no parser is registered for the request's content type.\n */\n async parse(ctx: ServerKitContext): Promise<ServerKitParserResult> {\n const mimeType = ctx.request.is(this.mimeTypes);\n if (!mimeType) {\n throw httpError(415).withDetails({ body: 'Unsupported media type' });\n }\n const parser = this.parsers.get(mimeType);\n if (!parser) {\n throw httpError(415).withDetails({ body: 'Unsupported media type' });\n }\n return parser.parse(ctx.req);\n }\n}\n","import { invalidAuthenticationSession } from '@maroonedsoftware/authentication';\nimport { PolicyService } from '@maroonedsoftware/policies';\nimport { unauthorizedError } from '@maroonedsoftware/errors';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\n\n/**\n * Options for {@link requirePolicy}.\n */\nexport interface RequirePolicyOptions {\n /**\n * Policy name to evaluate against `{ session: ctx.authenticationSession }`\n * via {@link PolicyService.assert}. The policy is resolved from\n * `ctx.container` per request, so applications can swap the underlying rule\n * by registering their own policy class against the same name in\n * `PolicyRegistryMap`.\n *\n * Defaults to `'auth.session.mfa.satisfied'`. Pass `false` to validate the\n * session only (skip the policy check entirely).\n */\n policy?: string | false;\n}\n\nconst DEFAULT_POLICY = 'auth.session.mfa.satisfied' as const;\n\n/**\n * Router middleware that enforces a valid authentication session and, by\n * default, the `'auth.session.mfa.satisfied'` policy.\n *\n * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and:\n *\n * - Throws HTTP 401 with `WWW-Authenticate: Bearer error=\"invalid_token\"`\n * when the session is `invalidAuthenticationSession`.\n * - When `options.policy` is set (or omitted — the default is\n * `'auth.session.mfa.satisfied'`), resolves the `PolicyService` from\n * `ctx.container` and calls `assert(policy, { session })`. The policy\n * declares its own wire-shape — including any `WWW-Authenticate` header\n * needed for clients to drive re-auth — via `result.headers`. By default\n * the bundled `DefaultMfaSatisfiedPolicy` denies with\n * `WWW-Authenticate: Bearer error=\"mfa_required\"`.\n * - When `options.policy` is `false`, skips the policy check (the session\n * only needs to be valid).\n * - Otherwise calls `next()`.\n *\n * Generated routers (e.g. via contractkit) can opt routes into different\n * policies — step-up (`'auth.session.recent.factor'`), AAL2\n * (`'auth.session.assurance.level'`), or custom — by passing the name; no\n * other middleware changes required.\n *\n * @param options - Optional. Defaults to `{ policy: 'auth.session.mfa.satisfied' }`.\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n * @throws {HttpError} 401 when the session is invalid.\n * @throws {HttpError} 403 when the policy denies (with `details`, `headers`,\n * and `internalDetails` populated by the policy).\n *\n * @example\n * ```typescript\n * // Default MFA gate\n * router.get('/profile', requirePolicy(), handler);\n *\n * // AAL2 step-up gate\n * router.post('/admin/dangerous', requirePolicy({ policy: 'auth.session.assurance.level' }), handler);\n *\n * // Authenticated-only (no policy)\n * router.post('/mfa/enroll', requirePolicy({ policy: false }), handler);\n * ```\n */\nexport const requirePolicy = (options: RequirePolicyOptions = {}): ServerKitRouterMiddleware => {\n const policy = options.policy === undefined ? DEFAULT_POLICY : options.policy;\n\n return async (ctx, next) => {\n const session = ctx.authenticationSession;\n\n if (session === invalidAuthenticationSession) {\n throw unauthorizedError('Bearer error=\"invalid_token\"');\n }\n\n if (policy !== false) {\n const policyService = ctx.container.get(PolicyService);\n await policyService.assert(policy, { session });\n }\n\n await next();\n };\n};\n","import { createHmac, BinaryToTextEncoding } from 'node:crypto';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\nimport { AppConfig } from '@maroonedsoftware/appconfig';\n\n/**\n * Configuration for {@link requireSignature}.\n *\n * Stored in `AppConfig` and retrieved by key at request time, so the values\n * can be loaded from any AppConfig source (JSON, `.env`, GCP secrets, etc.).\n */\nexport type SignatureOptions = {\n /** Name of the request header that carries the HMAC signature (e.g. `'X-Signature'`). */\n header: string;\n /** Secret key used to compute the HMAC. */\n secret: string;\n /** HMAC algorithm passed to `crypto.createHmac` (e.g. `'sha256'`, `'sha512'`). */\n algorithm: string;\n /** Output encoding for `hmac.digest()` (e.g. `'hex'`, `'base64'`). */\n digest: BinaryToTextEncoding;\n};\n\n/**\n * Router middleware that verifies a request signature against an HMAC of `ctx.rawBody`.\n *\n * Reads {@link SignatureOptions} from `AppConfig` using `optionsKey`, then:\n * - Computes `HMAC(algorithm, secret).update(ctx.rawBody).digest(digest)`\n * - Reads the expected signature from the request header named `options.header`\n * - Throws HTTP 401 (with internal diagnostics) if the signatures do not match\n * - Calls `next()` otherwise\n *\n * Requires `ctx.rawBody` to be populated before this middleware runs — use\n * {@link bodyParserMiddleware} upstream to ensure the raw bytes are captured.\n *\n * @param optionsKey - Key used to retrieve {@link SignatureOptions} from `AppConfig` via `getAs`.\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n *\n * @example\n * ```typescript\n * // config.json\n * // { \"webhook\": { \"header\": \"X-Hub-Signature-256\", \"secret\": \"${env:WEBHOOK_SECRET}\", \"algorithm\": \"sha256\", \"digest\": \"hex\" } }\n *\n * router.post('/webhooks/github', requireSignature('webhook'), handler);\n * ```\n */\nexport const requireSignature = (optionsKey: string): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n const options = ctx.container.get(AppConfig).getAs<SignatureOptions>(optionsKey);\n\n const { header, secret, algorithm, digest } = options;\n\n const hmac = createHmac(algorithm, secret).update(ctx.rawBody);\n\n const signature = ctx.get(header);\n const computedSignature = hmac.digest(digest);\n if (computedSignature !== signature) {\n throw httpError(401).withInternalDetails({\n message: 'Invalid signature',\n header,\n computedSignature,\n signature,\n algorithm,\n digest,\n });\n }\n\n await next();\n };\n};\n","import { BinaryLike } from 'node:crypto';\nimport { IncomingMessage } from 'http';\nimport { Injectable } from 'injectkit';\n\n/**\n * The result returned by every {@link ServerKitParser}.\n *\n * @property parsed - The structured/deserialized value derived from the body (e.g. a plain object for JSON).\n * @property raw - The unprocessed body bytes as read from the stream. Parsers that do not retain a raw\n * representation (e.g. binary, multipart) return an empty `Buffer`.\n */\nexport type ServerKitParserResult = {\n parsed: unknown;\n raw: BinaryLike;\n};\n\n/**\n * Abstract base class for all ServerKit body parsers.\n *\n * Implementations read from an {@link IncomingMessage} stream and return a\n * {@link ServerKitParserResult} containing both the parsed value and the raw body.\n * Each parser is registered in the DI container and selected by MIME type via\n * {@link ServerKitBodyParser}.\n *\n * @see {@link ServerKitBodyParser} – dispatcher that selects the right parser by MIME type\n * @see {@link defaultParserMappings} – built-in MIME-type-to-parser map\n */\n@Injectable()\nexport abstract class ServerKitParser {\n /**\n * Reads and parses the body from the given request stream.\n *\n * @param req - The incoming HTTP request whose body should be consumed.\n * @returns A promise resolving to a {@link ServerKitParserResult}.\n */\n abstract parse(req: IncomingMessage): Promise<ServerKitParserResult>;\n}\n","import { parse, Reviver } from '@hapi/bourne';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\nimport { httpError } from '@maroonedsoftware/errors';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { Injectable } from 'injectkit';\n\n/**\n * Configuration options for {@link JsonParser}.\n *\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property strict - When `true` (default), only JSON objects `{}` and arrays `[]` are accepted.\n * When `false`, any valid JSON value (string, number, etc.) is allowed.\n * @property protoAction - How `@hapi/bourne` handles `__proto__` keys. Defaults to `'error'`.\n * @property reviver - Optional JSON reviver function passed to `@hapi/bourne`.\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'1mb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n */\n@Injectable()\nexport class JsonParserOptions implements raw.Options {\n strict?: boolean;\n protoAction?: 'error' | 'remove' | 'ignore';\n reviver?: Reviver;\n encoding?: string;\n limit?: string;\n length?: number;\n}\n\n// Allowed whitespace is defined in RFC 7159\n// http://www.rfc-editor.org/rfc/rfc7159.txt\n/* eslint-disable-next-line no-control-regex */\nconst strictJSONReg = /^[\\x20\\x09\\x0a\\x0d]*(\\[|\\{)/;\n\n/**\n * Parses a JSON request body using `@hapi/bourne` for prototype-pollution protection.\n *\n * In strict mode (default), only top-level objects `{}` and arrays `[]` are accepted;\n * any other value throws HTTP 400. In non-strict mode, any valid JSON value is accepted.\n * An empty body always resolves to `{ parsed: undefined }`.\n *\n * @throws HTTP 400 if the body is not valid JSON or fails the strict-mode check.\n *\n * @example\n * ```typescript\n * // Default strict mode (injectable)\n * const parser = new JsonParser(new JsonParserOptions());\n *\n * // Custom options\n * const lenient = new JsonParser({ strict: false, protoAction: 'remove' });\n * ```\n */\n@Injectable()\nexport class JsonParser extends ServerKitParser {\n constructor(private readonly options: JsonParserOptions) {\n super();\n }\n\n /**\n * Reads, decompresses, and JSON-parses the request body.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <object|array|undefined>, raw: <original string> }`.\n * @throws HTTP 400 on malformed JSON or strict-mode violation.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '1mb';\n\n const strict = this.options.strict ?? true;\n const protoAction = this.options.protoAction ?? 'error';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n const doParse = (str: string) => {\n try {\n if (this.options.reviver) {\n return parse(str, this.options.reviver, { protoAction });\n }\n return parse(str, { protoAction });\n } catch (err) {\n throw httpError(400).withCause(err as Error);\n }\n };\n\n if (!strict) {\n return str ? { parsed: doParse(str), raw: str } : { parsed: undefined, raw: str };\n } else if (!str) {\n return { parsed: undefined, raw: str };\n } else if (!strictJSONReg.test(str)) {\n throw httpError(400).withDetails({ body: 'Invalid JSON, only supports object and array' });\n }\n return { parsed: doParse(str), raw: str };\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Configuration options for {@link TextParser}.\n *\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'1mb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n */\nexport class TextParserOptions implements raw.Options {\n encoding?: string;\n limit?: string;\n length?: number;\n}\n\n/**\n * Reads the request body as a plain string.\n *\n * No structural parsing is performed; the raw text is returned as both `parsed` and `raw`.\n * Suitable for `text/plain` and similar content types. Decompresses the stream via `inflation`\n * before buffering.\n *\n * @example\n * ```typescript\n * const parser = new TextParser(new TextParserOptions());\n * const { parsed } = await parser.parse(req); // parsed is a string\n * ```\n */\n@Injectable()\nexport class TextParser extends ServerKitParser {\n constructor(private readonly options: TextParserOptions) {\n super();\n }\n\n /**\n * Reads and decompresses the request body into a string.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <string>, raw: <same string> }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '1mb';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n return { parsed: str, raw: str };\n }\n}\n","import { httpError } from '@maroonedsoftware/errors';\nimport { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport { parse, IParseOptions } from 'qs';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Configuration options for {@link FormParser}.\n *\n * Combines `raw-body` read options with `qs` parse options.\n * All fields are optional; defaults are applied by the parser itself.\n *\n * @property encoding - Body text encoding (default: `'utf8'`).\n * @property limit - Maximum body size (default: `'56kb'`).\n * @property length - Expected byte length from `Content-Length` (auto-set by the parser).\n * @property allowDots - When `true`, `qs` interprets dot notation (`user.name`) as nested objects.\n * @property depth - Maximum nesting depth for parsed objects (default: `qs` default of `5`).\n * @property parameterLimit - Maximum number of parameters to parse (default: `qs` default of `1000`).\n */\n@Injectable()\nexport class FormParserOptions implements raw.Options, IParseOptions {\n encoding?: string;\n limit?: string;\n length?: number;\n allowDots?: boolean;\n depth?: number;\n parameterLimit?: number;\n}\n\n/**\n * Parses a URL-encoded (`application/x-www-form-urlencoded`) request body using `qs`.\n *\n * Supports nested objects via bracket notation (`user[name]=alice`) by default.\n * Dot notation (`user.name=alice`) requires `allowDots: true` in the options.\n * An empty body resolves to `{ parsed: {} }`.\n *\n * @throws HTTP 400 if `qs.parse` throws unexpectedly.\n *\n * @example\n * ```typescript\n * // Default options (injectable)\n * const parser = new FormParser(new FormParserOptions());\n *\n * // Enable dot notation\n * const parser = new FormParser({ allowDots: true });\n * ```\n */\n@Injectable()\nexport class FormParser extends ServerKitParser {\n constructor(private readonly options: FormParserOptions) {\n super();\n }\n\n /**\n * Reads, decompresses, and URL-decodes the request body.\n *\n * @param req - Incoming HTTP request whose body will be consumed.\n * @returns `{ parsed: <object>, raw: <original url-encoded string> }`.\n * @throws HTTP 400 if parsing fails.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n const len = req.headers['content-length'];\n const contentEncoding = req.headers['content-encoding'] || 'identity';\n const length: number | undefined = len && contentEncoding === 'identity' ? ~~len : undefined;\n const encoding = this.options.encoding ?? 'utf8';\n const limit = this.options.limit ?? '56kb';\n\n const str = await raw(inflate(req), { encoding, limit, length });\n\n try {\n return { parsed: parse(str, this.options), raw: str };\n } catch (err) {\n throw httpError(400).withCause(err as Error);\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport { MultipartBody } from '@maroonedsoftware/multipart';\n\n/**\n * Wraps the request stream in a {@link MultipartBody} for lazy multipart/form-data parsing.\n *\n * The body is **not** eagerly consumed; fields and files are read on-demand through the\n * `MultipartBody` API. `raw` is always `undefined` because the stream cannot be replayed\n * once consumed.\n */\n@Injectable()\nexport class MultipartParser extends ServerKitParser {\n /**\n * Creates a {@link MultipartBody} around the request stream.\n *\n * @param req - Incoming HTTP request containing the multipart body.\n * @returns `{ parsed: MultipartBody, raw: Buffer(0) }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: new MultipartBody(req), raw: Buffer.from('') };\n }\n}\n","import { Injectable } from 'injectkit';\nimport { ServerKitParser, ServerKitParserResult } from './serverkit.parser.js';\nimport { IncomingMessage } from 'http';\nimport raw from 'raw-body';\nimport inflate from 'inflation';\n\n/**\n * Reads the request body as a raw `Buffer` without any text decoding or structural parsing.\n *\n * Useful for binary payloads (e.g. PDFs, images, protobuf) where the caller needs the\n * untransformed bytes. Decompresses the stream via `inflation` before buffering.\n *\n * `raw` is always `undefined` because the `Buffer` itself is both the parsed and raw form.\n */\n@Injectable()\nexport class BinaryParser extends ServerKitParser {\n /**\n * Buffers the (optionally compressed) request body into a `Buffer`.\n *\n * @param req - Incoming HTTP request to read.\n * @returns `{ parsed: Buffer, raw: Buffer(0) }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: await raw(inflate(req)), raw: Buffer.from('') };\n }\n}\n","import { Identifier } from 'injectkit';\nimport { FormParser } from './form.parser.js';\nimport { JsonParser } from './json.parser.js';\nimport { MultipartParser } from './multipart.parser.js';\nimport { ServerKitParser } from './serverkit.parser.js';\nimport { TextParser } from './text.parser.js';\n\n/**\n * Built-in MIME-subtype-to-parser mappings used by {@link bodyParserMiddleware}.\n *\n * Each key is a MIME subtype (matched against `Content-Type` via Koa's `ctx.request.is()`)\n * and the value is the InjectKit {@link Identifier} for the corresponding {@link ServerKitParser}.\n *\n * | MIME subtype | Parser |\n * | --------------------- | ----------------- |\n * | `json` | {@link JsonParser} |\n * | `application/*+json` | {@link JsonParser} |\n * | `urlencoded` | {@link FormParser} |\n * | `text` | {@link TextParser} |\n * | `multipart` | {@link MultipartParser} |\n *\n * Extend by spreading into a new object and registering the result in the DI container:\n * ```typescript\n * const myMappings = { ...defaultParserMappings, pdf: BinaryParser };\n * ```\n */\nexport const defaultParserMappings: Record<string, Identifier<ServerKitParser>> = {\n json: JsonParser,\n 'application/*+json': JsonParser,\n urlencoded: FormParser,\n text: TextParser,\n multipart: MultipartParser,\n} as const;\n"],"mappings":";;;;AACA,SAAoBA,kBAAkB;;;;;;;;AA2C/B,IAAeC,mBAAf,MAAeA;SAAAA;;;AAA8C;;;;;;AC3CpE,OAAOC,YAA+B;AAY/B,IAAMC,kBAAkB,wBAAqDC,YAA4B,IAAIC,OAAyBD,OAAAA,GAA9G;;;ACb/B,OAAOE,UAAU;AAoBV,IAAMC,iBAAiB,wBAACC,YAAAA;AAE7B,QAAMC,gBAAgB,wBAACC,QAAAA;AACrB,UAAMC,SAASD,IAAIE,IAAI,QAAA;AACvB,UAAMC,WAAWL,SAASG,UAAU;MAAC;;AACrC,eAAWG,WAAWD,UAAU;AAC9B,UA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Matcher","ctx","origin","get","matchers","matcher","test","cors","allowMethods","secureContext","keepHeadersOnError","privateNetworkAccess","IsHttpError","IsServerkitError","errorMiddleware","ctx","next","status","body","statusCode","message","details","url","URL","toString","app","emit","error","IsHttpError","headers","entry","Object","entries","set","IsServerkitError","RateLimiterRes","httpError","isRateLimiterError","error","RateLimiterRes","rateLimiterMiddleware","rateLimiter","ctx","next","consume","ip","headers","msBeforeNext","toString","points","remainingPoints","Math","ceil","Date","now","httpError","withCause","withHeaders","crypto","Logger","serverKitContextMiddleware","container","ctx","next","scopedContainer","createScopedContainer","override","ServerKitContext","logger","get","Logger","loggerName","path","userAgent","ipAddress","ip","correlationId","headers","Array","isArray","crypto","randomUUID","requestId","set","AuthenticationSchemeHandler","invalidAuthenticationSession","authenticationMiddleware","ctx","next","authenticationSession","invalidAuthenticationSession","authorizationHeader","req","headers","authorization","schemeHandler","container","get","AuthenticationSchemeHandler","handle","httpError","IsHttpError","Injectable","unique","httpError","ServerKitParserMappings","Map","ServerKitBodyParser","mimeTypes","parsers","unique","Array","from","keys","parse","ctx","mimeType","request","is","httpError","withDetails","body","parser","get","req","bodyParserMiddleware","contentTypes","ctx","next","length","request","httpError","withDetails","body","is","join","value","type","parser","container","get","ServerKitBodyParser","result","parse","parsed","rawBody","raw","error","IsHttpError","withCause","invalidAuthenticationSession","PolicyService","unauthorizedError","DEFAULT_POLICY","requirePolicy","options","policy","undefined","ctx","next","session","authenticationSession","invalidAuthenticationSession","unauthorizedError","policyService","container","get","PolicyService","assert","createHmac","httpError","AppConfig","requireSignature","optionsKey","ctx","next","options","container","get","AppConfig","getAs","header","secret","algorithm","digest","hmac","createHmac","update","rawBody","signature","computedSignature","httpError","withInternalDetails","message","Injectable","ServerKitParser","parse","raw","inflate","httpError","Injectable","JsonParserOptions","strict","protoAction","reviver","encoding","limit","length","strictJSONReg","JsonParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","doParse","err","httpError","withCause","parsed","test","withDetails","body","Injectable","raw","inflate","TextParserOptions","encoding","limit","length","TextParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","parsed","httpError","Injectable","parse","raw","inflate","FormParserOptions","encoding","limit","length","allowDots","depth","parameterLimit","FormParser","ServerKitParser","options","parse","req","len","headers","contentEncoding","undefined","str","raw","inflate","parsed","err","httpError","withCause","Injectable","MultipartBody","MultipartParser","ServerKitParser","parse","req","parsed","MultipartBody","raw","Buffer","from","Injectable","raw","inflate","BinaryParser","ServerKitParser","parse","req","parsed","raw","inflate","Buffer","from","defaultParserMappings","json","JsonParser","urlencoded","FormParser","text","TextParser","multipart","MultipartParser"]}
@@ -0,0 +1,61 @@
1
+ import { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';
2
+ /**
3
+ * Options for {@link requirePolicy}.
4
+ */
5
+ export interface RequirePolicyOptions {
6
+ /**
7
+ * Policy name to evaluate against `{ session: ctx.authenticationSession }`
8
+ * via {@link PolicyService.assert}. The policy is resolved from
9
+ * `ctx.container` per request, so applications can swap the underlying rule
10
+ * by registering their own policy class against the same name in
11
+ * `PolicyRegistryMap`.
12
+ *
13
+ * Defaults to `'auth.session.mfa.satisfied'`. Pass `false` to validate the
14
+ * session only (skip the policy check entirely).
15
+ */
16
+ policy?: string | false;
17
+ }
18
+ /**
19
+ * Router middleware that enforces a valid authentication session and, by
20
+ * default, the `'auth.session.mfa.satisfied'` policy.
21
+ *
22
+ * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and:
23
+ *
24
+ * - Throws HTTP 401 with `WWW-Authenticate: Bearer error="invalid_token"`
25
+ * when the session is `invalidAuthenticationSession`.
26
+ * - When `options.policy` is set (or omitted — the default is
27
+ * `'auth.session.mfa.satisfied'`), resolves the `PolicyService` from
28
+ * `ctx.container` and calls `assert(policy, { session })`. The policy
29
+ * declares its own wire-shape — including any `WWW-Authenticate` header
30
+ * needed for clients to drive re-auth — via `result.headers`. By default
31
+ * the bundled `DefaultMfaSatisfiedPolicy` denies with
32
+ * `WWW-Authenticate: Bearer error="mfa_required"`.
33
+ * - When `options.policy` is `false`, skips the policy check (the session
34
+ * only needs to be valid).
35
+ * - Otherwise calls `next()`.
36
+ *
37
+ * Generated routers (e.g. via contractkit) can opt routes into different
38
+ * policies — step-up (`'auth.session.recent.factor'`), AAL2
39
+ * (`'auth.session.assurance.level'`), or custom — by passing the name; no
40
+ * other middleware changes required.
41
+ *
42
+ * @param options - Optional. Defaults to `{ policy: 'auth.session.mfa.satisfied' }`.
43
+ * @returns A {@link ServerKitRouterMiddleware} that guards the route.
44
+ * @throws {HttpError} 401 when the session is invalid.
45
+ * @throws {HttpError} 403 when the policy denies (with `details`, `headers`,
46
+ * and `internalDetails` populated by the policy).
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // Default MFA gate
51
+ * router.get('/profile', requirePolicy(), handler);
52
+ *
53
+ * // AAL2 step-up gate
54
+ * router.post('/admin/dangerous', requirePolicy({ policy: 'auth.session.assurance.level' }), handler);
55
+ *
56
+ * // Authenticated-only (no policy)
57
+ * router.post('/mfa/enroll', requirePolicy({ policy: false }), handler);
58
+ * ```
59
+ */
60
+ export declare const requirePolicy: (options?: RequirePolicyOptions) => ServerKitRouterMiddleware;
61
+ //# sourceMappingURL=require.policy.middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require.policy.middleware.d.ts","sourceRoot":"","sources":["../../../src/middleware/router/require.policy.middleware.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;;;;;;OASG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACzB;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,eAAO,MAAM,aAAa,GAAI,UAAS,oBAAyB,KAAG,yBAiBlE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/koa",
3
- "version": "2.1.21",
3
+ "version": "2.2.1",
4
4
  "description": "Koa middleware, body parsing, and utilities for ServerKit",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -38,11 +38,12 @@
38
38
  "rate-limiter-flexible": "^11.0.2",
39
39
  "raw-body": "^3.0.2",
40
40
  "@maroonedsoftware/appconfig": "1.4.1",
41
+ "@maroonedsoftware/authentication": "4.20.0",
41
42
  "@maroonedsoftware/errors": "1.6.0",
42
- "@maroonedsoftware/multipart": "1.1.2",
43
43
  "@maroonedsoftware/logger": "1.1.0",
44
- "@maroonedsoftware/utilities": "1.7.0",
45
- "@maroonedsoftware/authentication": "4.18.1"
44
+ "@maroonedsoftware/policies": "0.4.0",
45
+ "@maroonedsoftware/multipart": "1.1.2",
46
+ "@maroonedsoftware/utilities": "1.7.0"
46
47
  },
47
48
  "peerDependencies": {
48
49
  "@koa/cors": "^5.0.0",
@@ -1,43 +0,0 @@
1
- import { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';
2
- /**
3
- * Options for {@link requireSecurity}.
4
- *
5
- * Enforces that an authentication session is present and optionally that
6
- * multi-factor authentication has been completed.
7
- */
8
- type SecurityOptions = {
9
- /** Whether to require multi-factor authentication. */
10
- requireMfa: boolean;
11
- };
12
- /**
13
- * Router middleware that enforces a valid authentication session and, by
14
- * default, multi-factor authentication.
15
- *
16
- * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and:
17
- *
18
- * - Throws HTTP 401 with `WWW-Authenticate: Bearer error="invalid_token"`
19
- * when the session is `invalidAuthenticationSession`.
20
- * - When `requireMfa` is true (the default), throws HTTP 401 with
21
- * `WWW-Authenticate: Bearer error="mfa_required"` if the session has fewer
22
- * than two factors or every factor is of `kind: 'knowledge'` (i.e. no
23
- * `possession` or `biometric` factor was satisfied).
24
- * - Otherwise calls `next()`.
25
- *
26
- * @param options - Security requirements for the route. Defaults to
27
- * `{ requireMfa: true }`.
28
- * @returns A {@link ServerKitRouterMiddleware} that guards the route.
29
- * @throws {HttpError} 401 when the session is invalid or MFA is required but
30
- * not satisfied.
31
- *
32
- * @example
33
- * ```typescript
34
- * // Require an authenticated user with MFA
35
- * router.get('/profile', requireSecurity(), handler);
36
- *
37
- * // Require authentication only (e.g. for a step-up MFA enrollment route)
38
- * router.post('/mfa/enroll', requireSecurity({ requireMfa: false }), handler);
39
- * ```
40
- */
41
- export declare const requireSecurity: (options?: SecurityOptions) => ServerKitRouterMiddleware;
42
- export {};
43
- //# sourceMappingURL=require.security.middleware.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"require.security.middleware.d.ts","sourceRoot":"","sources":["../../../src/middleware/router/require.security.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAG1E;;;;;GAKG;AACH,KAAK,eAAe,GAAG;IACrB,sDAAsD;IACtD,UAAU,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,eAAe,GAAI,UAAS,eAAsC,KAAG,yBAiBjF,CAAC"}