@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
@@ -1 +1 @@
1
- {"version":3,"file":"abstract.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/abstract.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAE7C,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASvD,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAI1F,gGAAgG;AAChG,MAAM,OAAgB,0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B,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YAEH,EAAE,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QACzF,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC","sourcesContent":["import type { AESAlgorithmType } from '@venizia/ignis-helpers';\nimport { AES } from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type {\n IJWTIssueClaims,\n IJWTSignOptions,\n IJWTTokenPayload,\n IPayloadFieldCodec,\n TContext,\n TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { Authentication, AuthenticationErrors, BaseService } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport type { JWTPayload, JWTVerifyResult, SignJWT } from 'jose';\n\n/** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */\nexport abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {\n /** Standard JWT fields that are never encrypted. */\n static readonly JWT_COMMON_FIELDS = new Set<keyof JWTPayload>([\n 'iss',\n 'sub',\n 'aud',\n 'jti',\n 'nbf',\n 'exp',\n 'iat',\n ]);\n\n protected aes: AES | null = null;\n protected applicationSecret: string | null = null;\n protected fieldCodecs: Map<string, IPayloadFieldCodec> = new Map();\n\n /** Configured `iss` / `aud`. Authoritative over anything the payload carries. */\n protected signOptions: IJWTSignOptions | null = null;\n\n /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */\n protected configurePayloadEncryption(opts: {\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n sign?: IJWTSignOptions;\n }): void {\n const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs, sign } = opts;\n\n this.signOptions = sign ?? null;\n\n if (fieldCodecs) {\n for (const codec of fieldCodecs) {\n this.fieldCodecs.set(codec.key, codec);\n }\n }\n\n if (!applicationSecret) {\n return;\n }\n\n this.aes = AES.withAlgorithm(aesAlgorithm);\n this.applicationSecret = applicationSecret;\n }\n\n extractCredentials(context: TContext<E, string>): { type: string; token: string } {\n const request = context.req;\n\n const authHeaderValue = request.header('Authorization');\n\n if (!authHeaderValue) {\n throw getError({\n error: AuthenticationErrors.HEADER_MISSING,\n message: 'Unauthorized user! Missing authorization header',\n });\n }\n\n if (!authHeaderValue.startsWith(Authentication.TYPE_BEARER)) {\n throw getError({\n error: AuthenticationErrors.SCHEME_INVALID,\n message: 'Unauthorized user! Invalid schema of request token!',\n });\n }\n\n const parts = authHeaderValue.split(' ');\n\n if (parts.length !== 2) {\n throw getError({\n error: AuthenticationErrors.HEADER_MALFORMED,\n message: `Authorization header value is invalid format. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`,\n });\n }\n\n const [tokenType, tokenValue] = parts;\n\n return { type: tokenType, token: tokenValue };\n }\n\n async verify(opts: { type: string; token: string }): Promise<IJWTTokenPayload> {\n const { token } = opts;\n\n if (!token) {\n this.logger.for(this.verify.name).error('Missing token for validating request!');\n throw getError({\n error: AuthenticationErrors.TOKEN_MISSING,\n message: '[verify] Invalid request token!',\n });\n }\n\n try {\n const result = await this.doVerify(token);\n\n return result;\n } catch (error) {\n // No log here - `cause` carries the reason (JWTExpired, signature mismatch) to the error handler, which logs the request once. An expired token is the caller's problem, hence `warn`.\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] Invalid or expired token',\n logLevel: 'warn',\n cause: error,\n });\n }\n }\n\n async generate(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn?: TGetTokenExpiresFn;\n /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */\n claims?: IJWTIssueClaims;\n }): Promise<string> {\n const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;\n\n if (!payload) {\n throw getError({\n error: AuthenticationErrors.TOKEN_PAYLOAD_INVALID,\n message: '[generate] Invalid token payload!',\n });\n }\n\n const signer = await this.getSigner({ payload, getTokenExpiresFn, claims });\n\n try {\n const result = await this.getSigningKey();\n const rs = await signer.sign(result);\n\n return rs;\n } catch (error) {\n this.logger.for(this.generate.name).error('Failed to generate token | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[generate] Failed to generate token',\n });\n }\n }\n\n protected serializeField(opts: { key: string; value: any }): string {\n const { key, value } = opts;\n const codec = this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.serialize({ value });\n }\n\n return JSON.stringify(value);\n }\n\n async encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, string> = {};\n\n const keys = Object.keys(payload);\n\n for (const key of keys) {\n const value = payload[key];\n\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = value;\n continue;\n }\n\n // NOTE: Skip undefined or null values because they cannot be encrypted\n if (value === undefined || value === null) {\n continue;\n }\n\n const encryptedKey = await this.aes.encrypt({\n message: key,\n secret: this.applicationSecret,\n });\n\n const serialized = this.serializeField({ key, value });\n\n const encryptedValue = await this.aes.encrypt({\n message: serialized,\n secret: this.applicationSecret,\n });\n rs[encryptedKey] = encryptedValue;\n }\n\n return rs;\n }\n\n protected deserializeField(opts: { key: string; value: string }) {\n const { key, value } = opts;\n const codec = this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.deserialize({ raw: value });\n }\n\n return JSON.parse(value);\n }\n\n /**\n * Stamps the configured `iss` / `aud` onto a signer, plus any per-token claims the caller passed.\n *\n * The configured value is AUTHORITATIVE. `iss` and `aud` are in `JWT_COMMON_FIELDS`, so they ride\n * through the AES envelope in the clear and an application-shaped payload can carry them - an\n * issuer identity any payload could overwrite would not be an identity. A conflicting payload\n * claim is overwritten and reported.\n *\n * Per-token audience is an explicit argument rather than a smuggled payload key, so the caller\n * that legitimately needs one says so.\n */\n protected applySignClaims(opts: {\n signer: SignJWT;\n payload: Record<string, any>;\n claims?: IJWTIssueClaims;\n }): SignJWT {\n const { signer, payload, claims } = opts;\n const configured = this.signOptions;\n\n const issuer = claims?.issuer ?? configured?.issuer;\n const audience = claims?.audience ?? configured?.audience;\n\n const logger = this.logger.for(this.applySignClaims.name);\n\n if (issuer !== undefined) {\n if (payload.iss !== undefined && payload.iss !== issuer) {\n logger.warn(\n 'Payload iss overridden by the configured issuer | payload: %s | configured: %s',\n payload.iss,\n issuer,\n );\n }\n\n signer.setIssuer(issuer);\n }\n\n if (audience !== undefined) {\n if (payload.aud !== undefined) {\n logger.warn('Payload aud overridden | payload: %j | applied: %j', payload.aud, audience);\n }\n\n signer.setAudience(audience);\n }\n\n if (claims?.subject !== undefined) {\n signer.setSubject(claims.subject);\n }\n\n if (claims?.jwtId !== undefined) {\n signer.setJti(claims.jwtId);\n }\n\n return signer;\n }\n\n async decryptPayload(opts: {\n result: JWTVerifyResult<IJWTTokenPayload>;\n }): Promise<IJWTTokenPayload> {\n const { payload, protectedHeader } = opts.result;\n\n if (!this.aes || !this.applicationSecret) {\n return payload as IJWTTokenPayload;\n }\n\n this.logger\n .for(this.decryptPayload.name)\n .debug('JWT Token | payload: %j | header: %j', payload, protectedHeader);\n\n const rs: any = {};\n\n for (const key in payload) {\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = payload[key];\n continue;\n }\n\n const decryptedKey = await this.aes.decrypt({\n message: key,\n secret: this.applicationSecret,\n });\n const decryptedValue = await this.aes.decrypt({\n message: payload[key],\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n return rs;\n }\n\n protected abstract doVerify(token: string): Promise<IJWTTokenPayload>;\n\n abstract getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }): Promise<SignJWT>;\n\n protected abstract getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey>;\n\n protected abstract getDefaultTokenExpiresFn(): TGetTokenExpiresFn;\n}\n"]}
1
+ {"version":3,"file":"abstract.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/abstract.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAE7C,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAUtE,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAiB5C,gGAAgG;AAChG,MAAM,OAAgB,0BAAgD,SAAQ,WAAW;IAAzF;;QAYY,QAAG,GAAe,IAAI,CAAC;QACvB,sBAAiB,GAAkB,IAAI,CAAC;QACxC,gBAAW,GAAoC,IAAI,GAAG,EAAE,CAAC;QAEnE,oJAAoJ;QAC1I,iBAAY,GAA6B,IAAI,CAAC;QAExD,yFAAyF;QAC/E,kBAAa,GAA4B,IAAI,CAAC;IA4a1D,CAAC;IA/bC,oDAAoD;aACpC,sBAAiB,GAAG,IAAI,GAAG,CAAmB;QAC5D,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;KACN,CAAC,AAR+B,CAQ9B;IAYH,2CAA2C;aAC3B,eAAU,GAA0B,CAAC,QAAQ,EAAE,UAAU,CAAC,AAAhD,CAAiD;IAE3E;;;;;;;;OAQG;IACH,MAAM,CAAC,mBAAmB,CAAC,IAI1B;QACC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,gBAAgB,E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AC5C,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC;gBACrB,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YAEH,EAAE,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QACzF,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC","sourcesContent":["import type { AESAlgorithmType } from '@venizia/ignis-helpers';\nimport { AES } from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport type {\n IJWTClaimsOptions,\n IJWTIssueClaims,\n IJWTTokenPayload,\n IJWTVerifyOptions,\n IPayloadFieldCodec,\n TContext,\n TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport type { JWTPayload, JWTVerifyOptions, JWTVerifyResult, SignJWT } from 'jose';\n\n/** What a token service is configured with for claims: the required `claims`, the `verify` checks, and the removed `sign` it refuses. */\nexport interface IClaimsConfigSource {\n claims?: unknown;\n verify?: unknown;\n /** Removed: refused with a message that points to `claims`. */\n sign?: unknown;\n}\n\n/** What {@link AbstractBearerTokenService.resolveClaimsConfig} answers: the validated claims and the verify options jose receives. */\nexport interface IResolvedClaimsConfig {\n claims: IJWTClaimsOptions;\n verify: JWTVerifyOptions & { algorithms: string[] };\n}\n\n/** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */\nexport abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {\n /** Standard JWT fields that are never encrypted. */\n static readonly JWT_COMMON_FIELDS = new Set<keyof JWTPayload>([\n 'iss',\n 'sub',\n 'aud',\n 'jti',\n 'nbf',\n 'exp',\n 'iat',\n ]);\n\n protected aes: AES | null = null;\n protected applicationSecret: string | null = null;\n protected fieldCodecs: Map<string, IPayloadFieldCodec> = new Map();\n\n /** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */\n protected claimOptions: IJWTClaimsOptions | null = null;\n\n /** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */\n protected verifyOptions: JWTVerifyOptions | null = null;\n\n /** The keys a `claims` object may hold. */\n static readonly CLAIM_KEYS: ReadonlyArray<string> = ['issuer', 'audience'];\n\n /**\n * Validates the claims configuration of a token service and answers what the service uses. It throws, naming the\n * key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a\n * non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /\n * `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it\n * no `aud` is stamped and none is checked.\n * `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.\n * The component calls it at boot, and a service calls it when it is built, so neither can start without them.\n */\n static resolveClaimsConfig(opts: {\n scope: string;\n options: IClaimsConfigSource;\n pinnedAlgorithms?: string[];\n }): IResolvedClaimsConfig {\n const { scope, options, pinnedAlgorithms } = opts;\n const fail = (detail: string) =>\n getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${detail}`,\n });\n\n if (options.sign !== undefined) {\n throw fail(\n '`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',\n );\n }\n\n if (options.verify !== undefined && !RecordUtility.isPlainRecord(options.verify)) {\n throw fail(\n 'verify must be an object | its checks (maxTokenAge, subject, ...) would be dropped silently',\n );\n }\n\n const verify = RecordUtility.isPlainRecord(options.verify) ? options.verify : {};\n\n for (const key of AbstractBearerTokenService.CLAIM_KEYS) {\n if (key in verify) {\n throw fail(\n `verify.${key} was removed | set claims.${key}: it is stamped on every token and required on every verified one`,\n );\n }\n }\n\n const { claims } = options;\n\n if (!RecordUtility.isPlainRecord(claims)) {\n throw fail(\n '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',\n );\n }\n\n const unknown = Object.keys(claims).filter(\n (key) => !AbstractBearerTokenService.CLAIM_KEYS.includes(key),\n );\n\n if (unknown.length > 0) {\n throw fail(\n `claims holds unknown keys ${JSON.stringify(unknown)} | accepted: ${AbstractBearerTokenService.CLAIM_KEYS.join(', ')}`,\n );\n }\n\n const { issuer, audience } = claims;\n const isName = (value: unknown): value is string =>\n typeof value === 'string' && value.trim().length > 0;\n\n if (!isName(issuer)) {\n throw fail('claims.issuer is required | a non-empty string');\n }\n\n // Optional, but a present value is checked: `null`, `''` and `[]` are mistakes, not \"no audience\".\n if (\n audience !== undefined &&\n !isName(audience) &&\n !(Array.isArray(audience) && audience.length > 0 && audience.every(isName))\n ) {\n throw fail(\n 'claims.audience must be a non-empty string or a non-empty list of them | or leave it out',\n );\n }\n\n const resolvedAudience = Array.isArray(audience) ? [...audience] : audience;\n\n const algorithms = verify.algorithms ?? pinnedAlgorithms;\n\n if (!Array.isArray(algorithms) || algorithms.length === 0 || !algorithms.every(isName)) {\n throw fail(\n \"verify.algorithms is required | the accepted JWS algorithms, for example ['RS256']: a verifier cannot know what the issuer signs with\",\n );\n }\n\n if (algorithms.some((algorithm) => algorithm.trim().toLowerCase() === 'none')) {\n throw fail(\"the algorithm 'none' is refused | a token with no signature verifies nothing\");\n }\n\n return {\n claims: { issuer, ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }) },\n verify: {\n ...(verify as IJWTVerifyOptions),\n issuer,\n ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }),\n algorithms: [...algorithms],\n },\n };\n }\n\n /** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */\n protected configureClaims(opts: {\n options: IClaimsConfigSource;\n pinnedAlgorithms?: string[];\n }): void {\n const resolved = AbstractBearerTokenService.resolveClaimsConfig({\n scope: this.scope,\n options: opts.options,\n pinnedAlgorithms: opts.pinnedAlgorithms,\n });\n\n this.claimOptions = resolved.claims;\n this.verifyOptions = resolved.verify;\n }\n\n /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */\n protected configurePayloadEncryption(opts: {\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n }): void {\n const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs } = opts;\n\n if (fieldCodecs) {\n for (const codec of fieldCodecs) {\n this.fieldCodecs.set(codec.key, codec);\n }\n }\n\n if (!applicationSecret) {\n return;\n }\n\n this.aes = AES.withAlgorithm(aesAlgorithm);\n this.applicationSecret = applicationSecret;\n }\n\n extractCredentials(context: TContext<E, string>): { type: string; token: string } {\n const request = context.req;\n\n const authHeaderValue = request.header('Authorization');\n\n if (!authHeaderValue) {\n throw getError({\n error: AuthenticationErrors.HEADER_MISSING,\n message: 'Unauthorized user! Missing authorization header',\n });\n }\n\n if (!authHeaderValue.startsWith(Authentication.TYPE_BEARER)) {\n throw getError({\n error: AuthenticationErrors.SCHEME_INVALID,\n message: 'Unauthorized user! Invalid schema of request token!',\n });\n }\n\n const parts = authHeaderValue.split(' ');\n\n if (parts.length !== 2) {\n throw getError({\n error: AuthenticationErrors.HEADER_MALFORMED,\n message: `Authorization header value is invalid format. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`,\n });\n }\n\n const [tokenType, tokenValue] = parts;\n\n return { type: tokenType, token: tokenValue };\n }\n\n async verify(opts: { type: string; token: string }): Promise<IJWTTokenPayload> {\n const { token } = opts;\n\n if (!token) {\n this.logger.for(this.verify.name).error('Missing token for validating request!');\n throw getError({\n error: AuthenticationErrors.TOKEN_MISSING,\n message: '[verify] Invalid request token!',\n });\n }\n\n try {\n await this.assertNotServiceAssertion({ token });\n const result = await this.doVerify(token);\n\n return result;\n } catch (error) {\n // No log here - `cause` carries the reason (JWTExpired, signature mismatch) to the error handler, which logs the request once. An expired token is the caller's problem, hence `warn`.\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] Invalid or expired token',\n logLevel: 'warn',\n cause: error,\n });\n }\n }\n\n /**\n * A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service\n * assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.\n */\n protected async assertNotServiceAssertion(opts: { token: string }): Promise<void> {\n const { decodeProtectedHeader } = await JoseLoader.load();\n const { typ } = decodeProtectedHeader(opts.token);\n const kind = typeof typ === 'string' ? typ.toLowerCase().replace(/^application\\//, '') : '';\n\n if (kind === ServiceAssertion.TYP) {\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] A service assertion is not a user token',\n });\n }\n }\n\n async generate(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn?: TGetTokenExpiresFn;\n /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */\n claims?: IJWTIssueClaims;\n }): Promise<string> {\n const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;\n\n if (!payload) {\n throw getError({\n error: AuthenticationErrors.TOKEN_PAYLOAD_INVALID,\n message: '[generate] Invalid token payload!',\n });\n }\n\n const signer = await this.getSigner({ payload, getTokenExpiresFn, claims });\n\n try {\n const result = await this.getSigningKey();\n const rs = await signer.sign(result);\n\n return rs;\n } catch (error) {\n this.logger.for(this.generate.name).error('Failed to generate token | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[generate] Failed to generate token',\n });\n }\n }\n\n /** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */\n protected serializeField(opts: { key: string; value: any }): string {\n const { key, value } = opts;\n const codec = value === null ? undefined : this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.serialize({ value });\n }\n\n return JSON.stringify(value);\n }\n\n /**\n * With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;\n * without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,\n * so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An\n * `undefined` claim is skipped, as JSON drops it.\n */\n async encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, string> = {};\n\n const keys = Object.keys(payload);\n\n for (const key of keys) {\n const value = payload[key];\n\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = value;\n continue;\n }\n\n // Only `undefined` is skipped: JSON drops it too, so the claim is absent either way. `null` is a value, and\n // `serializeField` writes it as `null`, which `deserializeField` reads back, so an encrypted token decodes the\n // same payload as a plain one.\n if (value === undefined) {\n continue;\n }\n\n const encryptedKey = await this.aes.encrypt({\n message: key,\n secret: this.applicationSecret,\n });\n\n const serialized = this.serializeField({ key, value });\n\n const encryptedValue = await this.aes.encrypt({\n message: serialized,\n secret: this.applicationSecret,\n });\n rs[encryptedKey] = encryptedValue;\n }\n\n return rs;\n }\n\n /** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */\n protected deserializeField(opts: { key: string; value: string }) {\n const { key, value } = opts;\n const codec = value === 'null' ? undefined : this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.deserialize({ raw: value });\n }\n\n return JSON.parse(value);\n }\n\n /**\n * Stamps the configured `iss` / `aud` onto a signer, plus any per-token claims the caller passed.\n *\n * The configured value is AUTHORITATIVE. `iss` and `aud` are in `JWT_COMMON_FIELDS`, so they ride\n * through the AES envelope in the clear and an application-shaped payload can carry them - an\n * issuer identity any payload could overwrite would not be an identity. A conflicting payload\n * claim is overwritten and reported.\n *\n * Per-token audience is an explicit argument rather than a smuggled payload key, so the caller\n * that legitimately needs one says so.\n */\n protected applySignClaims(opts: {\n signer: SignJWT;\n payload: Record<string, any>;\n claims?: IJWTIssueClaims;\n }): SignJWT {\n const { signer, payload, claims } = opts;\n const configured = this.claimOptions;\n\n const issuer = claims?.issuer ?? configured?.issuer;\n const audience = claims?.audience ?? configured?.audience;\n\n const logger = this.logger.for(this.applySignClaims.name);\n\n if (issuer !== undefined) {\n if (payload.iss !== undefined && payload.iss !== issuer) {\n logger.warn(\n 'Payload iss overridden by the configured issuer | payload: %s | configured: %s',\n payload.iss,\n issuer,\n );\n }\n\n signer.setIssuer(issuer);\n }\n\n if (audience !== undefined) {\n if (payload.aud !== undefined) {\n logger.warn('Payload aud overridden | payload: %j | applied: %j', payload.aud, audience);\n }\n\n signer.setAudience(audience);\n }\n\n if (claims?.subject !== undefined) {\n signer.setSubject(claims.subject);\n }\n\n if (claims?.jwtId !== undefined) {\n signer.setJti(claims.jwtId);\n }\n\n return signer;\n }\n\n async decryptPayload(opts: {\n result: JWTVerifyResult<IJWTTokenPayload>;\n }): Promise<IJWTTokenPayload> {\n const { payload, protectedHeader } = opts.result;\n\n if (!this.aes || !this.applicationSecret) {\n return payload as IJWTTokenPayload;\n }\n\n this.logger\n .for(this.decryptPayload.name)\n .debug('JWT Token | payload: %j | header: %j', payload, protectedHeader);\n\n const rs: any = {};\n\n for (const key in payload) {\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = payload[key];\n continue;\n }\n\n const decryptedKey = await this.aes.decrypt({\n message: key,\n secret: this.applicationSecret,\n });\n const decryptedValue = await this.aes.decrypt({\n message: payload[key],\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n return rs;\n }\n\n protected abstract doVerify(token: string): Promise<IJWTTokenPayload>;\n\n abstract getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }): Promise<SignJWT>;\n\n protected abstract getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey>;\n\n protected abstract getDefaultTokenExpiresFn(): TGetTokenExpiresFn;\n}\n"]}
@@ -25,11 +25,11 @@ let JWKSIssuerTokenService = JWKSIssuerTokenService_1 = class JWKSIssuerTokenSer
25
25
  this.privateKey = null;
26
26
  this.publicKey = null;
27
27
  this.jwks = null;
28
+ this.configureClaims({ options: this.options, pinnedAlgorithms: [this.options.algorithm] });
28
29
  this.configurePayloadEncryption({
29
30
  aesAlgorithm: this.options.aesAlgorithm,
30
31
  applicationSecret: this.options.applicationSecret,
31
32
  fieldCodecs: this.options.fieldCodecs,
32
- sign: this.options.sign,
33
33
  });
34
34
  }
35
35
  async initialize() {
@@ -154,7 +154,7 @@ let JWKSIssuerTokenService = JWKSIssuerTokenService_1 = class JWKSIssuerTokenSer
154
154
  async doVerify(token) {
155
155
  await this.ensureInitialized();
156
156
  const { jwtVerify } = await JoseLoader.load();
157
- const result = await jwtVerify(token, this.publicKey, this.options.verify);
157
+ const result = await jwtVerify(token, this.publicKey, this.verifyOptions);
158
158
  return this.decryptPayload({ result });
159
159
  }
160
160
  async getSigner(opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuC,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,EACN,cAAc,EACd,cAAc,GAEf,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,4IAA4I;AAC5I,IAAa,sBAAsB,8BAAnC,MAAa,sBAA4C,SAAQ,wBAA2B;IAK1F,YAEE,OAAqC;QAErC,KAAK,CAA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AE,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1F,CAAC;IAEkB,aAAa;QAC9B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,qCAAqC,EAAE,CAAC,CAAC;QACrE,CAAC;QAED,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,iFAAiF;aAC3F,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,YAAY;QAChB,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,OAAO,IAAI,CAAC,IAAK,CAAC;IACpB,CAAC;CACF,CAAA;AArOY,sBAAsB;IAM9B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Signs tokens with a private key loaded from `IJWKSIssuerOptions` and exposes the matching public keys as a JWKS via `getJWKSAsync()`. */\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n sign: this.options.sign,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.options.verify);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
1
+ {"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuC,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,EACN,cAAc,EACd,cAAc,GAEf,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,4IAA4I;AAC5I,IAAa,sBAAsB,8BAAnC,MAAa,sBAA4C,SAAQ,wBAA2B;IAK1F,YAEE,OAAqC;QAErC,KAAK,CAAC,EAAE,KAAK,EAAE,wBAAsB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFpC,YAAO,GAAP,OAAO,CAAoB;QAN7B,eAAU,GAAsC,IAAI,CAAC;QACrD,cAAS,GAAsC,IAAI,CAAC;QACpD,SAAI,GAA2B,IAAI,CAAC;QAQ5C,IAAI,CAAC,eAAe,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,EAA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,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,iFAAiF;aAC3F,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,YAAY;QAChB,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,OAAO,IAAI,CAAC,IAAK,CAAC;IACpB,CAAC;CACF,CAAA;AArOY,sBAAsB;IAM9B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Signs tokens with a private key loaded from `IJWKSIssuerOptions` and exposes the matching public keys as a JWKS via `getJWKSAsync()`. */\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configureClaims({ options: this.options, pinnedAlgorithms: [this.options.algorithm] });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.verifyOptions!);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
@@ -15,6 +15,7 @@ import { HTTP } from '@venizia/ignis-helpers/common';
15
15
  import { getError } from '@venizia/ignis-helpers/core';
16
16
  import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
17
17
  import { JoseLoader } from '../../jose-loader.js';
18
+ import { JWKSUrlPolicy } from '../../jwks-url-policy.js';
18
19
  import { AbstractJWKSTokenService } from './abstract.service.js';
19
20
  /** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */
20
21
  let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTokenService extends AbstractJWKSTokenService {
@@ -22,6 +23,7 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
22
23
  super({ scope: JWKSVerifierTokenService_1.name });
23
24
  this.options = options;
24
25
  this.jwksVerifier = null;
26
+ this.configureClaims({ options: this.options });
25
27
  this.configurePayloadEncryption({
26
28
  aesAlgorithm: this.options.aesAlgorithm,
27
29
  applicationSecret: this.options.applicationSecret,
@@ -30,7 +32,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
30
32
  }
31
33
  async initialize() {
32
34
  const { createRemoteJWKSet } = await JoseLoader.load();
33
- const jwksUrl = new URL(this.options.jwksUrl);
35
+ const jwksUrl = JWKSUrlPolicy.assertUrl({
36
+ scope: JWKSVerifierTokenService_1.name,
37
+ label: 'jwksUrl',
38
+ url: this.options.jwksUrl,
39
+ hosts: this.options.jwks?.hosts?.http,
40
+ });
34
41
  this.jwksVerifier = createRemoteJWKSet(jwksUrl, {
35
42
  cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,
36
43
  cooldownDuration: this.options.cooldownMs ?? 30_000,
@@ -38,12 +45,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
38
45
  this.initialized = true;
39
46
  this.logger
40
47
  .for(this.initialize.name)
41
- .info('JWKS verifier initialized | url: %s', this.options.jwksUrl);
48
+ .info('JWKS verifier initialized | origin: %s', jwksUrl.origin);
42
49
  }
43
50
  async doVerify(token) {
44
51
  await this.ensureInitialized();
45
52
  const { jwtVerify } = await JoseLoader.load();
46
- const result = await jwtVerify(token, this.jwksVerifier, this.options.verify);
53
+ const result = await jwtVerify(token, this.jwksVerifier, this.verifyOptions);
47
54
  return this.decryptPayload({ result });
48
55
  }
49
56
  async getSigner(_opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,6LAA6L;AAC7L,IAAa,wBAAwB,gCAArC,MAAa,wBAA8C,SAAQ,wBAA2B;IAG5F,YAEE,OAAuC;QAEvC,KAAK,CAAC,EAAE,KAAK,EAAE,0BAAwB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,YAAO,GAAP,OAAO,CAAsB;QAJ/B,iBAAY,GAAiD,IAAI,CAAC;QAO1E,IAAI,CAAC,0BAA0B,CAAC;YAC9B,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY;YACvC,iBAAiB,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB;YACjD,WAAW,EAAE,IAA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EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,wBAAwB;QACzC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,8DAA8D;SACxE,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAjEY,wBAAwB;IAIhC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAJ7C,wBAAwB,CAiEpC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSVerifierOptions,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { createRemoteJWKSet, SignJWT } from 'jose';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */\nexport class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSVerifierOptions,\n ) {\n super({ scope: JWKSVerifierTokenService.name });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { createRemoteJWKSet } = await JoseLoader.load();\n const jwksUrl = new URL(this.options.jwksUrl);\n this.jwksVerifier = createRemoteJWKSet(jwksUrl, {\n cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,\n cooldownDuration: this.options.cooldownMs ?? 30_000,\n });\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info('JWKS verifier initialized | url: %s', this.options.jwksUrl);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwksVerifier!,\n this.options.verify,\n );\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(_opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n }): Promise<SignJWT> {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getSigningKey(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getDefaultTokenExpiresFn(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode has no token expiry',\n });\n }\n}\n"]}
1
+ {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,6LAA6L;AAC7L,IAAa,wBAAwB,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CAAC;IAEkB,KAAK,CAAC,QAAQ,CAAC,KAAa;QAC7C,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC/B,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,SAAS,CAC5B,KAAK,EACL,IAAI,CAAC,YAAa,EAClB,IAAI,CAAC,aAAc,CACpB,CAAC;QAEF,OAAO,IAAI,CAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACzC,CAAC;IAEQ,KAAK,CAAC,SAAS,CAAC,KAGxB;QACC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,aAAa;QAC9B,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,wBAAwB;QACzC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,8DAA8D;SACxE,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAvEY,wBAAwB;IAIhC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAJ7C,wBAAwB,CAuEpC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSVerifierOptions,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { createRemoteJWKSet, SignJWT } from 'jose';\nimport { JoseLoader } from '../../jose-loader';\nimport { JWKSUrlPolicy } from '../../jwks-url-policy';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */\nexport class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSVerifierOptions,\n ) {\n super({ scope: JWKSVerifierTokenService.name });\n this.configureClaims({ options: this.options });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { createRemoteJWKSet } = await JoseLoader.load();\n const jwksUrl = JWKSUrlPolicy.assertUrl({\n scope: JWKSVerifierTokenService.name,\n label: 'jwksUrl',\n url: this.options.jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n });\n this.jwksVerifier = createRemoteJWKSet(jwksUrl, {\n cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,\n cooldownDuration: this.options.cooldownMs ?? 30_000,\n });\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info('JWKS verifier initialized | origin: %s', jwksUrl.origin);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwksVerifier!,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(_opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n }): Promise<SignJWT> {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getSigningKey(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getDefaultTokenExpiresFn(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode has no token expiry',\n });\n }\n}\n"]}
@@ -5,7 +5,18 @@ import { AbstractBearerTokenService } from './abstract.service.js';
5
5
  /** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
6
6
  export declare class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {
7
7
  protected options: IJWSTokenServiceOptions;
8
+ /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
9
+ static readonly MIN_SECRET_BYTES = 32;
8
10
  protected jwtSecret: Uint8Array;
11
+ /**
12
+ * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
13
+ * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
14
+ * service when it is built.
15
+ */
16
+ static assertSecretStrength(opts: {
17
+ scope: string;
18
+ secret: string;
19
+ }): void;
9
20
  constructor(options: IJWSTokenServiceOptions);
10
21
  protected doVerify(token: string): Promise<IJWTTokenPayload>;
11
22
  getSigner(opts: {
@@ -17,7 +17,25 @@ import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
17
17
  import { JoseLoader } from '../jose-loader.js';
18
18
  import { AbstractBearerTokenService } from './abstract.service.js';
19
19
  /** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
20
- let JWSTokenService = JWSTokenService_1 = class JWSTokenService extends AbstractBearerTokenService {
20
+ let JWSTokenService = class JWSTokenService extends AbstractBearerTokenService {
21
+ static { JWSTokenService_1 = this; }
22
+ /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
23
+ static { this.MIN_SECRET_BYTES = 32; }
24
+ /**
25
+ * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
26
+ * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
27
+ * service when it is built.
28
+ */
29
+ static assertSecretStrength(opts) {
30
+ const bytes = new TextEncoder().encode(opts.secret).length;
31
+ if (bytes >= JWSTokenService_1.MIN_SECRET_BYTES) {
32
+ return;
33
+ }
34
+ throw getError({
35
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
36
+ message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService_1.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,
37
+ });
38
+ }
21
39
  constructor(options) {
22
40
  super({ scope: JWSTokenService_1.name });
23
41
  this.options = options;
@@ -34,17 +52,21 @@ let JWSTokenService = JWSTokenService_1 = class JWSTokenService extends Abstract
34
52
  message: '[JWSTokenService] Invalid getTokenExpiresFn',
35
53
  });
36
54
  }
55
+ this.configureClaims({
56
+ options,
57
+ pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],
58
+ });
59
+ JWSTokenService_1.assertSecretStrength({ scope: JWSTokenService_1.name, secret: jwtSecret });
37
60
  this.configurePayloadEncryption({
38
61
  aesAlgorithm,
39
62
  applicationSecret,
40
63
  fieldCodecs: options.fieldCodecs,
41
- sign: options.sign,
42
64
  });
43
65
  this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);
44
66
  }
45
67
  async doVerify(token) {
46
68
  const { jwtVerify } = await JoseLoader.load();
47
- const decodedToken = await jwtVerify(token, this.jwtSecret, this.options.verify);
69
+ const decodedToken = await jwtVerify(token, this.jwtSecret, this.verifyOptions);
48
70
  return this.decryptPayload({ result: decodedToken });
49
71
  }
50
72
  async getSigner(opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/j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oCAAoC,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;CACF,CAAA;AA5EY,eAAe;IAIvB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,WAAW,EAAE,CAAC,CAAA;;GAJ5C,eAAe,CA4E3B","sourcesContent":["import { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWSTokenServiceOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport { AbstractBearerTokenService } from './abstract.service';\n\n/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */\nexport class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {\n protected jwtSecret: Uint8Array;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n protected options: IJWSTokenServiceOptions,\n ) {\n super({ scope: JWSTokenService.name });\n\n const { aesAlgorithm, jwtSecret, applicationSecret, getTokenExpiresFn } = options ?? {};\n\n if (!jwtSecret) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid jwtSecret',\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid getTokenExpiresFn',\n });\n }\n\n this.configurePayloadEncryption({\n aesAlgorithm,\n applicationSecret,\n fieldCodecs: options.fieldCodecs,\n sign: options.sign,\n });\n this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n const { jwtVerify } = await JoseLoader.load();\n const decodedToken = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwtSecret,\n this.options.verify,\n );\n\n return this.decryptPayload({ result: decodedToken });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n const { SignJWT } = await JoseLoader.load();\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT(Object.assign({}, encryptedPayload))\n .setProtectedHeader({ alg: this.options.headerAlgorithm ?? 'HS256' })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array> {\n if (!this.jwtSecret) {\n throw getError({ message: '[getSigningKey] Invalid jwtSecret!' });\n }\n\n return this.jwtSecret;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n}\n"]}
1
+ {"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/jws.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAEhE,8EAA8E;AAC9E,IAAa,eAAe,GAA5B,MAAa,eAAqC,SAAQ,0BAA6B;;IACrF,yIAAyI;aACzH,qBAAgB,GAAG,EAAE,AAAL,CAAM;IAItC;;;;OAIG;I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I,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1F,CAAC;IAEkB,aAAa;QAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,oCAAoC,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;;AArGU,eAAe;IAyBvB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,WAAW,EAAE,CAAC,CAAA;;GAzB5C,eAAe,CAsG3B","sourcesContent":["import { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWSTokenServiceOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport { AbstractBearerTokenService } from './abstract.service';\n\n/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */\nexport class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {\n /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */\n static readonly MIN_SECRET_BYTES = 32;\n\n protected jwtSecret: Uint8Array;\n\n /**\n * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not\n * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the\n * service when it is built.\n */\n static assertSecretStrength(opts: { scope: string; secret: string }): void {\n const bytes = new TextEncoder().encode(opts.secret).length;\n\n if (bytes >= JWSTokenService.MIN_SECRET_BYTES) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,\n });\n }\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n protected options: IJWSTokenServiceOptions,\n ) {\n super({ scope: JWSTokenService.name });\n\n const { aesAlgorithm, jwtSecret, applicationSecret, getTokenExpiresFn } = options ?? {};\n\n if (!jwtSecret) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid jwtSecret',\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid getTokenExpiresFn',\n });\n }\n\n this.configureClaims({\n options,\n pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],\n });\n JWSTokenService.assertSecretStrength({ scope: JWSTokenService.name, secret: jwtSecret });\n\n this.configurePayloadEncryption({\n aesAlgorithm,\n applicationSecret,\n fieldCodecs: options.fieldCodecs,\n });\n this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n const { jwtVerify } = await JoseLoader.load();\n const decodedToken = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwtSecret,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result: decodedToken });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n const { SignJWT } = await JoseLoader.load();\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT(Object.assign({}, encryptedPayload))\n .setProtectedHeader({ alg: this.options.headerAlgorithm ?? 'HS256' })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array> {\n if (!this.jwtSecret) {\n throw getError({ message: '[getSigningKey] Invalid jwtSecret!' });\n }\n\n return this.jwtSecret;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export * from './basic/index.js';
2
2
  export * from './bearer/index.js';
3
+ export * from './jwks-url-policy.js';
3
4
  export * from './service/index.js';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export * from './basic/index.js';
2
2
  export * from './bearer/index.js';
3
+ export * from './jwks-url-policy.js';
3
4
  export * from './service/index.js';
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './service';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './jwks-url-policy';\nexport * from './service';\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
3
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
4
+ * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
5
+ * callers: both fetch a key set to decide who may call.
6
+ *
7
+ * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to
8
+ * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.
9
+ */
10
+ export declare class JWKSUrlPolicy {
11
+ /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */
12
+ static resolveHttpHosts(opts: {
13
+ scope: string;
14
+ hosts?: unknown;
15
+ }): ReadonlySet<string>;
16
+ /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */
17
+ private static isParsedAsItself;
18
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
19
+ static isLoopback(hostname: string): boolean;
20
+ /**
21
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
22
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
23
+ */
24
+ static assertUrl(opts: {
25
+ scope: string;
26
+ label: string;
27
+ url: string;
28
+ hosts?: unknown;
29
+ }): URL;
30
+ }
31
+ //# sourceMappingURL=jwks-url-policy.d.ts.map
@@ -0,0 +1,99 @@
1
+ import { HTTP } from '@venizia/ignis-helpers/common';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ /** One host name of `jwks.hosts.http`: labels of letters, digits and hyphens joined by single dots - no empty label, no port, no scheme, no wildcard, no address literal. */
4
+ const HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
5
+ /** An IPv4 address: an entry of `jwks.hosts.http` is a name, and an address is not one. */
6
+ const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/;
7
+ /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
8
+ const LOOPBACK_IPV4_PATTERN = /^127(?:\.\d{1,3}){3}$/;
9
+ const LOOPBACK_HOSTS = new Set(['localhost', '[::1]']);
10
+ /**
11
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
12
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
13
+ * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
14
+ * callers: both fetch a key set to decide who may call.
15
+ *
16
+ * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to
17
+ * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.
18
+ */
19
+ export class JWKSUrlPolicy {
20
+ /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */
21
+ static resolveHttpHosts(opts) {
22
+ const { scope, hosts } = opts;
23
+ if (hosts === undefined) {
24
+ return new Set();
25
+ }
26
+ if (!Array.isArray(hosts)) {
27
+ throw getError({
28
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
29
+ message: `[${scope}] jwks.hosts.http must be a list of host names`,
30
+ });
31
+ }
32
+ const resolved = new Set();
33
+ for (const entry of hosts) {
34
+ const name = typeof entry === 'string' ? entry.trim().toLowerCase() : '';
35
+ // The name must be what the URL parser makes of it: `2130706433`, `0x7f000001` and `1.2.3` are addresses the parser
36
+ // rewrites (to `127.0.0.1`, `1.2.0.3`), so none of them is the name it looks like.
37
+ if (!HOST_NAME_PATTERN.test(name) ||
38
+ IPV4_PATTERN.test(name) ||
39
+ !JWKSUrlPolicy.isParsedAsItself({ name })) {
40
+ throw getError({
41
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
42
+ message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list host names only: no port, scheme, wildcard or address, for example 'identity-service'`,
43
+ });
44
+ }
45
+ resolved.add(name);
46
+ }
47
+ return resolved;
48
+ }
49
+ /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */
50
+ static isParsedAsItself(opts) {
51
+ try {
52
+ return new URL(`http://${opts.name}`).hostname === opts.name;
53
+ // eslint-disable-next-line venizia/no-silent-catch -- a name the parser refuses is not a host name: the caller refuses the entry
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ }
59
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
60
+ static isLoopback(hostname) {
61
+ return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);
62
+ }
63
+ /**
64
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
65
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
66
+ */
67
+ static assertUrl(opts) {
68
+ const { scope, label, url } = opts;
69
+ let parsed;
70
+ try {
71
+ parsed = new URL(url);
72
+ // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials
73
+ }
74
+ catch {
75
+ throw getError({
76
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
77
+ message: `[${scope}] ${label} is not a valid URL`,
78
+ });
79
+ }
80
+ if (parsed.protocol === 'https:') {
81
+ return parsed;
82
+ }
83
+ if (parsed.protocol !== 'http:') {
84
+ throw getError({
85
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
86
+ message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,
87
+ });
88
+ }
89
+ const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });
90
+ if (JWKSUrlPolicy.isLoopback(parsed.hostname) || allowed.has(parsed.hostname)) {
91
+ return parsed;
92
+ }
93
+ throw getError({
94
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
95
+ message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host name in jwks.hosts.http`,
96
+ });
97
+ }
98
+ }
99
+ //# sourceMappingURL=jwks-url-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwks-url-policy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/jwks-url-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OA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QAChB,CAAC;QAED,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;YAChC,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,KAAK,KAAK,KAAK,6BAA6B,MAAM,CAAC,QAAQ,EAAE;aAC3E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,OAAO,GAAG,aAAa,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE7E,IAAI,aAAa,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9E,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,IAAI,KAAK,KAAK,KAAK,6BAA6B,MAAM,CAAC,QAAQ,wEAAwE;SACjJ,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** One host name of `jwks.hosts.http`: labels of letters, digits and hyphens joined by single dots - no empty label, no port, no scheme, no wildcard, no address literal. */\nconst HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;\n\n/** An IPv4 address: an entry of `jwks.hosts.http` is a name, and an address is not one. */\nconst IPV4_PATTERN = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n\n/** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\nconst LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n/**\n * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and\n * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or\n * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion\n * callers: both fetch a key set to decide who may call.\n *\n * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to\n * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.\n */\nexport class JWKSUrlPolicy {\n /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */\n static resolveHttpHosts(opts: { scope: string; hosts?: unknown }): ReadonlySet<string> {\n const { scope, hosts } = opts;\n\n if (hosts === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(hosts)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http must be a list of host names`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of hosts) {\n const name = typeof entry === 'string' ? entry.trim().toLowerCase() : '';\n\n // The name must be what the URL parser makes of it: `2130706433`, `0x7f000001` and `1.2.3` are addresses the parser\n // rewrites (to `127.0.0.1`, `1.2.0.3`), so none of them is the name it looks like.\n if (\n !HOST_NAME_PATTERN.test(name) ||\n IPV4_PATTERN.test(name) ||\n !JWKSUrlPolicy.isParsedAsItself({ name })\n ) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list host names only: no port, scheme, wildcard or address, for example 'identity-service'`,\n });\n }\n\n resolved.add(name);\n }\n\n return resolved;\n }\n\n /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */\n private static isParsedAsItself(opts: { name: string }): boolean {\n try {\n return new URL(`http://${opts.name}`).hostname === opts.name;\n // eslint-disable-next-line venizia/no-silent-catch -- a name the parser refuses is not a host name: the caller refuses the entry\n } catch {\n return false;\n }\n }\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopback(hostname: string): boolean {\n return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /**\n * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in\n * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.\n */\n static assertUrl(opts: { scope: string; label: string; url: string; hosts?: unknown }): URL {\n const { scope, label, url } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} is not a valid URL`,\n });\n }\n\n if (parsed.protocol === 'https:') {\n return parsed;\n }\n\n if (parsed.protocol !== 'http:') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,\n });\n }\n\n const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });\n\n if (JWKSUrlPolicy.isLoopback(parsed.hostname) || allowed.has(parsed.hostname)) {\n return parsed;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host name in jwks.hosts.http`,\n });\n }\n}\n"]}
@@ -15,6 +15,7 @@ import { inject } from '../../../../../base/metadata/index.js';
15
15
  import { AuthenticateBindingKeys, AuthenticationErrors, BaseService, ServiceAssertion, } from '@venizia/ignis-kernel';
16
16
  import { getError } from '@venizia/ignis-helpers/core';
17
17
  import { JoseLoader } from '../jose-loader.js';
18
+ import { JWKSUrlPolicy } from '../jwks-url-policy.js';
18
19
  /**
19
20
  * Verifies an incoming service assertion against the CALLER's own JWKS.
20
21
  *
@@ -91,7 +92,12 @@ let ServiceAssertionVerifierService = ServiceAssertionVerifierService_1 = class
91
92
  callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,
92
93
  serviceDefault: this.options.acceptMaxAgeSeconds,
93
94
  }));
94
- const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {
95
+ const keySet = jose.createRemoteJWKSet(JWKSUrlPolicy.assertUrl({
96
+ scope: ServiceAssertionVerifierService_1.name,
97
+ label: 'the caller jwksUrl',
98
+ url: jwksUrl,
99
+ hosts: this.options.jwks?.hosts?.http,
100
+ }), {
95
101
  cacheMaxAge: this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,
96
102
  cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,
97
103
  });