@venizia/ignis 0.4.8-16 → 0.4.8-17

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 (48) hide show
  1. package/dist/esm/base/applications/base.js.map +1 -1
  2. package/dist/esm/components/api-reference/common/types.d.ts +4 -1
  3. package/dist/esm/components/api-reference/common/types.js.map +1 -1
  4. package/dist/esm/components/api-reference/component.js +8 -3
  5. package/dist/esm/components/api-reference/component.js.map +1 -1
  6. package/dist/esm/components/auth/authenticate/component.js +2 -1
  7. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  8. package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +2 -2
  9. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +1 -1
  10. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  11. package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +1 -2
  12. package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
  13. package/dist/esm/components/mail/common/types/options.d.ts +54 -10
  14. package/dist/esm/components/mail/common/types/options.js.map +1 -1
  15. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +7 -2
  16. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
  17. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.d.ts +2 -3
  18. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
  19. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.d.ts +2 -3
  20. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
  21. package/dist/esm/components/mail/services/mail.service.d.ts +1 -2
  22. package/dist/esm/components/mail/services/mail.service.js.map +1 -1
  23. package/dist/esm/components/mail/services/template.service.d.ts +3 -4
  24. package/dist/esm/components/mail/services/template.service.js +1 -1
  25. package/dist/esm/components/mail/services/template.service.js.map +1 -1
  26. package/dist/esm/components/mail/utilities/header.utility.d.ts +1 -1
  27. package/dist/esm/components/mail/utilities/header.utility.js +1 -1
  28. package/dist/esm/components/mail/utilities/header.utility.js.map +1 -1
  29. package/dist/esm/components/mail/utilities/type.utility.d.ts +2 -3
  30. package/dist/esm/components/mail/utilities/type.utility.js +6 -7
  31. package/dist/esm/components/mail/utilities/type.utility.js.map +1 -1
  32. package/dist/esm/components/static-asset/common/types.d.ts +35 -13
  33. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  34. package/dist/esm/components/static-asset/controller/factory.d.ts +2 -2
  35. package/dist/esm/components/static-asset/controller/routes/context.d.ts +4 -3
  36. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -1
  37. package/dist/esm/components/static-asset/utilities/meta-link.utility.d.ts +5 -5
  38. package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -1
  39. package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +3 -11
  40. package/dist/esm/components/static-asset/utilities/toggle.utility.js +3 -14
  41. package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -1
  42. package/dist/esm/testing/assert-application-boots.d.ts +2 -2
  43. package/dist/esm/testing/assert-application-boots.js +6 -2
  44. package/dist/esm/testing/assert-application-boots.js.map +1 -1
  45. package/dist/presets/app/preset.json +4 -4
  46. package/dist/presets/lib/preset.json +3 -3
  47. package/dist/presets/shared/preset.json +1 -1
  48. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/base/applications/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD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Aa,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE;YACvE;gBACE,IAAI,EAAE,eAAe,CAAC,4BAA4B;gBAClD,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,0BAA0B,EAAE;aAC7C;YACD,GAAG,KAAK,CAAC,eAAe,EAAE;SAC3B,CAAC;QAEF,MAAM,WAAW,GAAG,YAAY,CAAC,WAAW,CAAC;YAC3C,KAAK;YACL,MAAM,EAAE,eAAe,CAAC,aAAa;YACrC,IAAI,EAAE,EAAE,IAAI,EAAE,eAAe,CAAC,eAAe,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE;SAClF,CAAC,CAAC;QAEH,+FAA+F;QAC/F,iGAAiG;QACjG,MAAM,cAAc,GAAG,YAAY,CAAC,WAAW,CAAC;YAC9C,KAAK,EAAE,WAAW;YAClB,MAAM,EAAE,eAAe,CAAC,iCAAiC;YACzD,IAAI,EAAE;gBACJ,IAAI,EAAE,eAAe,CAAC,sBAAsB;gBAC5C,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE;aACvC;SACF,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,cAAc;YACjB,6DAA6D;YAC7D;gBACE,IAAI,EAAE,eAAe,CAAC,6BAA6B;gBACnD,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,0BAA0B,EAAE;aAC7C;SACF,CAAC;IACJ,CAAC;IAED;;;OAGG;IACO,0BAA0B;QAClC,kBAAkB,CAAC,0BAA0B,CAAC;YAC5C,mBAAmB,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,IAAI,KAAK;YAC/D,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { ScopeFilterUtility } from '@venizia/ignis-connectors';\nimport { ControllerTransports } from '@venizia/ignis-kernel';\nimport { BindingNamespaces, CoreBindings } from '@venizia/ignis-kernel';\nimport { EnvironmentKeys } from '@/common/environments';\nimport { RequestTrackerComponent } from '@/components';\nimport { GrpcComponent } from '@/components/controller/grpc';\nimport {\n BindingScopes,\n BindingValueTypes,\n BootSequence,\n MetadataRegistry,\n RequestContextRegistry,\n} from '@venizia/ignis-kernel';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type {\n ISecretHydrateEntry,\n ISecretRotatable,\n ISecretsHelper,\n ISecretsRegistration,\n} from '@venizia/ignis-helpers';\nimport { ParseUtility, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, ObjectUtility } from '@venizia/ignis-helpers/common';\nimport { DEFAULT_TEMPORAL_TZ } from '@venizia/ignis-helpers/temporal';\nimport {\n applicationEnvironment,\n SecretsHelperFactory,\n PerformanceUtility,\n Environment,\n SecretProviders,\n} from '@venizia/ignis-helpers';\nimport { contextStorage, tryGetContext } from 'hono/context-storage';\nimport { AppErrorMiddleware, EmojiFaviconMiddleware } from '../middlewares';\nimport { serveStatic } from 'hono/bun';\nimport { ServerLoggerStartup } from './common';\nimport { ServerBootSteps } from './boot-steps';\nimport { ServerApplication } from './server';\nimport type { IRestApplication } from '@venizia/ignis-kernel';\nimport type { IBootSequenceStep } from '@venizia/ignis-kernel';\n\n/** Maps a secret bundle to env names: the explicit `keys` mapping when present, otherwise every bundle key under `prefix`. */\nconst selectSecretEnvKeys = (opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n}): Record<string, string> => {\n const { bundle, entry } = opts;\n const merged: Record<string, string> = {};\n\n if (!entry.keys) {\n const bundleEntries = Object.entries(bundle);\n\n for (const [rawKey, value] of bundleEntries) {\n merged[`${entry.prefix ?? ''}${rawKey}`] = value;\n }\n\n return merged;\n }\n\n const entryKeysEntries = Object.entries(entry.keys);\n\n for (const [rawKey, envKey] of entryKeysEntries) {\n const value = bundle[rawKey];\n\n if (value === undefined) {\n continue;\n }\n\n merged[envKey] = value;\n }\n\n return merged;\n};\n\n/**\n * The IGNIS server application: a `ServerApplication` that adds secrets hydration, env validation, start-up info and the gRPC controller branch. Extend it to build an application.\n *\n * @example\n * ```typescript\n * import { BaseApplication, type IApplicationInfo } from '@venizia/ignis';\n *\n * class App extends BaseApplication {\n * getAppInfo(): IApplicationInfo { return { name: 'app', version: '1.0.0', description: 'Demo' }; }\n * staticConfigure(): void {}\n * preConfigure(): void {}\n * postConfigure(): void {}\n * setupMiddlewares(): void {}\n * }\n * const app = new App({ scope: 'App', config: { host: '0.0.0.0', port: 3000, path: { base: '/api', isStrict: true } } });\n * app.init();\n * await app.start();\n * ```\n */\nexport abstract class BaseApplication extends ServerApplication implements IRestApplication {\n protected secretsProvider?: ISecretsHelper;\n protected secretsRegistration?: ISecretsRegistration;\n\n protected normalizePath(...segments: string[]): string {\n const joined = segments.join('/').replace(/\\/+/g, '/').replace(/\\/$/, '');\n\n return joined || '/';\n }\n\n /** Adds the gRPC branch the kernel cannot own: `GrpcComponent` needs `AbstractGrpcController`, core-only code that reaches `node:module`. */\n override async registerControllers(): Promise<void> {\n await super.registerControllers();\n\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n description: 'Register application gRPC controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n for (const transport of transports) {\n if (transport === ControllerTransports.REST) {\n continue;\n }\n\n if (transport !== ControllerTransports.GRPC) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[registerControllers] Unsupported transport: '${transport}'`,\n });\n }\n\n const grpcComponent = new GrpcComponent(this);\n await grpcComponent.configure();\n }\n\n // Warn if gRPC controllers exist but gRPC transport is not enabled\n if (transports.includes(ControllerTransports.GRPC)) {\n return;\n }\n\n const allBindings = this.findByTag({ tag: BindingNamespaces.CONTROLLER });\n\n for (const binding of allBindings) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n\n if (!target) {\n continue;\n }\n\n const metadata = MetadataRegistry.getInstance().getControllerMetadata({ target });\n\n if (metadata?.transport !== ControllerTransports.GRPC) {\n continue;\n }\n\n this.logger\n .for(this.registerControllers.name)\n .error(\n 'gRPC controller \"%s\" discovered but gRPC transport is not enabled. Add \"%s\" to transports config.',\n binding.key,\n ControllerTransports.GRPC,\n );\n }\n },\n });\n }\n\n registerSecrets(): ValueOrPromise<ISecretsRegistration> {\n return { provider: SecretProviders.SYSTEM_ENVS };\n }\n\n async hydrateSecrets(): Promise<void> {\n const logger = this.logger.for(this.hydrateSecrets.name);\n const registration = await this.registerSecrets();\n\n let provider: ISecretsHelper | undefined;\n const emptyHydrations: string[] = [];\n\n try {\n const result = await SecretsHelperFactory.create({ ...registration, identifier: 'app' });\n provider = result;\n await provider.configure();\n\n await this.hydrateSecretEntries({ provider, registration, emptyHydrations, logger });\n\n const registrationLease = registration.lease ?? [];\n\n for (const entry of registrationLease) {\n await provider.lease({ path: entry.path, key: entry.key });\n }\n } catch (error) {\n const env = Environment.current;\n\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Secret provider failed in non-development environment | env: ${env}`,\n });\n }\n\n logger.warn(\n 'Secret provider failed; falling back to system-envs | env: %s | error: %s',\n env,\n error,\n );\n\n if (provider) {\n try {\n await provider.shutdown();\n } catch (shutdownError) {\n logger.error(\n 'Failed to shut down partially-built provider during fallback | error: %s',\n shutdownError,\n );\n }\n }\n\n const result2 = await SecretsHelperFactory.create({\n provider: SecretProviders.SYSTEM_ENVS,\n identifier: 'app',\n });\n provider = result2;\n }\n\n if (!provider) {\n throw getError({ message: '[hydrateSecrets] No secrets provider resolved' });\n }\n\n if (emptyHydrations.length > 0) {\n const env = Environment.current;\n\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Hydrate entries resolved to an empty secret bundle in non-development environment | env: ${env} | paths: ${emptyHydrations.join(', ')}`,\n });\n }\n\n logger.warn(\n 'Hydrate entries resolved to an empty secret bundle; continuing in development | env: %s | paths: %s',\n env,\n emptyHydrations.join(', '),\n );\n }\n\n this.bind<ISecretsHelper>({ key: CoreBindings.APPLICATION_CONFIG })\n .toProvider(() => provider)\n .setScope(BindingScopes.SINGLETON);\n\n this.registerPostStopHook({ identifier: 'secrets.shutdown', hook: () => provider.shutdown() });\n this.secretsProvider = provider;\n this.secretsRegistration = registration;\n }\n\n /** Applies each hydrate entry in declaration order; paths that resolve empty while declaring an expectation are collected in `emptyHydrations` rather than failing here. */\n protected async hydrateSecretEntries(opts: {\n provider: ISecretsHelper;\n registration: ISecretsRegistration;\n emptyHydrations: string[];\n logger: ILogger;\n }): Promise<void> {\n const { provider, registration, emptyHydrations, logger } = opts;\n\n const registrationHydrate = registration.hydrate ?? [];\n\n for (const entry of registrationHydrate) {\n const bundle = await provider.getBundle({ path: entry.path });\n const merged = this.mergeSecretsIntoEnv({ bundle, entry });\n\n if (Object.keys(merged).length > 0) {\n continue;\n }\n\n if (this.hydrateEntryDeclaresExpectation({ entry })) {\n emptyHydrations.push(entry.path);\n continue;\n }\n\n logger.warn(\n 'Hydrate entry resolved to an empty bundle and declares no expected keys | path: %s',\n entry.path,\n );\n }\n }\n\n protected mergeSecretsIntoEnv(opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n }): Record<string, string> {\n const { bundle, entry } = opts;\n const merged = selectSecretEnvKeys({ bundle, entry });\n\n const mergedEntries = Object.entries(merged);\n\n for (const [key, value] of mergedEntries) {\n process.env[key] = value;\n }\n\n applicationEnvironment.merge({ envs: merged });\n\n return merged;\n }\n\n /** A hydrate entry declares an expectation only via explicit `keys` or a non-empty `prefix`; such an entry resolving to zero env values is a misconfiguration boot must not silently absorb. */\n protected hydrateEntryDeclaresExpectation(opts: { entry: ISecretHydrateEntry }): boolean {\n const { entry } = opts;\n\n if (entry.keys && Object.keys(entry.keys).length > 0) {\n return true;\n }\n\n return typeof entry.prefix === 'string' && entry.prefix.length > 0;\n }\n\n async wireSecretRotatables(): Promise<void> {\n const logger = this.logger.for(this.wireSecretRotatables.name);\n const provider = this.secretsProvider;\n const registration = this.secretsRegistration;\n\n if (!provider || !registration?.lease?.length) {\n return;\n }\n\n for (const entry of registration.lease) {\n const instance = this.get<ISecretRotatable>({ key: entry.key, isOptional: true });\n\n if (instance && typeof instance.onSecretRotated === 'function') {\n provider.registerRotatable({ key: entry.key, target: instance });\n logger.info('Wired rotatable | key: %s', entry.key);\n continue;\n }\n\n logger.debug('Lease key has no rotatable consumer | key: %s', entry.key);\n }\n }\n\n static(opts: { restPath?: string; folderPath: string }) {\n const { restPath = '*', folderPath } = opts;\n const server = this.getServer();\n\n server.use(restPath, serveStatic({ root: folderPath }));\n\n this.logger\n .for(this.static.name)\n .debug(\n 'Registered static files | runtime: %s | path: %s | folder: %s',\n this.runtime,\n restPath,\n folderPath,\n );\n\n return this;\n }\n\n /**\n * Every value is read HERE, not destructured at module load: an application that loads its\n * `.env` in its own entrypoint does so after this module is imported, and a module-load snapshot\n * would print the defaults for a host that configured everything correctly.\n */\n protected printStartUpInfo(opts: { scope: string }) {\n const { scope } = opts;\n const read = (key: string, fallback: string): string =>\n ParseUtility.blankToUndefined({ input: process.env[key] }) ?? fallback;\n const divider = '------------------------------------------------------------------------';\n\n this.logger.for(scope).info(divider);\n this.logger\n .for(scope)\n .info(\n 'Starting application... | Name: %s | Env: %s | Runtime: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_NAME, 'PNT'),\n Environment.ambient,\n this.runtime,\n );\n this.logger\n .for(scope)\n .info(\n 'AllowEmptyEnv: %s | Prefix: %s',\n read('ALLOW_EMPTY_ENV_VALUE', 'true'),\n read('APPLICATION_ENV_PREFIX', 'APP_ENV'),\n );\n this.logger.for(scope).info('RunMode: %s', process.env.RUN_MODE);\n this.logger\n .for(scope)\n .info(\n 'Timezone: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_TIMEZONE, DEFAULT_TEMPORAL_TZ),\n );\n this.logger\n .for(scope)\n .info('LogPath: %s', read(EnvironmentKeys.APP_ENV_LOGGER_FOLDER_PATH, './'));\n this.logger.for(scope).info(divider);\n }\n\n /** Swaps in the `ErrorPrettier`-backed formatter - `node:util`, so the kernel cannot build it. */\n protected override buildErrorMiddleware(): AppErrorMiddleware {\n return new AppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n });\n }\n\n /** Adds what only a listening server has, on top of the kernel's three - which stay in `RestApplication` so a browser Worker answers with the same envelope. */\n protected override async registerDefaultMiddlewares() {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerDefaultMiddlewares.name,\n description: 'Register default application server handler',\n task: async () => {\n const server = this.getServer();\n\n await super.registerDefaultMiddlewares();\n\n // Always installed, not only under `asyncContext.enable`: `tryGetContext()` answers \"no context\"\n // without a store, and a `contextStorage()` the application registered itself stays visible to\n // the enrichers. Inside a method body because every package declares `sideEffects: false`.\n RequestContextRegistry.setResolver({ resolver: () => tryGetContext() });\n\n if (this.configs.asyncContext?.enable) {\n server.use(contextStorage());\n }\n\n // Request-body parsing and the access log; the request id it reads is already installed\n // above (also works around the Bun + Hono body-parsing bug: https://github.com/honojs/middleware/issues/81).\n this.component(RequestTrackerComponent);\n\n server.use(EmojiFaviconMiddleware.create({ icon: this.configs.favicon ?? '🔥' }));\n },\n });\n }\n\n /** Lives here rather than on `AbstractApplication` - `applicationEnvironment` reads `process.env` at module load, so a kernel-pure ancestor cannot carry it; this is the layer that already depends on it. */\n protected validateEnvs() {\n const t = performance.now();\n const envKeys = applicationEnvironment.keys();\n\n // Permissive by DEFAULT: a name a host leaves empty is the host's business, and an empty value\n // already falls back to `defaultValue` at read time, so refusing to boot over one fights the\n // reader rather than helping it. Set ALLOW_EMPTY_ENV_VALUE to `false` or `0` to turn the check\n // on. Read once rather than per key, and a blank value reads as unset - the same rule every\n // other env read follows.\n const configured = ParseUtility.blankToUndefined({ input: process.env.ALLOW_EMPTY_ENV_VALUE });\n const allowsEmpty = configured === undefined || ParseUtility.toBoolean({ input: configured });\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'Envs: %s | START Validating application environments | Empty values: %s',\n envKeys.length,\n allowsEmpty ? 'ALLOWED (default)' : 'REJECTED',\n );\n\n if (allowsEmpty) {\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | SKIPPED - set ALLOW_EMPTY_ENV_VALUE=false to reject empty values',\n envKeys.length,\n );\n\n return;\n }\n\n for (const argKey of envKeys) {\n const argValue = applicationEnvironment.get<string | number>(argKey);\n\n if (!ObjectUtility.isEmpty({ value: argValue })) {\n continue;\n }\n\n throw getError({\n message: `[validateEnvs] Invalid Application Environment! Key: ${argKey} | Value: ${argValue}`,\n });\n }\n\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | DONE Validating application environments | Took: %s (ms)',\n envKeys.length,\n performance.now() - t,\n );\n }\n\n /**\n * Version tripwire, body identical to `RestApplication.initialize()`: a stale kernel without\n * `getBootSequence()`/`runBootSequence()` throws here before any socket binds.\n */\n override async initialize(): Promise<void> {\n await ServerLoggerStartup.selectDefault();\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n protected override getBootSequence(): IBootSequenceStep[] {\n const steps: IBootSequenceStep[] = [\n {\n name: ServerBootSteps.PRINT_START_UP_INFO,\n run: () => this.printStartUpInfo({ scope: this.initialize.name }),\n },\n { name: ServerBootSteps.VALIDATE_ENVS, run: () => this.validateEnvs() },\n {\n name: ServerBootSteps.REGISTER_DEFAULT_MIDDLEWARES,\n run: () => this.registerDefaultMiddlewares(),\n },\n ...super.getBootSequence(),\n ];\n\n const withHydrate = BootSequence.insertAfter({\n steps,\n target: ServerBootSteps.PRE_CONFIGURE,\n step: { name: ServerBootSteps.HYDRATE_SECRETS, run: () => this.hydrateSecrets() },\n });\n\n // Components can contribute datasources, so wire rotatables only after the contributed sweep -\n // a lease key pointing at a component-contributed datasource would otherwise resolve to nothing.\n const withRotatables = BootSequence.insertAfter({\n steps: withHydrate,\n target: ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n step: {\n name: ServerBootSteps.WIRE_SECRET_ROTATABLES,\n run: () => this.wireSecretRotatables(),\n },\n });\n\n return [\n ...withRotatables,\n // Last, so a model registered by a component is covered too.\n {\n name: ServerBootSteps.VALIDATE_SCOPE_FILTER_SUPPORT,\n run: () => this.validateScopeFilterSupport(),\n },\n ];\n }\n\n /**\n * Refuses to start when a model's `settings.access` cannot take effect. Both failures are\n * silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.\n */\n protected validateScopeFilterSupport(): void {\n ScopeFilterUtility.assertScopeFilterSupported({\n asyncContextEnabled: this.configs.asyncContext?.enable ?? false,\n logger: this.logger,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/base/applications/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAS/B,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACp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AC,eAAe,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE;SAClF,CAAC,CAAC;QAEH,+FAA+F;QAC/F,iGAAiG;QACjG,MAAM,cAAc,GAAG,YAAY,CAAC,WAAW,CAAC;YAC9C,KAAK,EAAE,WAAW;YAClB,MAAM,EAAE,eAAe,CAAC,iCAAiC;YACzD,IAAI,EAAE;gBACJ,IAAI,EAAE,eAAe,CAAC,sBAAsB;gBAC5C,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE;aACvC;SACF,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,cAAc;YACjB,6DAA6D;YAC7D;gBACE,IAAI,EAAE,eAAe,CAAC,6BAA6B;gBACnD,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,0BAA0B,EAAE;aAC7C;SACF,CAAC;IACJ,CAAC;IAED;;;OAGG;IACO,0BAA0B;QAClC,kBAAkB,CAAC,0BAA0B,CAAC;YAC5C,mBAAmB,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,IAAI,KAAK;YAC/D,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { ScopeFilterUtility } from '@venizia/ignis-connectors';\nimport { ControllerTransports } from '@venizia/ignis-kernel';\nimport { BindingNamespaces, CoreBindings } from '@venizia/ignis-kernel';\nimport { EnvironmentKeys } from '@/common/environments';\nimport { RequestTrackerComponent } from '@/components';\nimport { GrpcComponent } from '@/components/controller/grpc';\nimport {\n BindingScopes,\n BindingValueTypes,\n BootSequence,\n MetadataRegistry,\n RequestContextRegistry,\n} from '@venizia/ignis-kernel';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type {\n ISecretHydrateEntry,\n ISecretRotatable,\n ISecretsHelper,\n ISecretsRegistration,\n} from '@venizia/ignis-helpers';\nimport { ParseUtility, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, ObjectUtility } from '@venizia/ignis-helpers/common';\nimport { DEFAULT_TEMPORAL_TZ } from '@venizia/ignis-helpers/temporal';\nimport {\n applicationEnvironment,\n SecretsHelperFactory,\n PerformanceUtility,\n Environment,\n SecretProviders,\n} from '@venizia/ignis-helpers';\nimport { contextStorage, tryGetContext } from 'hono/context-storage';\nimport { AppErrorMiddleware, EmojiFaviconMiddleware } from '../middlewares';\nimport { serveStatic } from 'hono/bun';\nimport { ServerLoggerStartup } from './common';\nimport { ServerBootSteps } from './boot-steps';\nimport { ServerApplication } from './server';\nimport type { IRestApplication } from '@venizia/ignis-kernel';\nimport type { IBootSequenceStep } from '@venizia/ignis-kernel';\n\n/** Maps a secret bundle to env names: the explicit `keys` mapping when present, otherwise every bundle key under `prefix`. */\nconst selectSecretEnvKeys = (opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n}): Record<string, string> => {\n const { bundle, entry } = opts;\n const merged: Record<string, string> = {};\n\n if (!entry.keys) {\n const bundleEntries = Object.entries(bundle);\n\n for (const [rawKey, value] of bundleEntries) {\n merged[`${entry.prefix ?? ''}${rawKey}`] = value;\n }\n\n return merged;\n }\n\n const entryKeysEntries = Object.entries(entry.keys);\n\n for (const [rawKey, envKey] of entryKeysEntries) {\n const value = bundle[rawKey];\n\n if (value === undefined) {\n continue;\n }\n\n merged[envKey] = value;\n }\n\n return merged;\n};\n\n/**\n * The IGNIS server application: a `ServerApplication` that adds secrets hydration, env validation, start-up info and the gRPC controller branch. Extend it to build an application.\n *\n * @example\n * ```typescript\n * import { BaseApplication, type IApplicationInfo } from '@venizia/ignis';\n *\n * class App extends BaseApplication {\n * getAppInfo(): IApplicationInfo { return { name: 'app', version: '1.0.0', description: 'Demo' }; }\n * staticConfigure(): void {}\n * preConfigure(): void {}\n * postConfigure(): void {}\n * setupMiddlewares(): void {}\n * }\n * const app = new App({ scope: 'App', config: { host: '0.0.0.0', port: 3000, path: { base: '/api', isStrict: true } } });\n * app.init();\n * await app.start();\n * ```\n */\nexport abstract class BaseApplication extends ServerApplication implements IRestApplication {\n protected secretsProvider?: ISecretsHelper;\n protected secretsRegistration?: ISecretsRegistration;\n\n protected normalizePath(...segments: string[]): string {\n const joined = segments.join('/').replace(/\\/+/g, '/').replace(/\\/$/, '');\n\n return joined || '/';\n }\n\n /** Adds the gRPC branch the kernel cannot own: `GrpcComponent` needs `AbstractGrpcController`, core-only code that reaches `node:module`. */\n override async registerControllers(): Promise<void> {\n await super.registerControllers();\n\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n description: 'Register application gRPC controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n for (const transport of transports) {\n if (transport === ControllerTransports.REST) {\n continue;\n }\n\n if (transport !== ControllerTransports.GRPC) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[registerControllers] Unsupported transport: '${transport}'`,\n });\n }\n\n const grpcComponent = new GrpcComponent(this);\n await grpcComponent.configure();\n }\n\n // Warn if gRPC controllers exist but gRPC transport is not enabled\n if (transports.includes(ControllerTransports.GRPC)) {\n return;\n }\n\n const allBindings = this.findByTag({ tag: BindingNamespaces.CONTROLLER });\n\n for (const binding of allBindings) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n\n if (!target) {\n continue;\n }\n\n const metadata = MetadataRegistry.getInstance().getControllerMetadata({ target });\n\n if (metadata?.transport !== ControllerTransports.GRPC) {\n continue;\n }\n\n this.logger\n .for(this.registerControllers.name)\n .error(\n 'gRPC controller \"%s\" discovered but gRPC transport is not enabled. Add \"%s\" to transports config.',\n binding.key,\n ControllerTransports.GRPC,\n );\n }\n },\n });\n }\n\n registerSecrets(): ValueOrPromise<ISecretsRegistration> {\n return { provider: SecretProviders.SYSTEM_ENVS };\n }\n\n async hydrateSecrets(): Promise<void> {\n const logger = this.logger.for(this.hydrateSecrets.name);\n const registration = await this.registerSecrets();\n\n let provider: ISecretsHelper | undefined;\n const emptyHydrations: string[] = [];\n\n try {\n const result = await SecretsHelperFactory.create({ ...registration, identifier: 'app' });\n provider = result;\n await provider.configure();\n\n await this.hydrateSecretEntries({ provider, registration, emptyHydrations, logger });\n\n const registrationLease = registration.lease ?? [];\n\n for (const entry of registrationLease) {\n await provider.lease({ path: entry.path, key: entry.key });\n }\n } catch (error) {\n const env = Environment.current;\n\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Secret provider failed in non-development environment | env: ${env}`,\n });\n }\n\n logger.warn(\n 'Secret provider failed; falling back to system-envs | env: %s | error: %s',\n env,\n error,\n );\n\n if (provider) {\n try {\n await provider.shutdown();\n } catch (shutdownError) {\n logger.error(\n 'Failed to shut down partially-built provider during fallback | error: %s',\n shutdownError,\n );\n }\n }\n\n const result2 = await SecretsHelperFactory.create({\n provider: SecretProviders.SYSTEM_ENVS,\n identifier: 'app',\n });\n provider = result2;\n }\n\n if (!provider) {\n throw getError({ message: '[hydrateSecrets] No secrets provider resolved' });\n }\n\n if (emptyHydrations.length > 0) {\n const env = Environment.current;\n\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Hydrate entries resolved to an empty secret bundle in non-development environment | env: ${env} | paths: ${emptyHydrations.join(', ')}`,\n });\n }\n\n logger.warn(\n 'Hydrate entries resolved to an empty secret bundle; continuing in development | env: %s | paths: %s',\n env,\n emptyHydrations.join(', '),\n );\n }\n\n this.bind<ISecretsHelper>({ key: CoreBindings.APPLICATION_CONFIG })\n .toProvider(() => provider)\n .setScope(BindingScopes.SINGLETON);\n\n this.registerPostStopHook({ identifier: 'secrets.shutdown', hook: () => provider.shutdown() });\n this.secretsProvider = provider;\n this.secretsRegistration = registration;\n }\n\n /** Applies each hydrate entry in declaration order; paths that resolve empty while declaring an expectation are collected in `emptyHydrations` rather than failing here. */\n protected async hydrateSecretEntries(opts: {\n provider: ISecretsHelper;\n registration: ISecretsRegistration;\n emptyHydrations: string[];\n logger: ILogger;\n }): Promise<void> {\n const { provider, registration, emptyHydrations, logger } = opts;\n\n const registrationHydrate = registration.hydrate ?? [];\n\n for (const entry of registrationHydrate) {\n const bundle = await provider.getBundle({ path: entry.path });\n const merged = this.mergeSecretsIntoEnv({ bundle, entry });\n\n if (Object.keys(merged).length > 0) {\n continue;\n }\n\n if (this.hydrateEntryDeclaresExpectation({ entry })) {\n emptyHydrations.push(entry.path);\n continue;\n }\n\n logger.warn(\n 'Hydrate entry resolved to an empty bundle and declares no expected keys | path: %s',\n entry.path,\n );\n }\n }\n\n protected mergeSecretsIntoEnv(opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n }): Record<string, string> {\n const { bundle, entry } = opts;\n const merged = selectSecretEnvKeys({ bundle, entry });\n\n const mergedEntries = Object.entries(merged);\n\n for (const [key, value] of mergedEntries) {\n process.env[key] = value;\n }\n\n applicationEnvironment.merge({ envs: merged });\n\n return merged;\n }\n\n /** A hydrate entry declares an expectation only via explicit `keys` or a non-empty `prefix`; such an entry resolving to zero env values is a misconfiguration boot must not silently absorb. */\n protected hydrateEntryDeclaresExpectation(opts: { entry: ISecretHydrateEntry }): boolean {\n const { entry } = opts;\n\n if (entry.keys && Object.keys(entry.keys).length > 0) {\n return true;\n }\n\n return typeof entry.prefix === 'string' && entry.prefix.length > 0;\n }\n\n async wireSecretRotatables(): Promise<void> {\n const logger = this.logger.for(this.wireSecretRotatables.name);\n const provider = this.secretsProvider;\n const registration = this.secretsRegistration;\n\n if (!provider || !registration?.lease?.length) {\n return;\n }\n\n for (const entry of registration.lease) {\n const instance = this.get<ISecretRotatable>({ key: entry.key, isOptional: true });\n\n if (instance && typeof instance.onSecretRotated === 'function') {\n provider.registerRotatable({ key: entry.key, target: instance });\n logger.info('Wired rotatable | key: %s', entry.key);\n continue;\n }\n\n logger.debug('Lease key has no rotatable consumer | key: %s', entry.key);\n }\n }\n\n static(opts: { restPath?: string; folderPath: string }) {\n const { restPath = '*', folderPath } = opts;\n const server = this.getServer();\n\n server.use(restPath, serveStatic({ root: folderPath }));\n\n this.logger\n .for(this.static.name)\n .debug(\n 'Registered static files | runtime: %s | path: %s | folder: %s',\n this.runtime,\n restPath,\n folderPath,\n );\n\n return this;\n }\n\n /**\n * Every value is read HERE, not destructured at module load: an application that loads its\n * `.env` in its own entrypoint does so after this module is imported, and a module-load snapshot\n * would print the defaults for a host that configured everything correctly.\n */\n protected printStartUpInfo(opts: { scope: string }) {\n const { scope } = opts;\n const read = (key: string, fallback: string): string =>\n ParseUtility.blankToUndefined({ input: process.env[key] }) ?? fallback;\n const divider = '------------------------------------------------------------------------';\n\n this.logger.for(scope).info(divider);\n this.logger\n .for(scope)\n .info(\n 'Starting application... | Name: %s | Env: %s | Runtime: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_NAME, 'PNT'),\n Environment.ambient,\n this.runtime,\n );\n this.logger\n .for(scope)\n .info(\n 'AllowEmptyEnv: %s | Prefix: %s',\n read('ALLOW_EMPTY_ENV_VALUE', 'true'),\n read('APPLICATION_ENV_PREFIX', 'APP_ENV'),\n );\n this.logger.for(scope).info('RunMode: %s', process.env.RUN_MODE);\n this.logger\n .for(scope)\n .info(\n 'Timezone: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_TIMEZONE, DEFAULT_TEMPORAL_TZ),\n );\n this.logger\n .for(scope)\n .info('LogPath: %s', read(EnvironmentKeys.APP_ENV_LOGGER_FOLDER_PATH, './'));\n this.logger.for(scope).info(divider);\n }\n\n /** Swaps in the `ErrorPrettier`-backed formatter - `node:util`, so the kernel cannot build it. */\n protected override buildErrorMiddleware(): AppErrorMiddleware {\n return new AppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n });\n }\n\n /** Adds what only a listening server has, on top of the kernel's three - which stay in `RestApplication` so a browser Worker answers with the same envelope. */\n protected override async registerDefaultMiddlewares() {\n await PerformanceUtility.executeWithMeasure({\n logger: this.logger,\n scope: this.registerDefaultMiddlewares.name,\n description: 'Register default application server handler',\n task: async () => {\n const server = this.getServer();\n\n await super.registerDefaultMiddlewares();\n\n // Always installed, not only under `asyncContext.enable`: `tryGetContext()` answers \"no context\"\n // without a store, and a `contextStorage()` the application registered itself stays visible to\n // the enrichers. Inside a method body because every package declares `sideEffects: false`.\n RequestContextRegistry.setResolver({ resolver: () => tryGetContext() });\n\n if (this.configs.asyncContext?.enable) {\n server.use(contextStorage());\n }\n\n // Request-body parsing and the access log; the request id it reads is already installed\n // above (also works around the Bun + Hono body-parsing bug: https://github.com/honojs/middleware/issues/81).\n this.component(RequestTrackerComponent);\n\n server.use(EmojiFaviconMiddleware.create({ icon: this.configs.favicon ?? '🔥' }));\n },\n });\n }\n\n /** Lives here rather than on `AbstractApplication` - `applicationEnvironment` reads `process.env` at module load, so a kernel-pure ancestor cannot carry it; this is the layer that already depends on it. */\n protected validateEnvs() {\n const t = performance.now();\n const envKeys = applicationEnvironment.keys();\n\n // Permissive by DEFAULT: a name a host leaves empty is the host's business, and an empty value\n // already falls back to `defaultValue` at read time, so refusing to boot over one fights the\n // reader rather than helping it. Set ALLOW_EMPTY_ENV_VALUE to `false` or `0` to turn the check\n // on. Read once rather than per key, and a blank value reads as unset - the same rule every\n // other env read follows.\n const configured = ParseUtility.blankToUndefined({ input: process.env.ALLOW_EMPTY_ENV_VALUE });\n const allowsEmpty = configured === undefined || ParseUtility.toBoolean({ input: configured });\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'Envs: %s | START Validating application environments | Empty values: %s',\n envKeys.length,\n allowsEmpty ? 'ALLOWED (default)' : 'REJECTED',\n );\n\n if (allowsEmpty) {\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | SKIPPED - set ALLOW_EMPTY_ENV_VALUE=false to reject empty values',\n envKeys.length,\n );\n\n return;\n }\n\n for (const argKey of envKeys) {\n const argValue = applicationEnvironment.get(argKey);\n\n if (!ObjectUtility.isEmpty({ value: argValue })) {\n continue;\n }\n\n throw getError({\n message: `[validateEnvs] Invalid Application Environment! Key: ${argKey} | Value: ${argValue}`,\n });\n }\n\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | DONE Validating application environments | Took: %s (ms)',\n envKeys.length,\n performance.now() - t,\n );\n }\n\n /**\n * Version tripwire, body identical to `RestApplication.initialize()`: a stale kernel without\n * `getBootSequence()`/`runBootSequence()` throws here before any socket binds.\n */\n override async initialize(): Promise<void> {\n await ServerLoggerStartup.selectDefault();\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n protected override getBootSequence(): IBootSequenceStep[] {\n const steps: IBootSequenceStep[] = [\n {\n name: ServerBootSteps.PRINT_START_UP_INFO,\n run: () => this.printStartUpInfo({ scope: this.initialize.name }),\n },\n { name: ServerBootSteps.VALIDATE_ENVS, run: () => this.validateEnvs() },\n {\n name: ServerBootSteps.REGISTER_DEFAULT_MIDDLEWARES,\n run: () => this.registerDefaultMiddlewares(),\n },\n ...super.getBootSequence(),\n ];\n\n const withHydrate = BootSequence.insertAfter({\n steps,\n target: ServerBootSteps.PRE_CONFIGURE,\n step: { name: ServerBootSteps.HYDRATE_SECRETS, run: () => this.hydrateSecrets() },\n });\n\n // Components can contribute datasources, so wire rotatables only after the contributed sweep -\n // a lease key pointing at a component-contributed datasource would otherwise resolve to nothing.\n const withRotatables = BootSequence.insertAfter({\n steps: withHydrate,\n target: ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n step: {\n name: ServerBootSteps.WIRE_SECRET_ROTATABLES,\n run: () => this.wireSecretRotatables(),\n },\n });\n\n return [\n ...withRotatables,\n // Last, so a model registered by a component is covered too.\n {\n name: ServerBootSteps.VALIDATE_SCOPE_FILTER_SUPPORT,\n run: () => this.validateScopeFilterSupport(),\n },\n ];\n }\n\n /**\n * Refuses to start when a model's `settings.access` cannot take effect. Both failures are\n * silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.\n */\n protected validateScopeFilterSupport(): void {\n ScopeFilterUtility.assertScopeFilterSupported({\n asyncContextEnabled: this.configs.asyncContext?.enable ?? false,\n logger: this.logger,\n });\n }\n}\n"]}
@@ -1,6 +1,9 @@
1
+ import type { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
1
2
  import type { Context, Next } from 'hono';
2
3
  import type { DocumentUITypes } from './constants.js';
3
4
  import type { TConstValue } from '@venizia/ignis-helpers/common';
5
+ /** An OpenAPI security scheme (`apiKey`, `http`, `oauth2`, `openIdConnect`) or a reference to one, as the document registry takes it. */
6
+ export type TApiReferenceSecurityScheme = Parameters<typeof OpenAPIRegistry.prototype.registerComponent<'securitySchemes'>>[2];
4
7
  /** One of the `DocumentUITypes` values. */
5
8
  export type TDocumentUIType = TConstValue<typeof DocumentUITypes>;
6
9
  /**
@@ -47,7 +50,7 @@ export interface IApiReferenceOptions {
47
50
  }>;
48
51
  };
49
52
  uiConfig?: Record<string, unknown>;
50
- securitySchemes?: Record<string, Record<string, unknown>>;
53
+ securitySchemes?: Record<string, TApiReferenceSecurityScheme>;
51
54
  }
52
55
  /** Renders the interactive API documentation page for the OpenAPI document. Register an implementation on `UIProviderFactory` to serve a custom UI. */
53
56
  export interface IUIProvider {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/api-reference/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context, Next } from 'hono';\nimport type { DocumentUITypes } from './constants';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** One of the `DocumentUITypes` values. */\nexport type TDocumentUIType = TConstValue<typeof DocumentUITypes>;\n\n/**\n * Every field is optional: a partially-filled binding falls back to the component defaults.\n *\n * @example\n * ```typescript\n * import { ApiReferenceBindingKeys, type BaseApplication, type IApiReferenceOptions } from '@venizia/ignis';\n *\n * export const bindApiReference = (application: BaseApplication) => {\n * application\n * .bind<IApiReferenceOptions>({ key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS })\n * .toValue({ restOptions: { base: { path: '/docs' }, ui: { type: 'swagger' } } });\n * };\n * ```\n */\nexport interface IApiReferenceOptions {\n restOptions?: {\n base?: { path?: string };\n doc?: { path?: string };\n ui?: { path?: string; type?: TDocumentUIType };\n };\n explorer?: {\n openapi?: string;\n info?: {\n title: string;\n version: string;\n description: string;\n contact?: { name: string; email: string };\n };\n servers?: Array<{\n url: string;\n description?: string;\n }>;\n };\n uiConfig?: Record<string, unknown>;\n securitySchemes?: Record<string, Record<string, unknown>>;\n}\n\n/** Renders the interactive API documentation page for the OpenAPI document. Register an implementation on `UIProviderFactory` to serve a custom UI. */\nexport interface IUIProvider {\n render(context: Context, config: IUIConfig, next: Next): Promise<Response | void>;\n}\n\n/** Input of `IUIProvider.render`. Fields beyond `title` and `url` are passed through to the underlying UI library. */\nexport interface IUIConfig {\n title: string;\n url: string;\n [key: string]: unknown;\n}\n\n/** Selects a registered UI provider by its type name. */\nexport interface IGetProviderParams {\n type: string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/components/api-reference/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';\nimport type { Context, Next } from 'hono';\nimport type { DocumentUITypes } from './constants';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** An OpenAPI security scheme (`apiKey`, `http`, `oauth2`, `openIdConnect`) or a reference to one, as the document registry takes it. */\nexport type TApiReferenceSecurityScheme = Parameters<\n typeof OpenAPIRegistry.prototype.registerComponent<'securitySchemes'>\n>[2];\n\n/** One of the `DocumentUITypes` values. */\nexport type TDocumentUIType = TConstValue<typeof DocumentUITypes>;\n\n/**\n * Every field is optional: a partially-filled binding falls back to the component defaults.\n *\n * @example\n * ```typescript\n * import { ApiReferenceBindingKeys, type BaseApplication, type IApiReferenceOptions } from '@venizia/ignis';\n *\n * export const bindApiReference = (application: BaseApplication) => {\n * application\n * .bind<IApiReferenceOptions>({ key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS })\n * .toValue({ restOptions: { base: { path: '/docs' }, ui: { type: 'swagger' } } });\n * };\n * ```\n */\nexport interface IApiReferenceOptions {\n restOptions?: {\n base?: { path?: string };\n doc?: { path?: string };\n ui?: { path?: string; type?: TDocumentUIType };\n };\n explorer?: {\n openapi?: string;\n info?: {\n title: string;\n version: string;\n description: string;\n contact?: { name: string; email: string };\n };\n servers?: Array<{\n url: string;\n description?: string;\n }>;\n };\n uiConfig?: Record<string, unknown>;\n securitySchemes?: Record<string, TApiReferenceSecurityScheme>;\n}\n\n/** Renders the interactive API documentation page for the OpenAPI document. Register an implementation on `UIProviderFactory` to serve a custom UI. */\nexport interface IUIProvider {\n render(context: Context, config: IUIConfig, next: Next): Promise<Response | void>;\n}\n\n/** Input of `IUIProvider.render`. Fields beyond `title` and `url` are passed through to the underlying UI library. */\nexport interface IUIConfig {\n title: string;\n url: string;\n [key: string]: unknown;\n}\n\n/** Selects a registered UI provider by its type name. */\nexport interface IGetProviderParams {\n type: string;\n}\n"]}
@@ -18,6 +18,7 @@ import { Authentication } from '../auth/index.js';
18
18
  import { ServiceAssertion } from '@venizia/ignis-kernel';
19
19
  import { ApiReferenceBindingKeys, DocumentUITypes } from './common/index.js';
20
20
  import { UIProviderFactory } from './ui/index.js';
21
+ const DEFAULT_OPENAPI_VERSION = '3.0.0';
21
22
  const DEFAULT_API_REFERENCE_OPTIONS = {
22
23
  restOptions: {
23
24
  base: { path: '/doc' },
@@ -25,7 +26,7 @@ const DEFAULT_API_REFERENCE_OPTIONS = {
25
26
  ui: { path: '/explorer', type: 'scalar' },
26
27
  },
27
28
  explorer: {
28
- openapi: '3.0.0',
29
+ openapi: DEFAULT_OPENAPI_VERSION,
29
30
  info: {
30
31
  title: 'API Documentation',
31
32
  version: '1.0.0',
@@ -88,7 +89,7 @@ let ApiReferenceComponent = ApiReferenceComponent_1 = class ApiReferenceComponen
88
89
  const rootRouter = this.application.getRootRouter();
89
90
  const configs = this.application.getProjectConfigs();
90
91
  const appInfo = await this.application.getAppInfo();
91
- explorer.info = {
92
+ const info = {
92
93
  title: appInfo.name,
93
94
  version: appInfo.version,
94
95
  description: appInfo.description,
@@ -104,7 +105,11 @@ let ApiReferenceComponent = ApiReferenceComponent_1 = class ApiReferenceComponen
104
105
  }
105
106
  const docPath = joinRestPath([restOptions.base.path, restOptions.doc.path]);
106
107
  const uiPath = joinRestPath([restOptions.base.path, restOptions.ui.path]);
107
- rootRouter.doc(docPath, explorer);
108
+ rootRouter.doc(docPath, {
109
+ ...explorer,
110
+ openapi: explorer.openapi ?? DEFAULT_OPENAPI_VERSION,
111
+ info,
112
+ });
108
113
  const uiType = restOptions.ui.type ?? DocumentUITypes.SWAGGER;
109
114
  const uiProviderFactory = UIProviderFactory.getInstance();
110
115
  // A custom provider registered on the factory is honoured; only unknown types are rejected.
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../src/components/api-reference/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGzC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAA6B,MAAM,UAAU,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEzC,MAAM,6BAA6B,GAAyB;IAC1D,WAAW,EAAE;QACX,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;QACtB,GAAG,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE;QAC9B,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IA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B,GAAG,EAAE,MAAM;gBACX,GAAG,CAAC,YAAY,EAAE,QAAQ,IAAI,EAAE,CAAC;aAClC,EACD,IAAI,CACL,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,cAAc,CAAC,YAAY,EAAE;YAC3F,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,QAAQ;YAChB,YAAY,EAAE,KAAK;SACpB,CAAC,CAAC;QAEH,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,cAAc,CAAC,cAAc,EAAE;YAC7F,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC;QAEH,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAC1C,iBAAiB,EACjB,cAAc,CAAC,gBAAgB,EAC/B,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAChE,CAAC;QAEF,MAAM,eAAe,GAAG,YAAY,EAAE,eAAe,IAAI,EAAE,CAAC;QAC5D,MAAM,sBAAsB,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QAE/D,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,sBAAsB,EAAE,CAAC;YACpD,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,EAAE,MAAiB,CAAC,CAAC;QAC3F,CAAC;IACH,CAAC;CACF,CAAA;AAhHY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAgHjC","sourcesContent":["import { type BaseApplication } from '@/base/applications';\nimport { inject } from '@/base/metadata';\nimport { type OpenAPIObjectConfigure } from '@hono/zod-openapi';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseComponent, Binding, CoreBindings } from '@venizia/ignis-kernel';\nimport type { Context, Next } from 'hono';\nimport { Authentication } from '../auth';\nimport { ServiceAssertion } from '@venizia/ignis-kernel';\nimport { ApiReferenceBindingKeys, DocumentUITypes, type IApiReferenceOptions } from './common';\nimport { UIProviderFactory } from './ui';\n\nconst DEFAULT_API_REFERENCE_OPTIONS: IApiReferenceOptions = {\n restOptions: {\n base: { path: '/doc' },\n doc: { path: '/openapi.json' },\n ui: { path: '/explorer', type: 'scalar' },\n },\n explorer: {\n openapi: '3.0.0',\n info: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'API documentation for your service',\n },\n },\n};\n\n/** Joins rest path segments into a single absolute path (no empty or duplicated separators). */\nconst joinRestPath = (segments: Array<string | undefined>): string => {\n const joined = segments\n .filter((segment): segment is string => Boolean(segment))\n .join('/')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '');\n\n return joined.startsWith('/') ? joined : `/${joined}`;\n};\n\n/**\n * Serves the OpenAPI document and an interactive UI for it. Paths and UI type come from `IApiReferenceOptions` bound at `ApiReferenceBindingKeys.API_REFERENCE_OPTIONS`; `info` is always taken from the application info.\n *\n * @example\n * ```typescript\n * import { ApiReferenceComponent, BaseApplication } from '@venizia/ignis';\n *\n * abstract class App extends BaseApplication {\n * preConfigure(): void {\n * this.component(ApiReferenceComponent);\n * }\n * }\n * ```\n */\nexport class ApiReferenceComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: ApiReferenceComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [ApiReferenceBindingKeys.API_REFERENCE_OPTIONS]: Binding.bind<IApiReferenceOptions>({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n }).toValue(DEFAULT_API_REFERENCE_OPTIONS),\n },\n });\n }\n\n override async binding() {\n const boundOptions = this.application.get<IApiReferenceOptions>({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n isOptional: true,\n });\n\n const defaultRestOptions = DEFAULT_API_REFERENCE_OPTIONS.restOptions!;\n const restOptions = {\n base: { ...defaultRestOptions.base, ...boundOptions?.restOptions?.base },\n doc: { ...defaultRestOptions.doc, ...boundOptions?.restOptions?.doc },\n ui: { ...defaultRestOptions.ui, ...boundOptions?.restOptions?.ui },\n };\n\n // A fresh explorer object per application: mutating the bound one (or the module default) leaks this application's info/servers into every later application in the process.\n const explorer: NonNullable<IApiReferenceOptions['explorer']> = {\n ...DEFAULT_API_REFERENCE_OPTIONS.explorer,\n ...boundOptions?.explorer,\n };\n\n const rootRouter = this.application.getRootRouter();\n const configs = this.application.getProjectConfigs();\n\n const appInfo = await this.application.getAppInfo();\n explorer.info = {\n title: appInfo.name,\n version: appInfo.version,\n description: appInfo.description,\n contact: appInfo.author,\n };\n\n if (!explorer.servers?.length) {\n explorer.servers = [\n {\n url: ['http://', this.application.getServerAddress(), configs.path.base ?? ''].join(''),\n description: 'Local Application Server URL',\n },\n ];\n }\n\n const docPath = joinRestPath([restOptions.base.path, restOptions.doc.path]);\n const uiPath = joinRestPath([restOptions.base.path, restOptions.ui.path]);\n\n rootRouter.doc(docPath, explorer as OpenAPIObjectConfigure<any, string>);\n\n const uiType = restOptions.ui.type ?? DocumentUITypes.SWAGGER;\n const uiProviderFactory = UIProviderFactory.getInstance();\n\n // A custom provider registered on the factory is honoured; only unknown types are rejected.\n if (!uiProviderFactory.isBound(uiType)) {\n if (!DocumentUITypes.isValid(uiType)) {\n throw getError({\n message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${[...DocumentUITypes.SCHEME_SET]}`,\n });\n }\n\n uiProviderFactory.register({ type: uiType });\n }\n\n const docUrl = joinRestPath([configs.path.base, docPath]);\n const uiProvider = uiProviderFactory.getProvider({ type: uiType });\n\n rootRouter.get(uiPath, async (context: Context, next: Next) => {\n return uiProvider.render(\n context,\n {\n title: appInfo.name,\n url: docUrl,\n ...(boundOptions?.uiConfig ?? {}),\n },\n next,\n );\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_JWT, {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_BASIC, {\n type: 'http',\n scheme: 'basic',\n });\n\n rootRouter.openAPIRegistry.registerComponent(\n 'securitySchemes',\n Authentication.STRATEGY_SERVICE,\n { type: 'apiKey', in: 'header', name: ServiceAssertion.HEADER },\n );\n\n const securitySchemes = boundOptions?.securitySchemes ?? {};\n const securitySchemesEntries = Object.entries(securitySchemes);\n\n for (const [name, scheme] of securitySchemesEntries) {\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', name, scheme as AnyType);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../src/components/api-reference/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAA6B,MAAM,UAAU,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEzC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAExC,MAAM,6BAA6B,GAAyB;IAC1D,WAAW,EAAE;QACX,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;QACtB,GAAG,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE;QAC9B,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,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port { getError } from '@venizia/ignis-helpers/core';\nimport { BaseComponent, Binding, CoreBindings } from '@venizia/ignis-kernel';\nimport type { Context, Next } from 'hono';\nimport { Authentication } from '../auth';\nimport { ServiceAssertion } from '@venizia/ignis-kernel';\nimport { ApiReferenceBindingKeys, DocumentUITypes, type IApiReferenceOptions } from './common';\nimport { UIProviderFactory } from './ui';\n\nconst DEFAULT_OPENAPI_VERSION = '3.0.0';\n\nconst DEFAULT_API_REFERENCE_OPTIONS: IApiReferenceOptions = {\n restOptions: {\n base: { path: '/doc' },\n doc: { path: '/openapi.json' },\n ui: { path: '/explorer', type: 'scalar' },\n },\n explorer: {\n openapi: DEFAULT_OPENAPI_VERSION,\n info: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'API documentation for your service',\n },\n },\n};\n\n/** Joins rest path segments into a single absolute path (no empty or duplicated separators). */\nconst joinRestPath = (segments: Array<string | undefined>): string => {\n const joined = segments\n .filter((segment): segment is string => Boolean(segment))\n .join('/')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '');\n\n return joined.startsWith('/') ? joined : `/${joined}`;\n};\n\n/**\n * Serves the OpenAPI document and an interactive UI for it. Paths and UI type come from `IApiReferenceOptions` bound at `ApiReferenceBindingKeys.API_REFERENCE_OPTIONS`; `info` is always taken from the application info.\n *\n * @example\n * ```typescript\n * import { ApiReferenceComponent, BaseApplication } from '@venizia/ignis';\n *\n * abstract class App extends BaseApplication {\n * preConfigure(): void {\n * this.component(ApiReferenceComponent);\n * }\n * }\n * ```\n */\nexport class ApiReferenceComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: ApiReferenceComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [ApiReferenceBindingKeys.API_REFERENCE_OPTIONS]: Binding.bind<IApiReferenceOptions>({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n }).toValue(DEFAULT_API_REFERENCE_OPTIONS),\n },\n });\n }\n\n override async binding() {\n const boundOptions = this.application.get<IApiReferenceOptions>({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n isOptional: true,\n });\n\n const defaultRestOptions = DEFAULT_API_REFERENCE_OPTIONS.restOptions!;\n const restOptions = {\n base: { ...defaultRestOptions.base, ...boundOptions?.restOptions?.base },\n doc: { ...defaultRestOptions.doc, ...boundOptions?.restOptions?.doc },\n ui: { ...defaultRestOptions.ui, ...boundOptions?.restOptions?.ui },\n };\n\n // A fresh explorer object per application: mutating the bound one (or the module default) leaks this application's info/servers into every later application in the process.\n const explorer: NonNullable<IApiReferenceOptions['explorer']> = {\n ...DEFAULT_API_REFERENCE_OPTIONS.explorer,\n ...boundOptions?.explorer,\n };\n\n const rootRouter = this.application.getRootRouter();\n const configs = this.application.getProjectConfigs();\n\n const appInfo = await this.application.getAppInfo();\n const info = {\n title: appInfo.name,\n version: appInfo.version,\n description: appInfo.description,\n contact: appInfo.author,\n };\n\n if (!explorer.servers?.length) {\n explorer.servers = [\n {\n url: ['http://', this.application.getServerAddress(), configs.path.base ?? ''].join(''),\n description: 'Local Application Server URL',\n },\n ];\n }\n\n const docPath = joinRestPath([restOptions.base.path, restOptions.doc.path]);\n const uiPath = joinRestPath([restOptions.base.path, restOptions.ui.path]);\n\n rootRouter.doc(docPath, {\n ...explorer,\n openapi: explorer.openapi ?? DEFAULT_OPENAPI_VERSION,\n info,\n });\n\n const uiType = restOptions.ui.type ?? DocumentUITypes.SWAGGER;\n const uiProviderFactory = UIProviderFactory.getInstance();\n\n // A custom provider registered on the factory is honoured; only unknown types are rejected.\n if (!uiProviderFactory.isBound(uiType)) {\n if (!DocumentUITypes.isValid(uiType)) {\n throw getError({\n message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${[...DocumentUITypes.SCHEME_SET]}`,\n });\n }\n\n uiProviderFactory.register({ type: uiType });\n }\n\n const docUrl = joinRestPath([configs.path.base, docPath]);\n const uiProvider = uiProviderFactory.getProvider({ type: uiType });\n\n rootRouter.get(uiPath, async (context: Context, next: Next) => {\n return uiProvider.render(\n context,\n {\n title: appInfo.name,\n url: docUrl,\n ...(boundOptions?.uiConfig ?? {}),\n },\n next,\n );\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_JWT, {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_BASIC, {\n type: 'http',\n scheme: 'basic',\n });\n\n rootRouter.openAPIRegistry.registerComponent(\n 'securitySchemes',\n Authentication.STRATEGY_SERVICE,\n { type: 'apiKey', in: 'header', name: ServiceAssertion.HEADER },\n );\n\n const securitySchemes = boundOptions?.securitySchemes ?? {};\n const securitySchemesEntries = Object.entries(securitySchemes);\n\n for (const [name, scheme] of securitySchemesEntries) {\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', name, scheme);\n }\n }\n}\n"]}
@@ -63,6 +63,7 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
63
63
  }
64
64
  const options = { restOptions, jwtOptions, basicOptions, serviceOptions };
65
65
  if (jwtOptions) {
66
+ const standard = jwtOptions.standard;
66
67
  switch (jwtOptions.standard) {
67
68
  case JOSEStandards.JWS: {
68
69
  this.defineJWSAuth({ options: jwtOptions.options });
@@ -74,7 +75,7 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
74
75
  }
75
76
  default: {
76
77
  throw getError({
77
- message: `[AuthenticateComponent] Unknown JOSE standard: ${jwtOptions.standard}`,
78
+ message: `[AuthenticateComponent] Unknown JOSE standard: ${standard}`,
78
79
  });
79
80
  }
80
81
  }
@@ -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,EA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AC,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 listed 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.build(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,OAA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,WAAW,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC;IACrF,CAAC;IAEO,iBAAiB,CAAC,IAAuC;QAC/D,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QAEjD,IAAI,CAAC,WAAW,EAAE,iBAAiB,EAAE,CAAC;YACpC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,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,KAAK,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAC/E,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;AA/VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA+VjC","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 const standard: string = jwtOptions.standard;\n\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: ${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 listed 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.build(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"]}
@@ -23,8 +23,8 @@ export declare class AuthControllerFactory {
23
23
  scope: string;
24
24
  args: unknown;
25
25
  task: () => Promise<R>;
26
- }): Promise<any>;
27
- normalizeCountData<ResponseSchema extends unknown, RequestContext extends import("@venizia/ignis-kernel").TRouteContext<import("hono").Env> = import("@venizia/ignis-kernel").TRouteContext<import("hono").Env>, ResponseData extends {
26
+ }): Promise<R>;
27
+ normalizeCountData<ResponseSchema, RequestContext extends import("@venizia/ignis-kernel").TRouteContext<import("hono").Env> = import("@venizia/ignis-kernel").TRouteContext<import("hono").Env>, ResponseData extends {
28
28
  count: number;
29
29
  data?: import("@venizia/ignis-helpers").TNullable<ResponseSchema>;
30
30
  } = {
@@ -108,7 +108,7 @@ export declare abstract class AbstractBearerTokenService<E extends Env = Env> ex
108
108
  */
109
109
  protected applySignClaims(opts: {
110
110
  signer: SignJWT;
111
- payload: Record<string, any>;
111
+ payload: Record<string, unknown>;
112
112
  claims?: IJWTIssueClaims;
113
113
  }): SignJWT;
114
114
  decryptPayload(opts: {
@@ -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,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B;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,IAAI,CAAC,0BAA0B,CAAC,cAAc,CAAC,EAAE,CAAC,EAAE,CAAC;YACnD,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,YAAY;gBAC9C,OAAO,EAAE,uDAAuD;aACjE,CAAC,CAAC;QACL,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,oEAAoE;IAC5D,MAAM,CAAC,cAAc,CAAC,KAA8B;QAC1D,OAAO,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,CAAC;IACzD,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: unknown }): 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, unknown>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, unknown> = {};\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: Record<string, unknown> = {};\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 encryptedValue = payload[key];\n\n if (typeof encryptedValue !== 'string') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.Unauthorized,\n message: '[decryptPayload] An encrypted claim is not a string',\n });\n }\n\n const decryptedValue = await this.aes.decrypt({\n message: encryptedValue,\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n if (!AbstractBearerTokenService.isTokenPayload(rs)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.Unauthorized,\n message: '[decryptPayload] The decrypted claims carry no userId',\n });\n }\n\n return rs;\n }\n\n /** A decrypted claim set is a payload only if it names its user. */\n private static isTokenPayload(value: Record<string, unknown>): value is IJWTTokenPayload {\n return 'userId' in value && value.userId !== undefined;\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,G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cAAc,CAAC,KAA8B;QAC1D,OAAO,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,CAAC;IACzD,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: unknown }): 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, unknown>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, unknown> = {};\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, unknown>;\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: Record<string, unknown> = {};\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 encryptedValue = payload[key];\n\n if (typeof encryptedValue !== 'string') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.Unauthorized,\n message: '[decryptPayload] An encrypted claim is not a string',\n });\n }\n\n const decryptedValue = await this.aes.decrypt({\n message: encryptedValue,\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n if (!AbstractBearerTokenService.isTokenPayload(rs)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.Unauthorized,\n message: '[decryptPayload] The decrypted claims carry no userId',\n });\n }\n\n return rs;\n }\n\n /** A decrypted claim set is a payload only if it names its user. */\n private static isTokenPayload(value: Record<string, unknown>): value is IJWTTokenPayload {\n return 'userId' in value && value.userId !== undefined;\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"]}