@maroonedsoftware/koa 1.3.0 → 1.5.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/dist/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * from './middleware/server/rate.limiter.middleware.js';
7
7
  export * from './middleware/server/serverkit.context.middleware.js';
8
8
  export * from './middleware/server/authentication.middleware.js';
9
9
  export * from './middleware/router/body.parser.middleware.js';
10
+ export * from './middleware/router/require.security.middleware.js';
10
11
  export * from './parsers/serverkit.parser.js';
11
12
  export * from './serverkit.bodyparser.js';
12
13
  export * from './parsers/json.parser.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,wCAAwC,CAAC;AACvD,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,qDAAqD,CAAC;AACpE,cAAc,kDAAkD,CAAC;AACjE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wCAAwC,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uBAAuB,CAAC;AACtC,cAAc,wCAAwC,CAAC;AACvD,cAAc,yCAAyC,CAAC;AACxD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,qDAAqD,CAAC;AACpE,cAAc,kDAAkD,CAAC;AACjE,cAAc,+CAA+C,CAAC;AAC9D,cAAc,oDAAoD,CAAC;AACnE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,wCAAwC,CAAC"}
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
3
3
 
4
4
  // src/serverkit.router.ts
5
5
  import Router from "@koa/router";
6
- var ServerKitRouter = /* @__PURE__ */ __name(() => new Router(), "ServerKitRouter");
6
+ var ServerKitRouter = /* @__PURE__ */ __name((options) => new Router(options), "ServerKitRouter");
7
7
 
8
8
  // src/middleware/server/cors.middleware.ts
9
9
  import cors from "@koa/cors";
@@ -121,7 +121,7 @@ var authenticationMiddleware = /* @__PURE__ */ __name(() => {
121
121
  ctx.authenticationContext = invalidAuthenticationContext;
122
122
  const authorizationHeader = ctx.req.headers.authorization;
123
123
  delete ctx.req.headers.authorization;
124
- const schemeHandler = ctx.serviceLocator.get(AuthenticationSchemeHandler);
124
+ const schemeHandler = ctx.container.get(AuthenticationSchemeHandler);
125
125
  ctx.authenticationContext = await schemeHandler.handle(authorizationHeader);
126
126
  await next();
127
127
  };
@@ -232,6 +232,26 @@ var bodyParserMiddleware = /* @__PURE__ */ __name((contentTypes) => {
232
232
  };
233
233
  }, "bodyParserMiddleware");
234
234
 
235
+ // src/middleware/router/require.security.middleware.ts
236
+ import { invalidAuthenticationContext as invalidAuthenticationContext2 } from "@maroonedsoftware/authentication";
237
+ import { httpError as httpError4, unauthorizedError } from "@maroonedsoftware/errors";
238
+ var requireSecurity = /* @__PURE__ */ __name((options) => {
239
+ return async (ctx, next) => {
240
+ const authenticationContext = ctx.authenticationContext;
241
+ if (authenticationContext === invalidAuthenticationContext2) {
242
+ throw unauthorizedError('Bearer error="invalid_token"');
243
+ }
244
+ if (options?.role && !authenticationContext.roles.includes(options.role)) {
245
+ throw httpError4(403).withInternalDetails({
246
+ message: "Insufficient role",
247
+ requiredRole: options.role,
248
+ userRoles: authenticationContext.roles
249
+ });
250
+ }
251
+ await next();
252
+ };
253
+ }, "requireSecurity");
254
+
235
255
  // src/parsers/serverkit.parser.ts
236
256
  import { Injectable as Injectable2 } from "injectkit";
237
257
  function _ts_decorate2(decorators, target, key, desc) {
@@ -254,7 +274,7 @@ ServerKitParser = _ts_decorate2([
254
274
  import { parse } from "@hapi/bourne";
255
275
  import raw from "raw-body";
256
276
  import inflate from "inflation";
257
- import { httpError as httpError4 } from "@maroonedsoftware/errors";
277
+ import { httpError as httpError5 } from "@maroonedsoftware/errors";
258
278
  import { Injectable as Injectable3 } from "injectkit";
259
279
  function _ts_decorate3(decorators, target, key, desc) {
260
280
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -321,7 +341,7 @@ var JsonParser = class extends ServerKitParser {
321
341
  protoAction
322
342
  });
323
343
  } catch (err) {
324
- throw httpError4(400).withCause(err);
344
+ throw httpError5(400).withCause(err);
325
345
  }
326
346
  }, "doParse");
327
347
  if (!strict) {
@@ -338,7 +358,7 @@ var JsonParser = class extends ServerKitParser {
338
358
  raw: str
339
359
  };
340
360
  } else if (!strictJSONReg.test(str)) {
341
- throw httpError4(400).withDetails({
361
+ throw httpError5(400).withDetails({
342
362
  body: "Invalid JSON, only supports object and array"
343
363
  });
344
364
  }
@@ -419,7 +439,7 @@ TextParser = _ts_decorate4([
419
439
  ], TextParser);
420
440
 
421
441
  // src/parsers/form.parser.ts
422
- import { httpError as httpError5 } from "@maroonedsoftware/errors";
442
+ import { httpError as httpError6 } from "@maroonedsoftware/errors";
423
443
  import { Injectable as Injectable5 } from "injectkit";
424
444
  import { parse as parse2 } from "qs";
425
445
  import raw3 from "raw-body";
@@ -481,7 +501,7 @@ var FormParser = class extends ServerKitParser {
481
501
  raw: str
482
502
  };
483
503
  } catch (err) {
484
- throw httpError5(400).withCause(err);
504
+ throw httpError6(400).withCause(err);
485
505
  }
486
506
  }
487
507
  };
@@ -583,6 +603,7 @@ export {
583
603
  defaultParserMappings,
584
604
  errorMiddleware,
585
605
  rateLimiterMiddleware,
606
+ requireSecurity,
586
607
  serverKitContextMiddleware
587
608
  };
588
609
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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/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 { DefaultState } from 'koa';\nimport Router 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 * @returns A new {@link Router} instance.\n */\nexport const ServerKitRouter = <StateT = DefaultState, ContextT = ServerKitContext>() => new Router<StateT, ContextT>();\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 } 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 {\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 } from 'rate-limiter-flexible';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\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) {\n throw httpError(429).withCause(error as Error);\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';\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 * 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 ctx.container = container.createScopedContainer();\n ctx.logger = container.get(Logger);\n ctx.loggerName = ctx.path;\n\n ctx.userAgent = ctx.get('user-agent') ?? '';\n ctx.correlationId = ctx.get('x-correlation-id') ?? crypto.randomUUID();\n ctx.requestId = ctx.get('x-request-id') ?? 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.serviceLocator.get(AuthenticationSchemeHandler);\n\n ctx.authenticationContext = await schemeHandler.handle(authorizationHeader);\n\n await next();\n };\n};\n","import { httpError, IsHttpError } from '@maroonedsoftware/errors';\nimport { ServerKitMiddleware } 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 ServerKitMiddleware} 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[]): ServerKitMiddleware => {\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 { 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 as read from the stream (e.g. the original string or `Buffer`).\n * May be `undefined` for parsers that do not retain a raw representation (e.g. binary, multipart).\n */\nexport type ServerKitParserResult = {\n parsed: unknown;\n raw: unknown;\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: undefined }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: new MultipartBody(req), raw: undefined };\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: undefined }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: await raw(inflate(req)), raw: undefined };\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,OAAOA,YAAY;AAWZ,IAAMC,kBAAkB,6BAA0D,IAAIC,OAAAA,GAA9D;;;ACZ/B,OAAOC,UAAU;AAoBV,IAAMC,iBAAiB,w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C,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;IAAU;EAC1D;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;IAAU;EAC3D;AACF;;;;;;ACCO,IAAMC,wBAAqE;EAChFC,MAAMC;EACN,sBAAsBA;EACtBC,YAAYC;EACZC,MAAMC;EACNC,WAAWC;AACb;","names":["Router","ServerKitRouter","Router","cors","corsMiddleware","options","originMatcher","ctx","origin","get","matchers","matcher","test","cors","allowMethods","secureContext","keepHeadersOnError","privateNetworkAccess","IsHttpError","errorMiddleware","ctx","next","status","body","statusCode","message","details","url","URL","toString","app","emit","error","IsHttpError","headers","entry","Object","entries","set","httpError","rateLimiterMiddleware","rateLimiter","ctx","next","consume","ip","error","httpError","withCause","crypto","Logger","serverKitContextMiddleware","container","ctx","next","createScopedContainer","logger","get","Logger","loggerName","path","userAgent","correlationId","crypto","randomUUID","requestId","headers","set","AuthenticationSchemeHandler","invalidAuthenticationContext","authenticationMiddleware","ctx","next","authenticationContext","invalidAuthenticationContext","authorizationHeader","req","headers","authorization","schemeHandler","serviceLocator","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","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","undefined","Injectable","raw","inflate","BinaryParser","ServerKitParser","parse","req","parsed","raw","inflate","undefined","defaultParserMappings","json","JsonParser","urlencoded","FormParser","text","TextParser","multipart","MultipartParser"]}
1
+ {"version":3,"sources":["../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/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 { 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 } 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 {\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 } from 'rate-limiter-flexible';\nimport { ServerKitMiddleware } from '../../serverkit.middleware.js';\nimport { httpError } from '@maroonedsoftware/errors';\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) {\n throw httpError(429).withCause(error as Error);\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';\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 * 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 ctx.container = container.createScopedContainer();\n ctx.logger = container.get(Logger);\n ctx.loggerName = ctx.path;\n\n ctx.userAgent = ctx.get('user-agent') ?? '';\n ctx.correlationId = ctx.get('x-correlation-id') ?? crypto.randomUUID();\n ctx.requestId = ctx.get('x-request-id') ?? 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 role?: 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?.role && !authenticationContext.roles.includes(options.role)) {\n throw httpError(403).withInternalDetails({\n message: 'Insufficient role',\n requiredRole: options.role,\n userRoles: authenticationContext.roles,\n });\n }\n\n await next();\n };\n};\n","import { 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 as read from the stream (e.g. the original string or `Buffer`).\n * May be `undefined` for parsers that do not retain a raw representation (e.g. binary, multipart).\n */\nexport type ServerKitParserResult = {\n parsed: unknown;\n raw: unknown;\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: undefined }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: new MultipartBody(req), raw: undefined };\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: undefined }`.\n */\n async parse(req: IncomingMessage): Promise<ServerKitParserResult> {\n return { parsed: await raw(inflate(req)), raw: undefined };\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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,MAAMC;EACN,sBAAsBA;EACtBC,YAAYC;EACZC,MAAMC;EACNC,WAAWC;AACb;","names":["Router","ServerKitRouter","options","Router","cors","corsMiddleware","options","originMatcher","ctx","origin","get","matchers","matcher","test","cors","allowMethods","secureContext","keepHeadersOnError","privateNetworkAccess","IsHttpError","errorMiddleware","ctx","next","status","body","statusCode","message","details","url","URL","toString","app","emit","error","IsHttpError","headers","entry","Object","entries","set","httpError","rateLimiterMiddleware","rateLimiter","ctx","next","consume","ip","error","httpError","withCause","crypto","Logger","serverKitContextMiddleware","container","ctx","next","createScopedContainer","logger","get","Logger","loggerName","path","userAgent","correlationId","crypto","randomUUID","requestId","headers","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","role","roles","includes","httpError","withInternalDetails","message","requiredRole","userRoles","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","undefined","Injectable","raw","inflate","BinaryParser","ServerKitParser","parse","req","parsed","raw","inflate","undefined","defaultParserMappings","json","JsonParser","urlencoded","FormParser","text","TextParser","multipart","MultipartParser"]}
@@ -1,4 +1,4 @@
1
- import { ServerKitMiddleware } from '../../serverkit.middleware.js';
1
+ import { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';
2
2
  /**
3
3
  * Parses the request body based on `Content-Type` and assigns it to `ctx.body`.
4
4
  * Rejects requests with unexpected or unsupported content types.
@@ -8,11 +8,11 @@ import { ServerKitMiddleware } from '../../serverkit.middleware.js';
8
8
  *
9
9
  * @param contentTypes - Allowed MIME types (e.g. `['application/json', 'application/x-www-form-urlencoded']`).
10
10
  * Use an empty array to disallow any request body.
11
- * @returns {@link ServerKitMiddleware} that parses the body and sets `ctx.body`.
11
+ * @returns {@link ServerKitRouterMiddleware} that parses the body and sets `ctx.body`.
12
12
  * @throws HTTP 400 if body is present when no content types are allowed.
13
13
  * @throws HTTP 411 if body is required but missing.
14
14
  * @throws HTTP 415 if `Content-Type` is not in `contentTypes`.
15
15
  * @throws HTTP 422 if body is invalid or media type is unsupported.
16
16
  */
17
- export declare const bodyParserMiddleware: (contentTypes: string[]) => ServerKitMiddleware;
17
+ export declare const bodyParserMiddleware: (contentTypes: string[]) => ServerKitRouterMiddleware;
18
18
  //# sourceMappingURL=body.parser.middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"body.parser.middleware.d.ts","sourceRoot":"","sources":["../../../src/middleware/router/body.parser.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAGpE;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAAI,cAAc,MAAM,EAAE,KAAG,mBAkC7D,CAAC"}
1
+ {"version":3,"file":"body.parser.middleware.d.ts","sourceRoot":"","sources":["../../../src/middleware/router/body.parser.middleware.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAG1E;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAAI,cAAc,MAAM,EAAE,KAAG,yBAkC7D,CAAC"}
@@ -0,0 +1,32 @@
1
+ import { ServerKitRouterMiddleware } from '../../serverkit.middleware.js';
2
+ /**
3
+ * Options for {@link requireSecurity}.
4
+ */
5
+ type SecurityOptions = {
6
+ /** When set, the authenticated user must have this role in their `AuthenticationContext.roles` array. */
7
+ role?: string;
8
+ };
9
+ /**
10
+ * Router middleware that enforces authentication and optional role-based authorization.
11
+ *
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.
17
+ *
18
+ * @param options - Optional {@link SecurityOptions} for role-based access control.
19
+ * @returns A {@link ServerKitRouterMiddleware} that guards the route.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // Require any authenticated user
24
+ * router.get('/profile', requireSecurity(), handler);
25
+ *
26
+ * // Require the 'admin' role
27
+ * router.delete('/users/:id', requireSecurity({ role: 'admin' }), handler);
28
+ * ```
29
+ */
30
+ export declare const requireSecurity: (options?: SecurityOptions) => ServerKitRouterMiddleware;
31
+ export {};
32
+ //# sourceMappingURL=require.security.middleware.d.ts.map
@@ -0,0 +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,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,eAAe,GAAI,UAAU,eAAe,KAAG,yBAkB3D,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { DefaultState, Middleware } from 'koa';
2
2
  import { ServerKitContext } from './serverkit.context.js';
3
+ import { RouterMiddleware } from '@koa/router';
3
4
  /**
4
5
  * Koa middleware type bound to {@link ServerKitContext}.
5
6
  * Use this for middleware that relies on ServerKit context (container, logger, etc.).
@@ -9,4 +10,12 @@ import { ServerKitContext } from './serverkit.context.js';
9
10
  * @typeParam Context - Context type (defaults to `ServerKitContext`).
10
11
  */
11
12
  export type ServerKitMiddleware<ResponseBody = unknown, State = DefaultState, Context extends ServerKitContext = ServerKitContext> = Middleware<State, Context, ResponseBody>;
13
+ /**
14
+ * `@koa/router` middleware type bound to {@link ServerKitContext}.
15
+ * Use this for route-level middleware (attached via `router.use()` or inline on route definitions).
16
+ *
17
+ * @typeParam State - Koa state type (defaults to `DefaultState`).
18
+ * @typeParam Context - Context type (defaults to `ServerKitContext`).
19
+ */
20
+ export type ServerKitRouterMiddleware<State = DefaultState, Context extends ServerKitContext = ServerKitContext> = RouterMiddleware<State, Context>;
12
21
  //# sourceMappingURL=serverkit.middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverkit.middleware.d.ts","sourceRoot":"","sources":["../src/serverkit.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,CAAC,YAAY,GAAG,OAAO,EAAE,KAAK,GAAG,YAAY,EAAE,OAAO,SAAS,gBAAgB,GAAG,gBAAgB,IAAI,UAAU,CAC7I,KAAK,EACL,OAAO,EACP,YAAY,CACb,CAAC"}
1
+ {"version":3,"file":"serverkit.middleware.d.ts","sourceRoot":"","sources":["../src/serverkit.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,CAAC,YAAY,GAAG,OAAO,EAAE,KAAK,GAAG,YAAY,EAAE,OAAO,SAAS,gBAAgB,GAAG,gBAAgB,IAAI,UAAU,CAC7I,KAAK,EACL,OAAO,EACP,YAAY,CACb,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,yBAAyB,CAAC,KAAK,GAAG,YAAY,EAAE,OAAO,SAAS,gBAAgB,GAAG,gBAAgB,IAAI,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { DefaultState } from 'koa';
2
- import Router from '@koa/router';
2
+ import Router, { RouterOptions } from '@koa/router';
3
3
  import { ServerKitContext } from './serverkit.context.js';
4
4
  /**
5
5
  * Creates a new Koa router typed for ServerKit state and context.
@@ -7,7 +7,8 @@ import { ServerKitContext } from './serverkit.context.js';
7
7
  *
8
8
  * @typeParam StateT - Koa state type (defaults to `DefaultState`).
9
9
  * @typeParam ContextT - Context type (defaults to `ServerKitContext`).
10
- * @returns A new {@link Router} instance.
10
+ * @param options - Router options (defaults to `undefined`).
11
+ * @returns A new {@link Router} instance with the given options.
11
12
  */
12
- export declare const ServerKitRouter: <StateT = DefaultState, ContextT = ServerKitContext>() => Router<StateT, ContextT>;
13
+ export declare const ServerKitRouter: <StateT = DefaultState, ContextT = ServerKitContext>(options?: RouterOptions) => Router<StateT, ContextT>;
13
14
  //# sourceMappingURL=serverkit.router.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverkit.router.d.ts","sourceRoot":"","sources":["../src/serverkit.router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,MAAM,GAAG,YAAY,EAAE,QAAQ,GAAG,gBAAgB,+BAAqC,CAAC"}
1
+ {"version":3,"file":"serverkit.router.d.ts","sourceRoot":"","sources":["../src/serverkit.router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;;;;;;GAQG;AACH,eAAO,MAAM,eAAe,GAAI,MAAM,GAAG,YAAY,EAAE,QAAQ,GAAG,gBAAgB,EAAE,UAAU,aAAa,6BAA0C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/koa",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "Koa middleware, body parsing, and utilities for ServerKit",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -41,7 +41,7 @@
41
41
  "@maroonedsoftware/multipart": "1.0.2",
42
42
  "@maroonedsoftware/logger": "1.0.0",
43
43
  "@maroonedsoftware/utilities": "1.1.0",
44
- "@maroonedsoftware/authentication": "0.0.1"
44
+ "@maroonedsoftware/authentication": "0.1.0"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@koa/cors": "^5.0.0",
@@ -57,8 +57,8 @@
57
57
  "@types/koa__cors": "^5.0.1",
58
58
  "@types/qs": "^6.15.0",
59
59
  "koa": "^3.1.2",
60
- "@repo/config-typescript": "0.0.0",
61
- "@repo/config-eslint": "0.1.0"
60
+ "@repo/config-eslint": "0.1.0",
61
+ "@repo/config-typescript": "0.0.0"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "tsup src/index.ts --format esm --sourcemap --dts && tsc --emitDeclarationOnly --declaration",