@maroonedsoftware/koa 1.17.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,18 +12,18 @@ Peer dependencies: `koa`, `@koa/router`, `@koa/cors`.
12
12
 
13
13
  ## Features
14
14
 
15
- - **ServerKitContext** — Koa context extended with `container`, `logger`, `requestId`, `correlationId`, `authenticationContext`, and related request metadata
15
+ - **ServerKitContext** — Koa context extended with `container`, `logger`, `requestId`, `correlationId`, `authenticationSession`, and related request metadata
16
16
  - **ServerKitRouter** — Router typed for `ServerKitContext`
17
17
  - **ServerKitMiddleware** — Middleware type bound to `ServerKitContext`
18
18
  - **serverKitContextMiddleware** — Populates context with scoped container, logger, and request/correlation IDs; registers the live context against the `ServerKitContext` injection token so request-scoped services can inject it
19
19
  - **corsMiddleware** — CORS headers with `'*'`, string, or RegExp origin matching
20
20
  - **errorMiddleware** — Central error handler; maps HTTP errors to status/body, 404 for unmatched routes, 500 for unknown errors
21
21
  - **rateLimiterMiddleware** — Per-IP rate limiting via `rate-limiter-flexible` (429 when exceeded)
22
- - **authenticationMiddleware** — Resolves the `Authorization` header via `AuthenticationSchemeHandler` and populates `ctx.authenticationContext`
22
+ - **authenticationMiddleware** — Resolves the `Authorization` header via `AuthenticationSchemeHandler` and populates `ctx.authenticationSession`
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 authentication and optional role-based authorization
26
+ - **requireSecurity** — Router middleware that enforces a valid authentication session
27
27
 
28
28
  ## Usage
29
29
 
@@ -86,15 +86,15 @@ import { ServerKitContext } from '@maroonedsoftware/koa';
86
86
  class CurrentUserService {
87
87
  constructor(private readonly ctx: ServerKitContext) {}
88
88
 
89
- get actorId() {
90
- return this.ctx.authenticationContext?.actorId;
89
+ get subject() {
90
+ return this.ctx.authenticationSession?.subject;
91
91
  }
92
92
  }
93
93
  ```
94
94
 
95
95
  ### Authentication
96
96
 
97
- `authenticationMiddleware` reads the `Authorization` header, delegates resolution to the `AuthenticationSchemeHandler` registered in the DI container, and populates `ctx.authenticationContext`. The header is deleted from `ctx.req.headers` immediately after reading so it cannot be captured by downstream logging.
97
+ `authenticationMiddleware` reads the `Authorization` header, delegates resolution to the `AuthenticationSchemeHandler` registered in the DI container, and populates `ctx.authenticationSession`. The header is deleted from `ctx.req.headers` immediately after reading so it cannot be captured by downstream logging.
98
98
 
99
99
  ```typescript
100
100
  import {
@@ -115,25 +115,22 @@ diRegistry.register(AuthenticationSchemeHandler).asSingleton();
115
115
  app.use(serverKitContextMiddleware(container));
116
116
  app.use(authenticationMiddleware());
117
117
 
118
- // Access the resolved context in route handlers
118
+ // Access the resolved session in route handlers
119
119
  router.get('/api/me', async ctx => {
120
- const { actorId } = ctx.authenticationContext;
121
- ctx.body = { actorId };
120
+ const { subject } = ctx.authenticationSession;
121
+ ctx.body = { subject };
122
122
  });
123
123
  ```
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, if `roles` is provided, throws 403 unless the authenticated context has at least one of the listed roles.
127
+ `requireSecurity` is router middleware that runs after `authenticationMiddleware`. It throws 401 when the request is unauthenticated.
128
128
 
129
129
  ```typescript
130
130
  import { requireSecurity } from '@maroonedsoftware/koa';
131
131
 
132
132
  // Require any authenticated user
133
133
  router.get('/api/profile', requireSecurity(), handler);
134
-
135
- // Require at least one of the given roles
136
- router.delete('/api/users/:id', requireSecurity({ roles: ['admin'] }), handler);
137
134
  ```
138
135
 
139
136
  ### CORS
@@ -264,7 +261,7 @@ The default mappings are:
264
261
  | `correlationId` | `string` | From `X-Correlation-Id` header or generated |
265
262
  | `requestId` | `string` | From `X-Request-Id` header or generated |
266
263
  | `rawBody` | `BinaryLike` | Raw request body bytes; set by `bodyParserMiddleware` |
267
- | `authenticationContext` | `AuthenticationContext` | Resolved authentication context; set by `authenticationMiddleware` |
264
+ | `authenticationSession` | `AuthenticationSession` | Resolved authentication session; set by `authenticationMiddleware` |
268
265
 
269
266
  ### Middleware
270
267
 
@@ -274,10 +271,10 @@ The default mappings are:
274
271
  | `corsMiddleware(options?)` | CORS via `@koa/cors`; `origin`: `'*'`, string, or `(string \| RegExp)[]` |
275
272
  | `errorMiddleware()` | Catches errors, maps HTTP errors to status/body, 404/500, emits app events |
276
273
  | `rateLimiterMiddleware(rateLimiter)` | Consumes one token per request by IP; throws 429 when exceeded |
277
- | `authenticationMiddleware()` | Resolves `Authorization` header via `AuthenticationSchemeHandler`; populates `ctx.authenticationContext` |
274
+ | `authenticationMiddleware()` | Resolves `Authorization` header via `AuthenticationSchemeHandler`; populates `ctx.authenticationSession` |
278
275
  | `bodyParserMiddleware(contentTypes)` | Parses body by allowed MIME types; throws 400/411/415/422 on invalid input |
279
276
  | `requireSignature(optionsKey)` | Verifies HMAC of `ctx.rawBody` against a request header; throws 401 on mismatch |
280
- | `requireSecurity(options?)` | Throws 401 when unauthenticated; throws 403 when none of the `options.roles` are present |
277
+ | `requireSecurity()` | Throws 401 when `ctx.authenticationSession` is `invalidAuthenticationSession` |
281
278
 
282
279
  ### Parser options
283
280
 
package/dist/index.js CHANGED
@@ -157,14 +157,14 @@ var serverKitContextMiddleware = /* @__PURE__ */ __name((container) => {
157
157
  }, "serverKitContextMiddleware");
158
158
 
159
159
  // src/middleware/server/authentication.middleware.ts
160
- import { AuthenticationSchemeHandler, invalidAuthenticationContext } from "@maroonedsoftware/authentication";
160
+ import { AuthenticationSchemeHandler, invalidAuthenticationSession } from "@maroonedsoftware/authentication";
161
161
  var authenticationMiddleware = /* @__PURE__ */ __name(() => {
162
162
  return async (ctx, next) => {
163
- ctx.authenticationContext = invalidAuthenticationContext;
163
+ ctx.authenticationSession = invalidAuthenticationSession;
164
164
  const authorizationHeader = ctx.req.headers.authorization;
165
165
  delete ctx.req.headers.authorization;
166
166
  const schemeHandler = ctx.container.get(AuthenticationSchemeHandler);
167
- ctx.authenticationContext = await schemeHandler.handle(authorizationHeader);
167
+ ctx.authenticationSession = await schemeHandler.handle(authorizationHeader);
168
168
  await next();
169
169
  };
170
170
  }, "authenticationMiddleware");
@@ -275,28 +275,21 @@ var bodyParserMiddleware = /* @__PURE__ */ __name((contentTypes) => {
275
275
  }, "bodyParserMiddleware");
276
276
 
277
277
  // src/middleware/router/require.security.middleware.ts
278
- import { invalidAuthenticationContext as invalidAuthenticationContext2 } from "@maroonedsoftware/authentication";
279
- import { httpError as httpError4, unauthorizedError } from "@maroonedsoftware/errors";
280
- var requireSecurity = /* @__PURE__ */ __name((options) => {
278
+ import { invalidAuthenticationSession as invalidAuthenticationSession2 } from "@maroonedsoftware/authentication";
279
+ import { unauthorizedError } from "@maroonedsoftware/errors";
280
+ var requireSecurity = /* @__PURE__ */ __name((_options) => {
281
281
  return async (ctx, next) => {
282
- const authenticationContext = ctx.authenticationContext;
283
- if (authenticationContext === invalidAuthenticationContext2) {
282
+ const authenticationSession = ctx.authenticationSession;
283
+ if (authenticationSession === invalidAuthenticationSession2) {
284
284
  throw unauthorizedError('Bearer error="invalid_token"');
285
285
  }
286
- if (options?.roles && options.roles.length > 0 && !options.roles.some((role) => authenticationContext.roles.includes(role))) {
287
- throw httpError4(403).withInternalDetails({
288
- message: "Insufficient role",
289
- requiredRoles: options.roles,
290
- userRoles: authenticationContext.roles.join(", ")
291
- });
292
- }
293
286
  await next();
294
287
  };
295
288
  }, "requireSecurity");
296
289
 
297
290
  // src/middleware/router/require.signature.middleware.ts
298
291
  import { createHmac } from "crypto";
299
- import { httpError as httpError5 } from "@maroonedsoftware/errors";
292
+ import { httpError as httpError4 } from "@maroonedsoftware/errors";
300
293
  import { AppConfig } from "@maroonedsoftware/appconfig";
301
294
  var requireSignature = /* @__PURE__ */ __name((optionsKey) => {
302
295
  return async (ctx, next) => {
@@ -306,7 +299,7 @@ var requireSignature = /* @__PURE__ */ __name((optionsKey) => {
306
299
  const signature = ctx.get(header);
307
300
  const computedSignature = hmac.digest(digest);
308
301
  if (computedSignature !== signature) {
309
- throw httpError5(401).withInternalDetails({
302
+ throw httpError4(401).withInternalDetails({
310
303
  message: "Invalid signature",
311
304
  header,
312
305
  computedSignature,
@@ -341,7 +334,7 @@ ServerKitParser = _ts_decorate3([
341
334
  import { parse } from "@hapi/bourne";
342
335
  import raw from "raw-body";
343
336
  import inflate from "inflation";
344
- import { httpError as httpError6 } from "@maroonedsoftware/errors";
337
+ import { httpError as httpError5 } from "@maroonedsoftware/errors";
345
338
  import { Injectable as Injectable4 } from "injectkit";
346
339
  function _ts_decorate4(decorators, target, key, desc) {
347
340
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -408,7 +401,7 @@ var JsonParser = class extends ServerKitParser {
408
401
  protoAction
409
402
  });
410
403
  } catch (err) {
411
- throw httpError6(400).withCause(err);
404
+ throw httpError5(400).withCause(err);
412
405
  }
413
406
  }, "doParse");
414
407
  if (!strict) {
@@ -425,7 +418,7 @@ var JsonParser = class extends ServerKitParser {
425
418
  raw: str
426
419
  };
427
420
  } else if (!strictJSONReg.test(str)) {
428
- throw httpError6(400).withDetails({
421
+ throw httpError5(400).withDetails({
429
422
  body: "Invalid JSON, only supports object and array"
430
423
  });
431
424
  }
@@ -506,7 +499,7 @@ TextParser = _ts_decorate5([
506
499
  ], TextParser);
507
500
 
508
501
  // src/parsers/form.parser.ts
509
- import { httpError as httpError7 } from "@maroonedsoftware/errors";
502
+ import { httpError as httpError6 } from "@maroonedsoftware/errors";
510
503
  import { Injectable as Injectable6 } from "injectkit";
511
504
  import { parse as parse2 } from "qs";
512
505
  import raw3 from "raw-body";
@@ -568,7 +561,7 @@ var FormParser = class extends ServerKitParser {
568
561
  raw: str
569
562
  };
570
563
  } catch (err) {
571
- throw httpError7(400).withCause(err);
564
+ throw httpError6(400).withCause(err);
572
565
  }
573
566
  }
574
567
  };
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 { AuthenticationContext } 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 context. */\n authenticationContext: AuthenticationContext;\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, invalidAuthenticationContext } from '@maroonedsoftware/authentication';\n\n/**\n * Resolves the `Authorization` request header into an {@link AuthenticationContext}\n * and attaches it to `ctx.authenticationContext`.\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.authenticationContext` is initialised to\n * {@link invalidAuthenticationContext} 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.authenticationContext`.\n *\n * @example\n * ```typescript\n * app.use(authenticationMiddleware());\n * ```\n */\nexport const authenticationMiddleware = (): ServerKitMiddleware => {\n return async (ctx, next) => {\n ctx.authenticationContext = invalidAuthenticationContext; // 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.authenticationContext = 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 { invalidAuthenticationContext } from '@maroonedsoftware/authentication';\nimport { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';\nimport { httpError, unauthorizedError } from '@maroonedsoftware/errors';\n\n/**\n * Options for {@link requireSecurity}.\n */\ntype SecurityOptions = {\n /** When set, the authenticated user must have this role in their `AuthenticationContext.roles` array. */\n roles?: string[];\n};\n\n/**\n * Router middleware that enforces authentication and optional role-based authorization.\n *\n * Reads `ctx.authenticationContext` (set by `authenticationMiddleware`) and:\n * - Throws HTTP 401 with a `WWW-Authenticate: Bearer error=\"invalid_token\"` header\n * if the context is `invalidAuthenticationContext`.\n * - Throws HTTP 403 if `options.role` is specified and the user does not have that role.\n * - Calls `next()` otherwise.\n *\n * @param options - Optional {@link SecurityOptions} for role-based access control.\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n *\n * @example\n * ```typescript\n * // Require any authenticated user\n * router.get('/profile', requireSecurity(), handler);\n *\n * // Require the 'admin' role\n * router.delete('/users/:id', requireSecurity({ role: 'admin' }), handler);\n * ```\n */\nexport const requireSecurity = (options?: SecurityOptions): ServerKitRouterMiddleware => {\n return async (ctx, next) => {\n const authenticationContext = ctx.authenticationContext;\n\n if (authenticationContext === invalidAuthenticationContext) {\n throw unauthorizedError('Bearer error=\"invalid_token\"');\n }\n\n if (options?.roles && options.roles.length > 0 && !options.roles.some(role => authenticationContext.roles.includes(role))) {\n throw httpError(403).withInternalDetails({\n message: 'Insufficient role',\n requiredRoles: options.roles,\n userRoles: authenticationContext.roles.join(', '),\n });\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;IACzCC,oBAAoBX,SAASW,sBAAsB;IACnDC,sBAAsBZ,SAASY,wBAAwB;EACzD,CAAA;AACF,GAlC8B;;;ACnB9B,SAASC,aAAaC,wBAAwB;AASvC,IAAMC,kBAAkB,6BAAA;AAC7B,SAAO,OAAOC,KAAKC,SAAAA;AACjB,QAAI;AACF,YAAMA,KAAAA;AACN,UAAID,IAAIE,WAAW,OAAO,CAACF,IAAIG,MAAM;AACnC,cAAMA,OAAO;UACXC,YAAY;UACZC,SAAS;UACTC,SAAS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;;;;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","invalidAuthenticationContext","authenticationMiddleware","ctx","next","authenticationContext","invalidAuthenticationContext","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","invalidAuthenticationContext","httpError","unauthorizedError","requireSecurity","options","ctx","next","authenticationContext","invalidAuthenticationContext","unauthorizedError","roles","length","some","role","includes","httpError","withInternalDetails","message","requiredRoles","userRoles","join","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.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 * Reserved for future role/scope-based checks; currently the middleware only\n * enforces that an authentication session is present.\n */\ntype SecurityOptions = {\n /** Reserved — role enforcement is not currently wired up. */\n roles?: string[];\n};\n\n/**\n * Router middleware that enforces a valid authentication session.\n *\n * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and\n * throws HTTP 401 with a `WWW-Authenticate: Bearer error=\"invalid_token\"`\n * header when the session is `invalidAuthenticationSession`. Otherwise calls\n * `next()`.\n *\n * @returns A {@link ServerKitRouterMiddleware} that guards the route.\n *\n * @example\n * ```typescript\n * // Require any authenticated user\n * router.get('/profile', requireSecurity(), handler);\n * ```\n */\nexport const requireSecurity = (_options?: SecurityOptions): 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 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,eAA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QAAQR,YAAY;AAC1C,UAAMC,QAAQ,KAAKO,QAAQP,SAAS;AAEpC,UAAMc,MAAM,MAAMC,KAAIC,SAAQP,GAAAA,GAAM;MAAEV;MAAUC;MAAOC;IAAO,CAAA;AAE9D,QAAI;AACF,aAAO;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","ctx","next","authenticationSession","invalidAuthenticationSession","unauthorizedError","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,32 +1,30 @@
1
1
  import { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';
2
2
  /**
3
3
  * Options for {@link requireSecurity}.
4
+ *
5
+ * Reserved for future role/scope-based checks; currently the middleware only
6
+ * enforces that an authentication session is present.
4
7
  */
5
8
  type SecurityOptions = {
6
- /** When set, the authenticated user must have this role in their `AuthenticationContext.roles` array. */
9
+ /** Reserved role enforcement is not currently wired up. */
7
10
  roles?: string[];
8
11
  };
9
12
  /**
10
- * Router middleware that enforces authentication and optional role-based authorization.
13
+ * Router middleware that enforces a valid authentication session.
11
14
  *
12
- * Reads `ctx.authenticationContext` (set by `authenticationMiddleware`) and:
13
- * - Throws HTTP 401 with a `WWW-Authenticate: Bearer error="invalid_token"` header
14
- * if the context is `invalidAuthenticationContext`.
15
- * - Throws HTTP 403 if `options.role` is specified and the user does not have that role.
16
- * - Calls `next()` otherwise.
15
+ * Reads `ctx.authenticationSession` (set by `authenticationMiddleware`) and
16
+ * throws HTTP 401 with a `WWW-Authenticate: Bearer error="invalid_token"`
17
+ * header when the session is `invalidAuthenticationSession`. Otherwise calls
18
+ * `next()`.
17
19
  *
18
- * @param options - Optional {@link SecurityOptions} for role-based access control.
19
20
  * @returns A {@link ServerKitRouterMiddleware} that guards the route.
20
21
  *
21
22
  * @example
22
23
  * ```typescript
23
24
  * // Require any authenticated user
24
25
  * router.get('/profile', requireSecurity(), handler);
25
- *
26
- * // Require the 'admin' role
27
- * router.delete('/users/:id', requireSecurity({ role: 'admin' }), handler);
28
26
  * ```
29
27
  */
30
- export declare const requireSecurity: (options?: SecurityOptions) => ServerKitRouterMiddleware;
28
+ export declare const requireSecurity: (_options?: SecurityOptions) => ServerKitRouterMiddleware;
31
29
  export {};
32
30
  //# sourceMappingURL=require.security.middleware.d.ts.map
@@ -1 +1 @@
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;;GAEG;AACH,KAAK,eAAe,GAAG;IACrB,yGAAyG;IACzG,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,eAAe,GAAI,UAAU,eAAe,KAAG,yBAkB3D,CAAC"}
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,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,eAAe,GAAI,WAAW,eAAe,KAAG,yBAU5D,CAAC"}
@@ -1,17 +1,17 @@
1
1
  import { ServerKitMiddleware } from '../../serverkit.middleware.js';
2
2
  /**
3
- * Resolves the `Authorization` request header into an {@link AuthenticationContext}
4
- * and attaches it to `ctx.authenticationContext`.
3
+ * Resolves the `Authorization` request header into an {@link AuthenticationSession}
4
+ * and attaches it to `ctx.authenticationSession`.
5
5
  *
6
6
  * The header is immediately removed from `ctx.req.headers` after being read so it
7
7
  * cannot be accidentally captured by downstream logging or serialization.
8
8
  *
9
9
  * Resolution is delegated to the {@link AuthenticationSchemeHandler} registered in
10
- * the DI container. `ctx.authenticationContext` is initialised to
11
- * {@link invalidAuthenticationContext} before delegation, ensuring that any error
10
+ * the DI container. `ctx.authenticationSession` is initialised to
11
+ * {@link invalidAuthenticationSession} before delegation, ensuring that any error
12
12
  * thrown by the scheme handler leaves the context in a safe, unauthenticated state.
13
13
  *
14
- * @returns A {@link ServerKitMiddleware} that populates `ctx.authenticationContext`.
14
+ * @returns A {@link ServerKitMiddleware} that populates `ctx.authenticationSession`.
15
15
  *
16
16
  * @example
17
17
  * ```typescript
@@ -1,7 +1,7 @@
1
1
  import { Context } from 'koa';
2
2
  import { Container } from 'injectkit';
3
3
  import { Logger } from '@maroonedsoftware/logger';
4
- import { AuthenticationContext } from '@maroonedsoftware/authentication';
4
+ import { AuthenticationSession } from '@maroonedsoftware/authentication';
5
5
  import { BinaryLike } from 'node:crypto';
6
6
  /**
7
7
  * Koa context extended with ServerKit request-scoped services and metadata.
@@ -28,8 +28,8 @@ export interface ServerKitContext extends Context {
28
28
  requestId: string;
29
29
  /** Raw body for this request. */
30
30
  rawBody: BinaryLike;
31
- /** Authentication context. */
32
- authenticationContext: AuthenticationContext;
31
+ /** Authentication session. */
32
+ authenticationSession: AuthenticationSession;
33
33
  }
34
34
  /**
35
35
  * Abstract class merged with the {@link ServerKitContext} interface so it can serve as an
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/koa",
3
- "version": "1.17.9",
3
+ "version": "2.0.0",
4
4
  "description": "Koa middleware, body parsing, and utilities for ServerKit",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -37,12 +37,12 @@
37
37
  "qs": "^6.15.1",
38
38
  "rate-limiter-flexible": "^11.0.2",
39
39
  "raw-body": "^3.0.2",
40
- "@maroonedsoftware/authentication": "2.3.0",
41
40
  "@maroonedsoftware/appconfig": "1.4.1",
41
+ "@maroonedsoftware/authentication": "4.0.0",
42
42
  "@maroonedsoftware/errors": "1.6.0",
43
43
  "@maroonedsoftware/logger": "1.1.0",
44
- "@maroonedsoftware/utilities": "1.7.0",
45
- "@maroonedsoftware/multipart": "1.1.2"
44
+ "@maroonedsoftware/multipart": "1.1.2",
45
+ "@maroonedsoftware/utilities": "1.7.0"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@koa/cors": "^5.0.0",