@venizia/ignis 0.4.8-4 → 0.4.8-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
  2. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
  3. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
  4. package/dist/esm/components/auth/authenticate/component.js +37 -1
  5. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  6. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
  7. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
  8. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  9. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +2 -2
  10. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
  11. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +10 -3
  12. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
  13. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
  14. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
  15. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
  16. package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
  17. package/dist/esm/components/auth/authenticate/services/index.js +1 -0
  18. package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
  19. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +31 -0
  20. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +99 -0
  21. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
  22. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
  23. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
  24. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
  25. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
  26. package/dist/esm/components/health-check/reporter.js +2 -2
  27. package/dist/esm/components/health-check/reporter.js.map +1 -1
  28. package/dist/esm/components/static-asset/common/constants.d.ts +2 -0
  29. package/dist/esm/components/static-asset/common/constants.js +2 -0
  30. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  31. package/dist/esm/components/static-asset/common/types.d.ts +6 -0
  32. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  33. package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
  34. package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
  35. package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
  36. package/dist/esm/components/static-asset/controller/factory.js +16 -8
  37. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  38. package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
  39. package/dist/esm/components/static-asset/controller/route-options.js +16 -3
  40. package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
  41. package/dist/esm/components/static-asset/ingest.d.ts +2 -2
  42. package/dist/esm/components/static-asset/ingest.js +2 -2
  43. package/dist/esm/components/static-asset/ingest.js.map +1 -1
  44. package/dist/presets/app/preset.json +3 -3
  45. package/dist/presets/lib/preset.json +2 -2
  46. package/package.json +6 -6
@@ -5,6 +5,7 @@ import { type TContext } from '@venizia/ignis-kernel';
5
5
  /** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */
6
6
  export declare class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {
7
7
  static readonly REQUEST_ID_KEY = "requestId";
8
+ private static readonly CALLBACK_PARAMETERS;
8
9
  private isDebugMode;
9
10
  /**
10
11
  * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this
@@ -1,13 +1,14 @@
1
1
  import { NetworkUtility } from '../../../utilities/network.utility.js';
2
2
  import { Environment } from '@venizia/ignis-helpers';
3
3
  import { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';
4
- import { HTTP } from '@venizia/ignis-helpers/common';
4
+ import { HTTP, REDACTED } from '@venizia/ignis-helpers/common';
5
5
  import { createMiddleware } from 'hono/factory';
6
6
  import { REQUEST_ID_KEY, RequestErrors } from '@venizia/ignis-kernel';
7
7
  const TEXT_CONTENT_TYPE_PREFIX = 'text/';
8
8
  /** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */
9
9
  export class RequestSpyMiddleware extends BaseHelper {
10
10
  static { this.REQUEST_ID_KEY = REQUEST_ID_KEY; }
11
+ static { this.CALLBACK_PARAMETERS = new Set(['code', 'state']); }
11
12
  /**
12
13
  * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this
13
14
  * framework recognises as a development one enables body logging.
@@ -82,7 +83,13 @@ export class RequestSpyMiddleware extends BaseHelper {
82
83
  const path = req.path ?? '/';
83
84
  // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.
84
85
  const clientIp = incomingIp ?? forwardedIp ?? 'unknown';
85
- const query = req.query() ?? {};
86
+ // `code` and `state` are credentials in an OAuth callback and too common as plain names to mask everywhere.
87
+ const query = Object.fromEntries(Object.entries(req.query() ?? {}).map(([key, value]) => {
88
+ return [
89
+ key,
90
+ RequestSpyMiddleware.CALLBACK_PARAMETERS.has(key.toLowerCase()) ? REDACTED : value,
91
+ ];
92
+ }));
86
93
  if (this.isDebugMode) {
87
94
  const body = await this.parseBody({ req });
88
95
  this.logger.info('[%s][%s][=>] %s %s | query: %j | body: %j', requestId, clientIp, method.padEnd(8, ' '), path, query, body);
@@ -1 +1 @@
1
- {"version":3,"file":"request-spy.middleware.js","sourceRoot":"","sources":["../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F;gBACzF,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,EAAE,CAAC;oBACxF,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;gBAChC,CAAC;gBAED,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,gCAAgC,EAChC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,KAAK,CACN,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,EAAE,CAAC;YAEb,MAAM,QAAQ,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACpD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oCAAoC,EACpC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,QAAQ,CACT,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { NetworkUtility } from '@/utilities/network.utility';\nimport { Environment } from '@venizia/ignis-helpers';\nimport { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport { createMiddleware } from 'hono/factory';\nimport type { MiddlewareHandler } from 'hono/types';\nimport { REQUEST_ID_KEY, RequestErrors, type TContext } from '@venizia/ignis-kernel';\n\nconst TEXT_CONTENT_TYPE_PREFIX = 'text/';\n\n/** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */\nexport class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {\n static readonly REQUEST_ID_KEY = REQUEST_ID_KEY;\n\n private isDebugMode: boolean;\n\n /**\n * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this\n * framework recognises as a development one enables body logging.\n *\n * The previous test was `env !== 'production'`, which enabled it for an unset `NODE_ENV` and for\n * every pre-production name that carries real user data - `staging`, `uat`, `alpha`, `beta`, and\n * the abbreviation `prod`. `development-envs.test.ts` pins those as NOT development for exactly\n * that reason. Redaction is no defence here: it masks secret-SHAPED keys, so `nationalId`,\n * `cardNumber` and `ssn` were written verbatim.\n */\n constructor() {\n super({ scope: 'SpyMW' });\n const env = Environment.ambient?.toLowerCase();\n this.isDebugMode = !!env && EnvironmentNames.DEVELOPMENT_ENVS.has(env);\n }\n\n /** Parses the body by Content-Type without draining it for the handler: JSON and form bodies go through the request cache, `text/*` is read from a clone (from the cache once something read it), and any other type is described by its size, never read. */\n async parseBody(opts: { req: TContext['req'] }): Promise<unknown> {\n const contentType = opts.req.header(HTTP.Headers.CONTENT_TYPE);\n\n if (!contentType) {\n return null;\n }\n\n // Only an explicit zero short-circuits: a CHUNKED request carries no Content-Length, so gating on the header's presence would skip every streamed body and let a malformed one detonate deeper as a 500.\n const contentLength = opts.req.header(HTTP.Headers.CONTENT_LENGTH);\n\n if (contentLength === '0' || !opts.req.raw.body) {\n return null;\n }\n\n try {\n if (contentType.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n const rs = await opts.req.json();\n\n return rs;\n }\n\n if (\n contentType.includes(HTTP.HeaderValues.MULTIPART_FORM_DATA) ||\n contentType.includes(HTTP.HeaderValues.APPLICATION_FORM_URLENCODED)\n ) {\n const rs = await opts.req.parseBody();\n\n return rs;\n }\n\n if (contentType === HTTP.HeaderValues.APPLICATION_OCTET_STREAM) {\n return opts.req.raw.body;\n }\n\n // Anything else is read, if at all, from a clone: a handler may stream `req.raw.body` on (an upload proxy), and reading the request itself would drain it and mangle binary bytes.\n // A body an earlier middleware read cannot be cloned; Hono's cache serves it instead.\n if (contentType.startsWith(TEXT_CONTENT_TYPE_PREFIX)) {\n let rs: string;\n\n if (opts.req.raw.bodyUsed) {\n const cached = await opts.req.text();\n rs = cached;\n } else {\n const cloned = await opts.req.raw.clone().text();\n rs = cloned;\n }\n\n return rs;\n }\n\n return `<${contentLength ?? 'unknown'} bytes, ${contentType}>`;\n } catch {\n throw getError({\n error: RequestErrors.BODY_MALFORMED,\n message: 'Malformed Body Payload',\n });\n }\n }\n\n /** Returns a Hono middleware that logs request details and duration. */\n value() {\n return createMiddleware(async (context, next) => {\n const t = performance.now();\n const { req } = context;\n\n const requestId = context.get(RequestSpyMiddleware.REQUEST_ID_KEY);\n const incomingIp = NetworkUtility.getIncomingIp(context);\n const forwardedIp = req.header('x-real-ip') ?? req.header('x-forwarded-for') ?? null;\n\n const method = req.method;\n const path = req.path ?? '/';\n\n // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.\n const clientIp = incomingIp ?? forwardedIp ?? 'unknown';\n const query = req.query() ?? {};\n\n if (this.isDebugMode) {\n const body = await this.parseBody({ req });\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j | body: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n body,\n );\n } else {\n // Only JSON is parsed here: its clean 400 on a malformed body is a contract. Any other body\n // would be read for a log line that never prints it, before the route's own size checks.\n if (req.header(HTTP.Headers.CONTENT_TYPE)?.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n await this.parseBody({ req });\n }\n\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n );\n }\n\n await next();\n\n const duration = (performance.now() - t).toFixed(2);\n this.logger.info(\n '[%s][%s][<=] %s %s | Took: %s (ms)',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n duration,\n );\n });\n }\n}\n"]}
1
+ {"version":3,"file":"request-spy.middleware.js","sourceRoot":"","sources":["../../../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AAC,CAAC,KAAK;iBACnF,CAAC;YACJ,CAAC,CAAC,CACH,CAAC;YAEF,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;gBACrB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;gBAC3C,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,2CAA2C,EAC3C,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,KAAK,EACL,IAAI,CACL,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,4FAA4F;gBAC5F,yFAAyF;gBACzF,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,EAAE,CAAC;oBACxF,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;gBAChC,CAAC;gBAED,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,gCAAgC,EAChC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,KAAK,CACN,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,EAAE,CAAC;YAEb,MAAM,QAAQ,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACpD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oCAAoC,EACpC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,QAAQ,CACT,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { NetworkUtility } from '@/utilities/network.utility';\nimport { Environment } from '@venizia/ignis-helpers';\nimport { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, REDACTED } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport { createMiddleware } from 'hono/factory';\nimport type { MiddlewareHandler } from 'hono/types';\nimport { REQUEST_ID_KEY, RequestErrors, type TContext } from '@venizia/ignis-kernel';\n\nconst TEXT_CONTENT_TYPE_PREFIX = 'text/';\n\n/** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */\nexport class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {\n static readonly REQUEST_ID_KEY = REQUEST_ID_KEY;\n private static readonly CALLBACK_PARAMETERS = new Set(['code', 'state']);\n\n private isDebugMode: boolean;\n\n /**\n * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this\n * framework recognises as a development one enables body logging.\n *\n * The previous test was `env !== 'production'`, which enabled it for an unset `NODE_ENV` and for\n * every pre-production name that carries real user data - `staging`, `uat`, `alpha`, `beta`, and\n * the abbreviation `prod`. `development-envs.test.ts` pins those as NOT development for exactly\n * that reason. Redaction is no defence here: it masks secret-SHAPED keys, so `nationalId`,\n * `cardNumber` and `ssn` were written verbatim.\n */\n constructor() {\n super({ scope: 'SpyMW' });\n const env = Environment.ambient?.toLowerCase();\n this.isDebugMode = !!env && EnvironmentNames.DEVELOPMENT_ENVS.has(env);\n }\n\n /** Parses the body by Content-Type without draining it for the handler: JSON and form bodies go through the request cache, `text/*` is read from a clone (from the cache once something read it), and any other type is described by its size, never read. */\n async parseBody(opts: { req: TContext['req'] }): Promise<unknown> {\n const contentType = opts.req.header(HTTP.Headers.CONTENT_TYPE);\n\n if (!contentType) {\n return null;\n }\n\n // Only an explicit zero short-circuits: a CHUNKED request carries no Content-Length, so gating on the header's presence would skip every streamed body and let a malformed one detonate deeper as a 500.\n const contentLength = opts.req.header(HTTP.Headers.CONTENT_LENGTH);\n\n if (contentLength === '0' || !opts.req.raw.body) {\n return null;\n }\n\n try {\n if (contentType.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n const rs = await opts.req.json();\n\n return rs;\n }\n\n if (\n contentType.includes(HTTP.HeaderValues.MULTIPART_FORM_DATA) ||\n contentType.includes(HTTP.HeaderValues.APPLICATION_FORM_URLENCODED)\n ) {\n const rs = await opts.req.parseBody();\n\n return rs;\n }\n\n if (contentType === HTTP.HeaderValues.APPLICATION_OCTET_STREAM) {\n return opts.req.raw.body;\n }\n\n // Anything else is read, if at all, from a clone: a handler may stream `req.raw.body` on (an upload proxy), and reading the request itself would drain it and mangle binary bytes.\n // A body an earlier middleware read cannot be cloned; Hono's cache serves it instead.\n if (contentType.startsWith(TEXT_CONTENT_TYPE_PREFIX)) {\n let rs: string;\n\n if (opts.req.raw.bodyUsed) {\n const cached = await opts.req.text();\n rs = cached;\n } else {\n const cloned = await opts.req.raw.clone().text();\n rs = cloned;\n }\n\n return rs;\n }\n\n return `<${contentLength ?? 'unknown'} bytes, ${contentType}>`;\n } catch {\n throw getError({\n error: RequestErrors.BODY_MALFORMED,\n message: 'Malformed Body Payload',\n });\n }\n }\n\n /** Returns a Hono middleware that logs request details and duration. */\n value() {\n return createMiddleware(async (context, next) => {\n const t = performance.now();\n const { req } = context;\n\n const requestId = context.get(RequestSpyMiddleware.REQUEST_ID_KEY);\n const incomingIp = NetworkUtility.getIncomingIp(context);\n const forwardedIp = req.header('x-real-ip') ?? req.header('x-forwarded-for') ?? null;\n\n const method = req.method;\n const path = req.path ?? '/';\n\n // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.\n const clientIp = incomingIp ?? forwardedIp ?? 'unknown';\n // `code` and `state` are credentials in an OAuth callback and too common as plain names to mask everywhere.\n const query = Object.fromEntries(\n Object.entries(req.query() ?? {}).map(([key, value]) => {\n return [\n key,\n RequestSpyMiddleware.CALLBACK_PARAMETERS.has(key.toLowerCase()) ? REDACTED : value,\n ];\n }),\n );\n\n if (this.isDebugMode) {\n const body = await this.parseBody({ req });\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j | body: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n body,\n );\n } else {\n // Only JSON is parsed here: its clean 400 on a malformed body is a contract. Any other body\n // would be read for a log line that never prints it, before the route's own size checks.\n if (req.header(HTTP.Headers.CONTENT_TYPE)?.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n await this.parseBody({ req });\n }\n\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n );\n }\n\n await next();\n\n const duration = (performance.now() - t).toFixed(2);\n this.logger.info(\n '[%s][%s][<=] %s %s | Took: %s (ms)',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n duration,\n );\n });\n }\n}\n"]}
@@ -16,8 +16,9 @@ import { Binding } from '@venizia/ignis-inversion';
16
16
  import { AuthenticateBindingKeys, Authentication, AuthenticationStrategyRegistry, BaseComponent, controller, CoreBindings, inject, JOSEStandards, JWKSKeyFormats, JWKSModes, ServiceAssertion, } from '@venizia/ignis-kernel';
17
17
  import { AuthControllerFactory, JWKSController } from './controllers/index.js';
18
18
  import { ServiceCertsController } from './controllers/service-certs/index.js';
19
- import { BasicTokenService, JWKSIssuerTokenService, JWKSVerifierTokenService, JWSTokenService, } from './services/index.js';
19
+ import { AbstractBearerTokenService, BasicTokenService, JWKSIssuerTokenService, JWKSVerifierTokenService, JWSTokenService, } from './services/index.js';
20
20
  import { JoseLoader } from './services/jose-loader.js';
21
+ import { JWKSUrlPolicy } from './services/jwks-url-policy.js';
21
22
  import { ServiceAssertionSignerService } from './services/service/signer.service.js';
22
23
  import { ServiceAssertionVerifierService } from './services/service/verifier.service.js';
23
24
  import { ServiceAuthenticationStrategy } from './strategies/service.strategy.js';
@@ -118,6 +119,13 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
118
119
  message: '[defineJWSAuth] getTokenExpiresFn is required',
119
120
  });
120
121
  }
122
+ // The boot refuses a configuration without claims, and a service refuses the same when built.
123
+ AbstractBearerTokenService.resolveClaimsConfig({
124
+ scope: 'defineJWSAuth',
125
+ options: jwsOptions,
126
+ pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],
127
+ });
128
+ JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });
121
129
  this.application
122
130
  .bind({ key: AuthenticateBindingKeys.JWT_OPTIONS })
123
131
  .toValue(jwsOptions);
@@ -147,6 +155,11 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
147
155
  message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',
148
156
  });
149
157
  }
158
+ AbstractBearerTokenService.resolveClaimsConfig({
159
+ scope: 'defineJWKSAuth',
160
+ options: issuerOpts,
161
+ pinnedAlgorithms: [issuerOpts.algorithm],
162
+ });
150
163
  this.application
151
164
  .bind({ key: AuthenticateBindingKeys.JWKS_OPTIONS })
152
165
  .toValue(issuerOpts);
@@ -164,6 +177,16 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
164
177
  if (!verifierOpts.jwksUrl) {
165
178
  throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });
166
179
  }
180
+ AbstractBearerTokenService.resolveClaimsConfig({
181
+ scope: 'defineJWKSAuth',
182
+ options: verifierOpts,
183
+ });
184
+ JWKSUrlPolicy.assertUrl({
185
+ scope: 'defineJWKSAuth',
186
+ label: 'jwksUrl',
187
+ url: verifierOpts.jwksUrl,
188
+ hosts: verifierOpts.jwks?.hosts?.http,
189
+ });
167
190
  this.application
168
191
  .bind({ key: AuthenticateBindingKeys.JWKS_OPTIONS })
169
192
  .toValue(verifierOpts);
@@ -205,6 +228,19 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
205
228
  message: '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',
206
229
  });
207
230
  }
231
+ // A caller's key set decides who may call: https, loopback, or a host named in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.
232
+ JWKSUrlPolicy.resolveHttpHosts({
233
+ scope: 'defineServiceAuth',
234
+ hosts: serviceOptions.jwks?.hosts?.http,
235
+ });
236
+ for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {
237
+ JWKSUrlPolicy.assertUrl({
238
+ scope: 'defineServiceAuth',
239
+ label: `callers[${JSON.stringify(caller)}].jwksUrl`,
240
+ url: typeof entry === 'string' ? entry : entry.jwksUrl,
241
+ hosts: serviceOptions.jwks?.hosts?.http,
242
+ });
243
+ }
208
244
  this.application.service(ServiceAssertionVerifierService);
209
245
  if (serviceOptions.keys) {
210
246
  this.application.service(ServiceAssertionSignerService);
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,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K,CAAC,0BAA0B,CAAC,CAAC;YAE/E,OAAO;QACT,CAAC;QAED,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,0EAA0E;aACpF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,cAAc,GAAG,qBAAqB,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAChF,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AAnTY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAmTjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
1
+ {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,0BAA0B,EAC1B,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAE9E,MAAM,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,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAE/E,OAAO;QACT,CAAC;QAED,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,0EAA0E;aACpF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,cAAc,GAAG,qBAAqB,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAChF,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AA7VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA6VjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n AbstractBearerTokenService,\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { JWKSUrlPolicy } from './services/jwks-url-policy';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: issuerOpts,\n pinnedAlgorithms: [issuerOpts.algorithm],\n });\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: verifierOpts,\n });\n\n JWKSUrlPolicy.assertUrl({\n scope: 'defineJWKSAuth',\n label: 'jwksUrl',\n url: verifierOpts.jwksUrl,\n hosts: verifierOpts.jwks?.hosts?.http,\n });\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n // A caller's key set decides who may call: https, loopback, or a host named in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveHttpHosts({\n scope: 'defineServiceAuth',\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n\n for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {\n JWKSUrlPolicy.assertUrl({\n scope: 'defineServiceAuth',\n label: `callers[${JSON.stringify(caller)}].jwksUrl`,\n url: typeof entry === 'string' ? entry : entry.jwksUrl,\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
@@ -1,10 +1,24 @@
1
1
  import type { AESAlgorithmType } from '@venizia/ignis-helpers';
2
2
  import { AES } from '@venizia/ignis-helpers';
3
3
  import type { ValueOrPromise } from '@venizia/ignis-helpers/common';
4
- import type { IJWTIssueClaims, IJWTSignOptions, IJWTTokenPayload, IPayloadFieldCodec, TContext, TGetTokenExpiresFn } from '@venizia/ignis-kernel';
4
+ import type { IJWTClaimsOptions, IJWTIssueClaims, IJWTTokenPayload, IPayloadFieldCodec, TContext, TGetTokenExpiresFn } from '@venizia/ignis-kernel';
5
5
  import { BaseService } from '@venizia/ignis-kernel';
6
6
  import type { Env } from 'hono';
7
- import type { JWTPayload, JWTVerifyResult, SignJWT } from 'jose';
7
+ import type { JWTPayload, JWTVerifyOptions, JWTVerifyResult, SignJWT } from 'jose';
8
+ /** What a token service is configured with for claims: the required `claims`, the `verify` checks, and the removed `sign` it refuses. */
9
+ export interface IClaimsConfigSource {
10
+ claims?: unknown;
11
+ verify?: unknown;
12
+ /** Removed: refused with a message that points to `claims`. */
13
+ sign?: unknown;
14
+ }
15
+ /** What {@link AbstractBearerTokenService.resolveClaimsConfig} answers: the validated claims and the verify options jose receives. */
16
+ export interface IResolvedClaimsConfig {
17
+ claims: IJWTClaimsOptions;
18
+ verify: JWTVerifyOptions & {
19
+ algorithms: string[];
20
+ };
21
+ }
8
22
  /** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */
9
23
  export declare abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {
10
24
  /** Standard JWT fields that are never encrypted. */
@@ -12,14 +26,36 @@ export declare abstract class AbstractBearerTokenService<E extends Env = Env> ex
12
26
  protected aes: AES | null;
13
27
  protected applicationSecret: string | null;
14
28
  protected fieldCodecs: Map<string, IPayloadFieldCodec>;
15
- /** Configured `iss` / `aud`. Authoritative over anything the payload carries. */
16
- protected signOptions: IJWTSignOptions | null;
29
+ /** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */
30
+ protected claimOptions: IJWTClaimsOptions | null;
31
+ /** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */
32
+ protected verifyOptions: JWTVerifyOptions | null;
33
+ /** The keys a `claims` object may hold. */
34
+ static readonly CLAIM_KEYS: ReadonlyArray<string>;
35
+ /**
36
+ * Validates the claims configuration of a token service and answers what the service uses. It throws, naming the
37
+ * key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a
38
+ * non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /
39
+ * `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it
40
+ * no `aud` is stamped and none is checked.
41
+ * `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.
42
+ * The component calls it at boot, and a service calls it when it is built, so neither can start without them.
43
+ */
44
+ static resolveClaimsConfig(opts: {
45
+ scope: string;
46
+ options: IClaimsConfigSource;
47
+ pinnedAlgorithms?: string[];
48
+ }): IResolvedClaimsConfig;
49
+ /** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */
50
+ protected configureClaims(opts: {
51
+ options: IClaimsConfigSource;
52
+ pinnedAlgorithms?: string[];
53
+ }): void;
17
54
  /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */
18
55
  protected configurePayloadEncryption(opts: {
19
56
  aesAlgorithm?: AESAlgorithmType;
20
57
  applicationSecret?: string;
21
58
  fieldCodecs?: IPayloadFieldCodec[];
22
- sign?: IJWTSignOptions;
23
59
  }): void;
24
60
  extractCredentials(context: TContext<E, string>): {
25
61
  type: string;
@@ -29,17 +65,32 @@ export declare abstract class AbstractBearerTokenService<E extends Env = Env> ex
29
65
  type: string;
30
66
  token: string;
31
67
  }): Promise<IJWTTokenPayload>;
68
+ /**
69
+ * A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service
70
+ * assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.
71
+ */
72
+ protected assertNotServiceAssertion(opts: {
73
+ token: string;
74
+ }): Promise<void>;
32
75
  generate(opts: {
33
76
  payload: IJWTTokenPayload;
34
77
  getTokenExpiresFn?: TGetTokenExpiresFn;
35
78
  /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */
36
79
  claims?: IJWTIssueClaims;
37
80
  }): Promise<string>;
81
+ /** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */
38
82
  protected serializeField(opts: {
39
83
  key: string;
40
84
  value: any;
41
85
  }): string;
86
+ /**
87
+ * With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;
88
+ * without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,
89
+ * so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An
90
+ * `undefined` claim is skipped, as JSON drops it.
91
+ */
42
92
  encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>>;
93
+ /** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */
43
94
  protected deserializeField(opts: {
44
95
  key: string;
45
96
  value: string;
@@ -1,7 +1,8 @@
1
1
  import { AES } from '@venizia/ignis-helpers';
2
2
  import { HTTP } from '@venizia/ignis-helpers/common';
3
- import { getError } from '@venizia/ignis-helpers/core';
4
- import { Authentication, AuthenticationErrors, BaseService } from '@venizia/ignis-kernel';
3
+ import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
4
+ import { Authentication, AuthenticationErrors, BaseService, ServiceAssertion, } from '@venizia/ignis-kernel';
5
+ import { JoseLoader } from '../jose-loader.js';
5
6
  /** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */
6
7
  export class AbstractBearerTokenService extends BaseService {
7
8
  constructor() {
@@ -9,8 +10,10 @@ export class AbstractBearerTokenService extends BaseService {
9
10
  this.aes = null;
10
11
  this.applicationSecret = null;
11
12
  this.fieldCodecs = new Map();
12
- /** Configured `iss` / `aud`. Authoritative over anything the payload carries. */
13
- this.signOptions = null;
13
+ /** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */
14
+ this.claimOptions = null;
15
+ /** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */
16
+ this.verifyOptions = null;
14
17
  }
15
18
  /** Standard JWT fields that are never encrypted. */
16
19
  static { this.JWT_COMMON_FIELDS = new Set([
@@ -22,10 +25,85 @@ export class AbstractBearerTokenService extends BaseService {
22
25
  'exp',
23
26
  'iat',
24
27
  ]); }
28
+ /** The keys a `claims` object may hold. */
29
+ static { this.CLAIM_KEYS = ['issuer', 'audience']; }
30
+ /**
31
+ * Validates the claims configuration of a token service and answers what the service uses. It throws, naming the
32
+ * key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a
33
+ * non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /
34
+ * `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it
35
+ * no `aud` is stamped and none is checked.
36
+ * `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.
37
+ * The component calls it at boot, and a service calls it when it is built, so neither can start without them.
38
+ */
39
+ static resolveClaimsConfig(opts) {
40
+ const { scope, options, pinnedAlgorithms } = opts;
41
+ const fail = (detail) => getError({
42
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
43
+ message: `[${scope}] ${detail}`,
44
+ });
45
+ if (options.sign !== undefined) {
46
+ throw fail('`sign` was removed | put the issuer and the audience in `claims: { issuer, audience }`: they are stamped on every token and required on every verified one');
47
+ }
48
+ if (options.verify !== undefined && !RecordUtility.isPlainRecord(options.verify)) {
49
+ throw fail('verify must be an object | its checks (maxTokenAge, subject, ...) would be dropped silently');
50
+ }
51
+ const verify = RecordUtility.isPlainRecord(options.verify) ? options.verify : {};
52
+ for (const key of AbstractBearerTokenService.CLAIM_KEYS) {
53
+ if (key in verify) {
54
+ throw fail(`verify.${key} was removed | set claims.${key}: it is stamped on every token and required on every verified one`);
55
+ }
56
+ }
57
+ const { claims } = options;
58
+ if (!RecordUtility.isPlainRecord(claims)) {
59
+ throw fail('claims is required | pass claims: { issuer: string, audience: string | string[] }: a token signed with the same key for another purpose must not authenticate a request');
60
+ }
61
+ const unknown = Object.keys(claims).filter((key) => !AbstractBearerTokenService.CLAIM_KEYS.includes(key));
62
+ if (unknown.length > 0) {
63
+ throw fail(`claims holds unknown keys ${JSON.stringify(unknown)} | accepted: ${AbstractBearerTokenService.CLAIM_KEYS.join(', ')}`);
64
+ }
65
+ const { issuer, audience } = claims;
66
+ const isName = (value) => typeof value === 'string' && value.trim().length > 0;
67
+ if (!isName(issuer)) {
68
+ throw fail('claims.issuer is required | a non-empty string');
69
+ }
70
+ // Optional, but a present value is checked: `null`, `''` and `[]` are mistakes, not "no audience".
71
+ if (audience !== undefined &&
72
+ !isName(audience) &&
73
+ !(Array.isArray(audience) && audience.length > 0 && audience.every(isName))) {
74
+ throw fail('claims.audience must be a non-empty string or a non-empty list of them | or leave it out');
75
+ }
76
+ const resolvedAudience = Array.isArray(audience) ? [...audience] : audience;
77
+ const algorithms = verify.algorithms ?? pinnedAlgorithms;
78
+ if (!Array.isArray(algorithms) || algorithms.length === 0 || !algorithms.every(isName)) {
79
+ throw fail("verify.algorithms is required | the accepted JWS algorithms, for example ['RS256']: a verifier cannot know what the issuer signs with");
80
+ }
81
+ if (algorithms.some((algorithm) => algorithm.trim().toLowerCase() === 'none')) {
82
+ throw fail("the algorithm 'none' is refused | a token with no signature verifies nothing");
83
+ }
84
+ return {
85
+ claims: { issuer, ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }) },
86
+ verify: {
87
+ ...verify,
88
+ issuer,
89
+ ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }),
90
+ algorithms: [...algorithms],
91
+ },
92
+ };
93
+ }
94
+ /** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */
95
+ configureClaims(opts) {
96
+ const resolved = AbstractBearerTokenService.resolveClaimsConfig({
97
+ scope: this.scope,
98
+ options: opts.options,
99
+ pinnedAlgorithms: opts.pinnedAlgorithms,
100
+ });
101
+ this.claimOptions = resolved.claims;
102
+ this.verifyOptions = resolved.verify;
103
+ }
25
104
  /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */
26
105
  configurePayloadEncryption(opts) {
27
- const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs, sign } = opts;
28
- this.signOptions = sign ?? null;
106
+ const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs } = opts;
29
107
  if (fieldCodecs) {
30
108
  for (const codec of fieldCodecs) {
31
109
  this.fieldCodecs.set(codec.key, codec);
@@ -72,6 +150,7 @@ export class AbstractBearerTokenService extends BaseService {
72
150
  });
73
151
  }
74
152
  try {
153
+ await this.assertNotServiceAssertion({ token });
75
154
  const result = await this.doVerify(token);
76
155
  return result;
77
156
  }
@@ -85,6 +164,21 @@ export class AbstractBearerTokenService extends BaseService {
85
164
  });
86
165
  }
87
166
  }
167
+ /**
168
+ * A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service
169
+ * assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.
170
+ */
171
+ async assertNotServiceAssertion(opts) {
172
+ const { decodeProtectedHeader } = await JoseLoader.load();
173
+ const { typ } = decodeProtectedHeader(opts.token);
174
+ const kind = typeof typ === 'string' ? typ.toLowerCase().replace(/^application\//, '') : '';
175
+ if (kind === ServiceAssertion.TYP) {
176
+ throw getError({
177
+ error: AuthenticationErrors.TOKEN_INVALID,
178
+ message: '[verify] A service assertion is not a user token',
179
+ });
180
+ }
181
+ }
88
182
  async generate(opts) {
89
183
  const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;
90
184
  if (!payload) {
@@ -107,14 +201,21 @@ export class AbstractBearerTokenService extends BaseService {
107
201
  });
108
202
  }
109
203
  }
204
+ /** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */
110
205
  serializeField(opts) {
111
206
  const { key, value } = opts;
112
- const codec = this.fieldCodecs.get(key);
207
+ const codec = value === null ? undefined : this.fieldCodecs.get(key);
113
208
  if (codec) {
114
209
  return codec.serialize({ value });
115
210
  }
116
211
  return JSON.stringify(value);
117
212
  }
213
+ /**
214
+ * With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;
215
+ * without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,
216
+ * so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An
217
+ * `undefined` claim is skipped, as JSON drops it.
218
+ */
118
219
  async encryptPayload(payload) {
119
220
  if (!this.aes || !this.applicationSecret) {
120
221
  return payload;
@@ -127,8 +228,10 @@ export class AbstractBearerTokenService extends BaseService {
127
228
  rs[key] = value;
128
229
  continue;
129
230
  }
130
- // NOTE: Skip undefined or null values because they cannot be encrypted
131
- if (value === undefined || value === null) {
231
+ // Only `undefined` is skipped: JSON drops it too, so the claim is absent either way. `null` is a value, and
232
+ // `serializeField` writes it as `null`, which `deserializeField` reads back, so an encrypted token decodes the
233
+ // same payload as a plain one.
234
+ if (value === undefined) {
132
235
  continue;
133
236
  }
134
237
  const encryptedKey = await this.aes.encrypt({
@@ -144,9 +247,10 @@ export class AbstractBearerTokenService extends BaseService {
144
247
  }
145
248
  return rs;
146
249
  }
250
+ /** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */
147
251
  deserializeField(opts) {
148
252
  const { key, value } = opts;
149
- const codec = this.fieldCodecs.get(key);
253
+ const codec = value === 'null' ? undefined : this.fieldCodecs.get(key);
150
254
  if (codec) {
151
255
  return codec.deserialize({ raw: value });
152
256
  }
@@ -165,7 +269,7 @@ export class AbstractBearerTokenService extends BaseService {
165
269
  */
166
270
  applySignClaims(opts) {
167
271
  const { signer, payload, claims } = opts;
168
- const configured = this.signOptions;
272
+ const configured = this.claimOptions;
169
273
  const issuer = claims?.issuer ?? configured?.issuer;
170
274
  const audience = claims?.audience ?? configured?.audience;
171
275
  const logger = this.logger.for(this.applySignClaims.name);