@venizia/ignis 0.4.8-5 → 0.4.8-6

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 (22) hide show
  1. package/dist/esm/base/applications/server.d.ts +12 -0
  2. package/dist/esm/base/applications/server.js +11 -0
  3. package/dist/esm/base/applications/server.js.map +1 -1
  4. package/dist/esm/components/auth/authenticate/component.js +1 -1
  5. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  6. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +17 -6
  7. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +85 -22
  8. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -1
  9. package/dist/esm/components/auth/authorize/adapters/base-filtered.d.ts +1 -1
  10. package/dist/esm/components/auth/authorize/adapters/base-filtered.js +3 -2
  11. package/dist/esm/components/auth/authorize/adapters/base-filtered.js.map +1 -1
  12. package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +2 -0
  13. package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
  14. package/dist/esm/components/auth/authorize/adapters/connector.d.ts +2 -2
  15. package/dist/esm/components/auth/authorize/adapters/connector.js +3 -2
  16. package/dist/esm/components/auth/authorize/adapters/connector.js.map +1 -1
  17. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js +1 -1
  18. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
  19. package/dist/presets/app/preset.json +4 -4
  20. package/dist/presets/lib/preset.json +3 -3
  21. package/dist/presets/shared/preset.json +1 -1
  22. package/package.json +8 -8
@@ -1,3 +1,4 @@
1
+ import { OpenAPIHono } from '@hono/zod-openapi';
1
2
  import { RestApplication } from '@venizia/ignis-kernel';
2
3
  import type { Env, Schema } from 'hono';
3
4
  import type { IServerApplication, IServerApplicationConfigs, IServerRuntimeConfigs, IShutdownSignalsOptions } from './common/index.js';
@@ -41,6 +42,17 @@ export declare abstract class ServerApplication<AppEnv extends Env = Env, AppSch
41
42
  scope: string;
42
43
  config: IServerApplicationConfigs;
43
44
  });
45
+ /** Both routers are `OpenAPIHono` (see `createRouter`). */
46
+ protected server: {
47
+ hono: OpenAPIHono<AppEnv, AppSchema, BasePath>;
48
+ };
49
+ protected rootRouter: OpenAPIHono<AppEnv, AppSchema, BasePath>;
50
+ /** Always an `OpenAPIHono`, whatever else is loaded: the API reference reads `rootRouter.openAPIRegistry`. */
51
+ protected createRouter(opts: {
52
+ strict: boolean;
53
+ }): OpenAPIHono<AppEnv, AppSchema, BasePath>;
54
+ getServer(): OpenAPIHono<AppEnv, AppSchema, BasePath>;
55
+ getRootRouter(): OpenAPIHono<AppEnv, AppSchema, BasePath>;
44
56
  /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */
45
57
  protected getDefaultAsyncContextEnabled(): boolean;
46
58
  /** `configs.projectRoot` wins, else the process cwd. The value is bound AND handed to `ModuleUtility`, so every peer lookup (optional modules, the gRPC adapter) resolves under it - a compiled binary sets it to where its `node_modules` really is. */
@@ -1,3 +1,4 @@
1
+ import { OpenAPIHono } from '@hono/zod-openapi';
1
2
  import { CoreBindings, RestApplication } from '@venizia/ignis-kernel';
2
3
  import { ModuleUtility } from '@venizia/ignis-helpers';
3
4
  import { getError } from '@venizia/ignis-helpers/core';
@@ -87,6 +88,16 @@ export class ServerApplication extends RestApplication {
87
88
  candidates: [opts.config.port, process.env.PORT, process.env.APP_ENV_SERVER_PORT],
88
89
  });
89
90
  }
91
+ /** Always an `OpenAPIHono`, whatever else is loaded: the API reference reads `rootRouter.openAPIRegistry`. */
92
+ createRouter(opts) {
93
+ return new OpenAPIHono({ strict: opts.strict });
94
+ }
95
+ getServer() {
96
+ return this.server.hono;
97
+ }
98
+ getRootRouter() {
99
+ return this.rootRouter;
100
+ }
90
101
  /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */
91
102
  getDefaultAsyncContextEnabled() {
92
103
  return true;
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,MAAM,SAAS,GAAG,GAAG,EAAE;YACrB,YAAY,CAAC,KAAK,CAAC,CAAC;YAEpB,KAAK,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC7C,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAChC,CAAC;YAED,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC,CAAC;QAEF,IAAI,CAAC,eAAe,GAAG,EAAE,SAAS,EAAE,CAAC;QAErC,OAAO,SAAS,CAAC;IACnB,CAAC;IAES,KAAK,CAAC,UAAU;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC;QAErC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;YAEjF,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAEtB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport { ModuleUtility } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { RuntimeModules } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type {\n IServerApplication,\n IServerApplicationConfigs,\n IServerRuntimeConfigs,\n IShutdownSignalsOptions,\n} from './common';\n\n/** Lives here, not in the kernel: `Bun.serve` resolves only through `@types/bun`, and emitting `Bun` into the kernel's published `.d.ts` would force that dependency on every browser consumer of `@venizia/ignis-kernel`. This package legitimately has Bun types - it is the layer that calls `Bun.serve`. */\nexport type TBunServerInstance = ReturnType<typeof Bun.serve>;\n\nconst MINIMUM_BUN = { major: 1, minor: 4 };\n\n/** What the process runs on. `Bun` is the one global that tells the runtimes apart, and it cannot be hidden in a test, so the guard reads this snapshot instead. */\nexport interface IRuntimeSnapshot {\n /** `Bun.version`, set only under Bun. */\n bunVersion?: string;\n /** `process.release.name` and `process.version` of a runtime that is not Bun (`node`, `v24.14.0`). */\n otherName?: string;\n otherVersion?: string;\n}\n\n/** The Bun-only guard: what the process runs on, and the refusal when it is not Bun 1.4 or later. */\nexport class BunRuntimeGuard {\n /** Reads the runtime the process is on. */\n static readSnapshot(): IRuntimeSnapshot {\n return {\n bunVersion: RuntimeModules.isBun() ? Bun.version : undefined,\n otherName: globalThis.process?.release?.name,\n otherVersion: globalThis.process?.version,\n };\n }\n\n private static describeRuntime(opts: { runtime: IRuntimeSnapshot }): string {\n const { bunVersion, otherName, otherVersion } = opts.runtime;\n\n if (bunVersion !== undefined) {\n return `bun ${bunVersion}`;\n }\n\n return otherName ? `${otherName} ${otherVersion ?? ''}`.trim() : 'an unknown runtime';\n }\n\n /**\n * IGNIS runs on Bun 1.4 or later, and nothing else. One refusal at the top of `start()`, before any\n * hook, datasource or socket is touched, replaces a failure that would otherwise surface halfway\n * through startup.\n */\n static assert(opts: { runtime?: IRuntimeSnapshot } = {}): void {\n const runtime = opts.runtime ?? BunRuntimeGuard.readSnapshot();\n\n if (runtime.bunVersion !== undefined) {\n const [major = 0, minor = 0] = runtime.bunVersion.split('.').map(Number);\n\n if (\n major > MINIMUM_BUN.major ||\n (major === MINIMUM_BUN.major && minor >= MINIMUM_BUN.minor)\n ) {\n return;\n }\n }\n\n throw getError({\n message: `IGNIS requires Bun >= ${MINIMUM_BUN.major}.${MINIMUM_BUN.minor} (running on ${BunRuntimeGuard.describeRuntime({ runtime })})`,\n });\n }\n}\n\nconst DEFAULT_SHUTDOWN_SIGNALS: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 15_000;\n\nconst DEFAULT_SERVER_HOST = 'localhost';\nconst DEFAULT_SERVER_PORT = 3000;\nconst MAX_SERVER_PORT = 65535;\n\n/**\n * The first candidate USABLE as a port. Rejection is on validity, never falsiness: `0` legitimately\n * asks the OS for an ephemeral port, and taking the first TRUTHY value instead let an unusable\n * `PORT` shadow a usable `APP_ENV_SERVER_PORT` - `PORT=abc APP_ENV_SERVER_PORT=8080` bound 3000, as\n * did Docker's legacy container-link form `PORT=tcp://172.17.0.5:8080`.\n */\nconst resolveServerPort = (opts: { candidates: Array<number | string | undefined> }): number => {\n for (const candidate of opts.candidates) {\n if (candidate === undefined || candidate === null) {\n continue;\n }\n\n const normalized = typeof candidate === 'string' ? candidate.trim() : candidate;\n\n if (normalized === '') {\n continue;\n }\n\n const parsed = Number(normalized);\n\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > MAX_SERVER_PORT) {\n continue;\n }\n\n return parsed;\n }\n\n return DEFAULT_SERVER_PORT;\n};\n\n/** Adds the listening server (`Bun.serve`) on top of `RestApplication` - the only layer that touches a socket, so it is the layer that stays out of the browser-pure kernel. */\nexport abstract class ServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n>\n extends RestApplication<AppEnv, AppSchema, BasePath>\n implements IServerApplication<AppEnv, AppSchema, BasePath>\n{\n /** Which runtime is underneath, and the socket once one is bound. Both live here, not on `RestApplication`: a browser Worker has neither. `start()` refuses to run unless this is Bun. */\n protected runtime = RuntimeModules.detect();\n protected serverInstance?: TBunServerInstance;\n\n /** Widened by this layer, which is the only one that binds a socket. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IServerApplicationConfigs;\n\n /**\n * The address resolution the kernel deliberately does not do: `host` and `port` mean nothing to a\n * host with no socket, and resolving them there silently configured every browser Worker with\n * `localhost:3000`. Env is the fallback, explicit config always wins.\n */\n constructor(opts: { scope: string; config: IServerApplicationConfigs }) {\n super(opts);\n\n this.configs.host =\n [opts.config.host, process.env.HOST, process.env.APP_ENV_SERVER_HOST].find(Boolean) ??\n DEFAULT_SERVER_HOST;\n this.configs.port = resolveServerPort({\n candidates: [opts.config.port, process.env.PORT, process.env.APP_ENV_SERVER_PORT],\n });\n }\n\n /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */\n protected override getDefaultAsyncContextEnabled(): boolean {\n return true;\n }\n\n /** `configs.projectRoot` wins, else the process cwd. The value is bound AND handed to `ModuleUtility`, so every peer lookup (optional modules, the gRPC adapter) resolves under it - a compiled binary sets it to where its `node_modules` really is. */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? process.cwd();\n\n if (this.configs.projectRoot && !existsSync(path.join(projectRoot, 'node_modules'))) {\n this.logger\n .for(this.getProjectRoot.name)\n .warn(\n 'configs.projectRoot has no node_modules | root: %s | optional peers will not resolve from it',\n projectRoot,\n );\n }\n\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ModuleUtility.setProjectRoot({ projectRoot });\n\n return projectRoot;\n }\n\n getServerHost(): string {\n return this.configs.host!;\n }\n\n getServerPort(): number {\n return this.configs.port!;\n }\n\n getServerAddress() {\n return `${this.getServerHost()}:${this.getServerPort()}`;\n }\n\n /** `configs.server` with unset keys dropped, so a missing option keeps Bun's default instead of passing `undefined`. */\n protected getServerRuntimeOptions(): IServerRuntimeConfigs {\n const { idleTimeout, maxRequestBodySize } = this.configs.server ?? {};\n\n return {\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n ...(maxRequestBodySize === undefined ? {} : { maxRequestBodySize }),\n };\n }\n\n /** What `start()` checks. A seam for the guard's test: the `Bun` global cannot be hidden from inside Bun. */\n protected getRuntimeSnapshot(): IRuntimeSnapshot {\n return BunRuntimeGuard.readSnapshot();\n }\n\n getServerInstance<T extends TBunServerInstance = TBunServerInstance>(): T | undefined {\n return this.serverInstance as T | undefined;\n }\n\n protected startBunModule() {\n return new Promise((resolve, reject) => {\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n\n Promise.resolve(\n Bun.serve({\n port,\n hostname: host,\n fetch: server.fetch,\n ...this.getServerRuntimeOptions(),\n }),\n )\n .then((rs) => {\n this.serverInstance = rs;\n this.configs.port = rs.port;\n this.inspectRoutes();\n\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s', this.getServerAddress());\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n resolve(rs);\n })\n .catch(reject);\n });\n }\n\n async start() {\n BunRuntimeGuard.assert({ runtime: this.getRuntimeSnapshot() });\n\n await this.initialize();\n await this.setupMiddlewares();\n\n const server = this.getServer();\n server.route(this.configs.path.base, this.rootRouter);\n\n await this.startBunModule();\n\n await this.executePostStartHooks();\n }\n\n /** Post-stop hooks, then the server, then the datasources - closed even when the server fails to, so a stopped application holds no connection. */\n async stop() {\n await this.executePostStopHooks();\n\n try {\n await this.stopServer();\n } finally {\n await this.closeDataSources();\n }\n }\n\n /** Set once `installShutdownSignals` ran; holds the way back, so a second call is a no-op. */\n protected shutdownSignals?: { uninstall: () => void };\n\n /**\n * Stops the application on a signal (SIGTERM and SIGINT by default), then exits the process.\n * Opt-in: nothing is installed until you call it, usually right after `start()`.\n *\n * - Calls `stop()` once. A second signal while it runs is ignored.\n * - Exits 0 when `stop()` finishes, 1 when it throws or does not finish within `timeoutMs`.\n * - Idempotent: calling it again returns the same uninstall function and adds no listener.\n * - Returns an uninstall function that removes the listeners and the pending timeout.\n */\n installShutdownSignals(opts: IShutdownSignalsOptions = {}): () => void {\n if (this.shutdownSignals) {\n return this.shutdownSignals.uninstall;\n }\n\n const {\n signals = DEFAULT_SHUTDOWN_SIGNALS,\n timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,\n exit = (code: number) => process.exit(code),\n } = opts;\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw getError({\n message: `[installShutdownSignals] timeoutMs must be a positive number of milliseconds | value: ${String(timeoutMs)}`,\n });\n }\n\n const log = this.logger.for(this.installShutdownSignals.name);\n let isShuttingDown = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const finish = (code: number) => {\n clearTimeout(timer);\n exit(code);\n };\n\n const onSignal = (signal: NodeJS.Signals) => {\n if (isShuttingDown) {\n log.warn('Signal %s ignored | shutdown already in progress', signal);\n\n return;\n }\n\n isShuttingDown = true;\n log.info('Signal %s received | stopping the application | timeout: %s ms', signal, timeoutMs);\n\n timer = setTimeout(() => {\n log.error('Shutdown did not finish within %s ms | forcing exit', timeoutMs);\n exit(1);\n }, timeoutMs);\n\n this.stop().then(\n () => {\n log.info('Application stopped | exiting');\n finish(0);\n },\n (error: unknown) => {\n log.error(\n 'Shutdown failed | error: %s',\n error instanceof Error ? error.message : String(error),\n );\n finish(1);\n },\n );\n };\n\n const listeners = signals.map((signal) => {\n const listener = () => onSignal(signal);\n process.on(signal, listener);\n\n return { signal, listener };\n });\n\n const uninstall = () => {\n clearTimeout(timer);\n\n for (const { signal, listener } of listeners) {\n process.off(signal, listener);\n }\n\n this.shutdownSignals = undefined;\n };\n\n this.shutdownSignals = { uninstall };\n\n return uninstall;\n }\n\n protected async stopServer(): Promise<void> {\n const instance = this.serverInstance;\n\n if (!instance) {\n this.logger.for(this.stop.name).info('Server was not started | Nothing to stop');\n\n return;\n }\n\n await instance.stop();\n\n this.serverInstance = undefined;\n this.logger.for(this.stop.name).info('Server STOPPED');\n }\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/base/applications/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,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AM,EAAE,QAAQ,CAAC,CAAC;YAE7B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,MAAM,SAAS,GAAG,GAAG,EAAE;YACrB,YAAY,CAAC,KAAK,CAAC,CAAC;YAEpB,KAAK,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC7C,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAChC,CAAC;YAED,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC,CAAC;QAEF,IAAI,CAAC,eAAe,GAAG,EAAE,SAAS,EAAE,CAAC;QAErC,OAAO,SAAS,CAAC;IACnB,CAAC;IAES,KAAK,CAAC,UAAU;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC;QAErC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;YAEjF,OAAO;QACT,CAAC;QAED,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAEtB,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import { OpenAPIHono } from '@hono/zod-openapi';\nimport { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport { ModuleUtility } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { RuntimeModules } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type {\n IServerApplication,\n IServerApplicationConfigs,\n IServerRuntimeConfigs,\n IShutdownSignalsOptions,\n} from './common';\n\n/** Lives here, not in the kernel: `Bun.serve` resolves only through `@types/bun`, and emitting `Bun` into the kernel's published `.d.ts` would force that dependency on every browser consumer of `@venizia/ignis-kernel`. This package legitimately has Bun types - it is the layer that calls `Bun.serve`. */\nexport type TBunServerInstance = ReturnType<typeof Bun.serve>;\n\nconst MINIMUM_BUN = { major: 1, minor: 4 };\n\n/** What the process runs on. `Bun` is the one global that tells the runtimes apart, and it cannot be hidden in a test, so the guard reads this snapshot instead. */\nexport interface IRuntimeSnapshot {\n /** `Bun.version`, set only under Bun. */\n bunVersion?: string;\n /** `process.release.name` and `process.version` of a runtime that is not Bun (`node`, `v24.14.0`). */\n otherName?: string;\n otherVersion?: string;\n}\n\n/** The Bun-only guard: what the process runs on, and the refusal when it is not Bun 1.4 or later. */\nexport class BunRuntimeGuard {\n /** Reads the runtime the process is on. */\n static readSnapshot(): IRuntimeSnapshot {\n return {\n bunVersion: RuntimeModules.isBun() ? Bun.version : undefined,\n otherName: globalThis.process?.release?.name,\n otherVersion: globalThis.process?.version,\n };\n }\n\n private static describeRuntime(opts: { runtime: IRuntimeSnapshot }): string {\n const { bunVersion, otherName, otherVersion } = opts.runtime;\n\n if (bunVersion !== undefined) {\n return `bun ${bunVersion}`;\n }\n\n return otherName ? `${otherName} ${otherVersion ?? ''}`.trim() : 'an unknown runtime';\n }\n\n /**\n * IGNIS runs on Bun 1.4 or later, and nothing else. One refusal at the top of `start()`, before any\n * hook, datasource or socket is touched, replaces a failure that would otherwise surface halfway\n * through startup.\n */\n static assert(opts: { runtime?: IRuntimeSnapshot } = {}): void {\n const runtime = opts.runtime ?? BunRuntimeGuard.readSnapshot();\n\n if (runtime.bunVersion !== undefined) {\n const [major = 0, minor = 0] = runtime.bunVersion.split('.').map(Number);\n\n if (\n major > MINIMUM_BUN.major ||\n (major === MINIMUM_BUN.major && minor >= MINIMUM_BUN.minor)\n ) {\n return;\n }\n }\n\n throw getError({\n message: `IGNIS requires Bun >= ${MINIMUM_BUN.major}.${MINIMUM_BUN.minor} (running on ${BunRuntimeGuard.describeRuntime({ runtime })})`,\n });\n }\n}\n\nconst DEFAULT_SHUTDOWN_SIGNALS: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 15_000;\n\nconst DEFAULT_SERVER_HOST = 'localhost';\nconst DEFAULT_SERVER_PORT = 3000;\nconst MAX_SERVER_PORT = 65535;\n\n/**\n * The first candidate USABLE as a port. Rejection is on validity, never falsiness: `0` legitimately\n * asks the OS for an ephemeral port, and taking the first TRUTHY value instead let an unusable\n * `PORT` shadow a usable `APP_ENV_SERVER_PORT` - `PORT=abc APP_ENV_SERVER_PORT=8080` bound 3000, as\n * did Docker's legacy container-link form `PORT=tcp://172.17.0.5:8080`.\n */\nconst resolveServerPort = (opts: { candidates: Array<number | string | undefined> }): number => {\n for (const candidate of opts.candidates) {\n if (candidate === undefined || candidate === null) {\n continue;\n }\n\n const normalized = typeof candidate === 'string' ? candidate.trim() : candidate;\n\n if (normalized === '') {\n continue;\n }\n\n const parsed = Number(normalized);\n\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > MAX_SERVER_PORT) {\n continue;\n }\n\n return parsed;\n }\n\n return DEFAULT_SERVER_PORT;\n};\n\n/** Adds the listening server (`Bun.serve`) on top of `RestApplication` - the only layer that touches a socket, so it is the layer that stays out of the browser-pure kernel. */\nexport abstract class ServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n>\n extends RestApplication<AppEnv, AppSchema, BasePath>\n implements IServerApplication<AppEnv, AppSchema, BasePath>\n{\n /** Which runtime is underneath, and the socket once one is bound. Both live here, not on `RestApplication`: a browser Worker has neither. `start()` refuses to run unless this is Bun. */\n protected runtime = RuntimeModules.detect();\n protected serverInstance?: TBunServerInstance;\n\n /** Widened by this layer, which is the only one that binds a socket. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IServerApplicationConfigs;\n\n /**\n * The address resolution the kernel deliberately does not do: `host` and `port` mean nothing to a\n * host with no socket, and resolving them there silently configured every browser Worker with\n * `localhost:3000`. Env is the fallback, explicit config always wins.\n */\n constructor(opts: { scope: string; config: IServerApplicationConfigs }) {\n super(opts);\n\n this.configs.host =\n [opts.config.host, process.env.HOST, process.env.APP_ENV_SERVER_HOST].find(Boolean) ??\n DEFAULT_SERVER_HOST;\n this.configs.port = resolveServerPort({\n candidates: [opts.config.port, process.env.PORT, process.env.APP_ENV_SERVER_PORT],\n });\n }\n\n /** Both routers are `OpenAPIHono` (see `createRouter`). */\n declare protected server: { hono: OpenAPIHono<AppEnv, AppSchema, BasePath> };\n declare protected rootRouter: OpenAPIHono<AppEnv, AppSchema, BasePath>;\n\n /** Always an `OpenAPIHono`, whatever else is loaded: the API reference reads `rootRouter.openAPIRegistry`. */\n protected override createRouter(opts: {\n strict: boolean;\n }): OpenAPIHono<AppEnv, AppSchema, BasePath> {\n return new OpenAPIHono<AppEnv, AppSchema, BasePath>({ strict: opts.strict });\n }\n\n override getServer(): OpenAPIHono<AppEnv, AppSchema, BasePath> {\n return this.server.hono;\n }\n\n override getRootRouter(): OpenAPIHono<AppEnv, AppSchema, BasePath> {\n return this.rootRouter;\n }\n\n /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */\n protected override getDefaultAsyncContextEnabled(): boolean {\n return true;\n }\n\n /** `configs.projectRoot` wins, else the process cwd. The value is bound AND handed to `ModuleUtility`, so every peer lookup (optional modules, the gRPC adapter) resolves under it - a compiled binary sets it to where its `node_modules` really is. */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? process.cwd();\n\n if (this.configs.projectRoot && !existsSync(path.join(projectRoot, 'node_modules'))) {\n this.logger\n .for(this.getProjectRoot.name)\n .warn(\n 'configs.projectRoot has no node_modules | root: %s | optional peers will not resolve from it',\n projectRoot,\n );\n }\n\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ModuleUtility.setProjectRoot({ projectRoot });\n\n return projectRoot;\n }\n\n getServerHost(): string {\n return this.configs.host!;\n }\n\n getServerPort(): number {\n return this.configs.port!;\n }\n\n getServerAddress() {\n return `${this.getServerHost()}:${this.getServerPort()}`;\n }\n\n /** `configs.server` with unset keys dropped, so a missing option keeps Bun's default instead of passing `undefined`. */\n protected getServerRuntimeOptions(): IServerRuntimeConfigs {\n const { idleTimeout, maxRequestBodySize } = this.configs.server ?? {};\n\n return {\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n ...(maxRequestBodySize === undefined ? {} : { maxRequestBodySize }),\n };\n }\n\n /** What `start()` checks. A seam for the guard's test: the `Bun` global cannot be hidden from inside Bun. */\n protected getRuntimeSnapshot(): IRuntimeSnapshot {\n return BunRuntimeGuard.readSnapshot();\n }\n\n getServerInstance<T extends TBunServerInstance = TBunServerInstance>(): T | undefined {\n return this.serverInstance as T | undefined;\n }\n\n protected startBunModule() {\n return new Promise((resolve, reject) => {\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n\n Promise.resolve(\n Bun.serve({\n port,\n hostname: host,\n fetch: server.fetch,\n ...this.getServerRuntimeOptions(),\n }),\n )\n .then((rs) => {\n this.serverInstance = rs;\n this.configs.port = rs.port;\n this.inspectRoutes();\n\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s', this.getServerAddress());\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n resolve(rs);\n })\n .catch(reject);\n });\n }\n\n async start() {\n BunRuntimeGuard.assert({ runtime: this.getRuntimeSnapshot() });\n\n await this.initialize();\n await this.setupMiddlewares();\n\n const server = this.getServer();\n server.route(this.configs.path.base, this.rootRouter);\n\n await this.startBunModule();\n\n await this.executePostStartHooks();\n }\n\n /** Post-stop hooks, then the server, then the datasources - closed even when the server fails to, so a stopped application holds no connection. */\n async stop() {\n await this.executePostStopHooks();\n\n try {\n await this.stopServer();\n } finally {\n await this.closeDataSources();\n }\n }\n\n /** Set once `installShutdownSignals` ran; holds the way back, so a second call is a no-op. */\n protected shutdownSignals?: { uninstall: () => void };\n\n /**\n * Stops the application on a signal (SIGTERM and SIGINT by default), then exits the process.\n * Opt-in: nothing is installed until you call it, usually right after `start()`.\n *\n * - Calls `stop()` once. A second signal while it runs is ignored.\n * - Exits 0 when `stop()` finishes, 1 when it throws or does not finish within `timeoutMs`.\n * - Idempotent: calling it again returns the same uninstall function and adds no listener.\n * - Returns an uninstall function that removes the listeners and the pending timeout.\n */\n installShutdownSignals(opts: IShutdownSignalsOptions = {}): () => void {\n if (this.shutdownSignals) {\n return this.shutdownSignals.uninstall;\n }\n\n const {\n signals = DEFAULT_SHUTDOWN_SIGNALS,\n timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,\n exit = (code: number) => process.exit(code),\n } = opts;\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw getError({\n message: `[installShutdownSignals] timeoutMs must be a positive number of milliseconds | value: ${String(timeoutMs)}`,\n });\n }\n\n const log = this.logger.for(this.installShutdownSignals.name);\n let isShuttingDown = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const finish = (code: number) => {\n clearTimeout(timer);\n exit(code);\n };\n\n const onSignal = (signal: NodeJS.Signals) => {\n if (isShuttingDown) {\n log.warn('Signal %s ignored | shutdown already in progress', signal);\n\n return;\n }\n\n isShuttingDown = true;\n log.info('Signal %s received | stopping the application | timeout: %s ms', signal, timeoutMs);\n\n timer = setTimeout(() => {\n log.error('Shutdown did not finish within %s ms | forcing exit', timeoutMs);\n exit(1);\n }, timeoutMs);\n\n this.stop().then(\n () => {\n log.info('Application stopped | exiting');\n finish(0);\n },\n (error: unknown) => {\n log.error(\n 'Shutdown failed | error: %s',\n error instanceof Error ? error.message : String(error),\n );\n finish(1);\n },\n );\n };\n\n const listeners = signals.map((signal) => {\n const listener = () => onSignal(signal);\n process.on(signal, listener);\n\n return { signal, listener };\n });\n\n const uninstall = () => {\n clearTimeout(timer);\n\n for (const { signal, listener } of listeners) {\n process.off(signal, listener);\n }\n\n this.shutdownSignals = undefined;\n };\n\n this.shutdownSignals = { uninstall };\n\n return uninstall;\n }\n\n protected async stopServer(): Promise<void> {\n const instance = this.serverInstance;\n\n if (!instance) {\n this.logger.for(this.stop.name).info('Server was not started | Nothing to stop');\n\n return;\n }\n\n await instance.stop();\n\n this.serverInstance = undefined;\n this.logger.for(this.stop.name).info('Server STOPPED');\n }\n}\n"]}
@@ -228,7 +228,7 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
228
228
  message: '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',
229
229
  });
230
230
  }
231
- // A caller's key set decides who may call: https, loopback, or a host named in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.
231
+ // 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.
232
232
  JWKSUrlPolicy.resolveHttpHosts({
233
233
  scope: 'defineServiceAuth',
234
234
  hosts: serviceOptions.jwks?.hosts?.http,
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,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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,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAChF,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AA7VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA6VjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n AbstractBearerTokenService,\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { JWKSUrlPolicy } from './services/jwks-url-policy';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: issuerOpts,\n pinnedAlgorithms: [issuerOpts.algorithm],\n });\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: verifierOpts,\n });\n\n JWKSUrlPolicy.assertUrl({\n scope: 'defineJWKSAuth',\n label: 'jwksUrl',\n url: verifierOpts.jwksUrl,\n hosts: verifierOpts.jwks?.hosts?.http,\n });\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n // A caller's key set decides who may call: https, loopback, or a host named in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveHttpHosts({\n scope: 'defineServiceAuth',\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n\n for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {\n JWKSUrlPolicy.assertUrl({\n scope: 'defineServiceAuth',\n label: `callers[${JSON.stringify(caller)}].jwksUrl`,\n url: typeof entry === 'string' ? entry : entry.jwksUrl,\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
1
+ {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,0BAA0B,EAC1B,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,MAAM,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;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,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAChF,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AA7VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA6VjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n AbstractBearerTokenService,\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { JWKSUrlPolicy } from './services/jwks-url-policy';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: issuerOpts,\n pinnedAlgorithms: [issuerOpts.algorithm],\n });\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: verifierOpts,\n });\n\n JWKSUrlPolicy.assertUrl({\n scope: 'defineJWKSAuth',\n label: 'jwksUrl',\n url: verifierOpts.jwksUrl,\n hosts: verifierOpts.jwks?.hosts?.http,\n });\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n // A caller's key set decides who may call: https, loopback, or a host 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.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
@@ -1,20 +1,31 @@
1
1
  /**
2
2
  * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
3
3
  * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
4
- * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
4
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
5
5
  * callers: both fetch a key set to decide who may call.
6
6
  *
7
- * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to
8
- * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.
7
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
8
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
9
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
10
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
11
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
9
12
  */
10
13
  export declare class JWKSUrlPolicy {
11
- /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */
14
+ /**
15
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
16
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
17
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
18
+ */
12
19
  static resolveHttpHosts(opts: {
13
20
  scope: string;
14
21
  hosts?: unknown;
15
22
  }): ReadonlySet<string>;
16
- /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */
17
- private static isParsedAsItself;
23
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
24
+ private static canonicalEntry;
25
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
26
+ private static isWithinLimits;
27
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
28
+ private static parseHttp;
18
29
  /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
19
30
  static isLoopback(hostname: string): boolean;
20
31
  /**
@@ -1,23 +1,42 @@
1
1
  import { HTTP } from '@venizia/ignis-helpers/common';
2
2
  import { getError } from '@venizia/ignis-helpers/core';
3
- /** One host name of `jwks.hosts.http`: labels of letters, digits and hyphens joined by single dots - no empty label, no port, no scheme, no wildcard, no address literal. */
3
+ /** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */
4
4
  const HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
5
- /** An IPv4 address: an entry of `jwks.hosts.http` is a name, and an address is not one. */
5
+ /** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */
6
6
  const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/;
7
+ /**
8
+ * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional
9
+ * `:port`. Nothing else: no scheme, path, userinfo or wildcard.
10
+ */
11
+ const ENTRY_PATTERN = /^(?<host>\[[0-9a-f:.]+\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;
12
+ /** The port of an `http:` URL that names none. */
13
+ const DEFAULT_HTTP_PORT = '80';
14
+ /** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */
15
+ const MAX_LABEL_LENGTH = 63;
16
+ const MAX_NAME_LENGTH = 253;
17
+ /** The addresses that mean "any local address", not a host: as the URL parser writes them. */
18
+ const UNSPECIFIED_HOSTS = new Set(['0.0.0.0', '[::]']);
7
19
  /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
8
20
  const LOOPBACK_IPV4_PATTERN = /^127(?:\.\d{1,3}){3}$/;
9
21
  const LOOPBACK_HOSTS = new Set(['localhost', '[::1]']);
10
22
  /**
11
23
  * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
12
24
  * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
13
- * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
25
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
14
26
  * callers: both fetch a key set to decide who may call.
15
27
  *
16
- * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to
17
- * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.
28
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
29
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
30
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
31
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
32
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
18
33
  */
19
34
  export class JWKSUrlPolicy {
20
- /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */
35
+ /**
36
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
37
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
38
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
39
+ */
21
40
  static resolveHttpHosts(opts) {
22
41
  const { scope, hosts } = opts;
23
42
  if (hosts === undefined) {
@@ -26,34 +45,67 @@ export class JWKSUrlPolicy {
26
45
  if (!Array.isArray(hosts)) {
27
46
  throw getError({
28
47
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
29
- message: `[${scope}] jwks.hosts.http must be a list of host names`,
48
+ message: `[${scope}] jwks.hosts.http must be a list of hosts`,
30
49
  });
31
50
  }
32
51
  const resolved = new Set();
33
52
  for (const entry of hosts) {
34
- const name = typeof entry === 'string' ? entry.trim().toLowerCase() : '';
35
- // The name must be what the URL parser makes of it: `2130706433`, `0x7f000001` and `1.2.3` are addresses the parser
36
- // rewrites (to `127.0.0.1`, `1.2.0.3`), so none of them is the name it looks like.
37
- if (!HOST_NAME_PATTERN.test(name) ||
38
- IPV4_PATTERN.test(name) ||
39
- !JWKSUrlPolicy.isParsedAsItself({ name })) {
53
+ const canonical = typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;
54
+ if (canonical === undefined) {
40
55
  throw getError({
41
56
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
42
- message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list host names only: no port, scheme, wildcard or address, for example 'identity-service'`,
57
+ message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,
43
58
  });
44
59
  }
45
- resolved.add(name);
60
+ resolved.add(canonical);
46
61
  }
47
62
  return resolved;
48
63
  }
49
- /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */
50
- static isParsedAsItself(opts) {
64
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
65
+ static canonicalEntry(opts) {
66
+ // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.
67
+ const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());
68
+ const { host, port } = matched?.groups ?? {};
69
+ if (host === undefined) {
70
+ return undefined;
71
+ }
72
+ // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.
73
+ const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);
74
+ if (!isAddress &&
75
+ !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))) {
76
+ return undefined;
77
+ }
78
+ const parsed = JWKSUrlPolicy.parseHttp({
79
+ authority: port === undefined ? host : `${host}:${port}`,
80
+ });
81
+ // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and
82
+ // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.
83
+ if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {
84
+ return undefined;
85
+ }
86
+ if (port === undefined) {
87
+ return host;
88
+ }
89
+ // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.
90
+ const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
91
+ if (kept !== port || Number(port) < 1) {
92
+ return undefined;
93
+ }
94
+ return `${host}:${port}`;
95
+ }
96
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
97
+ static isWithinLimits(opts) {
98
+ return (opts.name.length <= MAX_NAME_LENGTH &&
99
+ opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH));
100
+ }
101
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
102
+ static parseHttp(opts) {
51
103
  try {
52
- return new URL(`http://${opts.name}`).hostname === opts.name;
53
- // eslint-disable-next-line venizia/no-silent-catch -- a name the parser refuses is not a host name: the caller refuses the entry
104
+ return new URL(`http://${opts.authority}`);
105
+ // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry
54
106
  }
55
107
  catch {
56
- return false;
108
+ return undefined;
57
109
  }
58
110
  }
59
111
  /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
@@ -87,12 +139,23 @@ export class JWKSUrlPolicy {
87
139
  });
88
140
  }
89
141
  const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });
90
- if (JWKSUrlPolicy.isLoopback(parsed.hostname) || allowed.has(parsed.hostname)) {
142
+ // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.
143
+ if (parsed.port === '0') {
144
+ throw getError({
145
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
146
+ message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,
147
+ });
148
+ }
149
+ // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).
150
+ const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
151
+ if (JWKSUrlPolicy.isLoopback(parsed.hostname) ||
152
+ allowed.has(parsed.hostname) ||
153
+ allowed.has(`${parsed.hostname}:${port}`)) {
91
154
  return parsed;
92
155
  }
93
156
  throw getError({
94
157
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
95
- message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host name in jwks.hosts.http`,
158
+ message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,
96
159
  });
97
160
  }
98
161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jwks-url-policy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/jwks-url-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,6KAA6K;AAC7K,MAAM,iBAAiB,GAAG,yEAAyE,CAAC;AAEpG,2FAA2F;AAC3F,MAAM,YAAY,GAAG,2BAA2B,CAAC;AAEjD,4DAA4D;AAC5D,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AAEtD,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;AAE5E;;;;;;;;GAQG;AACH,MAAM,OAAO,aAAa;IACxB,+GAA+G;IAC/G,MAAM,CAAC,gBAAgB,CAAC,IAAwC;QAC9D,MAAM,EAAE,KAA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C,QAAQ,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9E,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,IAAI,KAAK,KAAK,KAAK,6BAA6B,MAAM,CAAC,QAAQ,wEAAwE;SACjJ,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** One host name of `jwks.hosts.http`: labels of letters, digits and hyphens joined by single dots - no empty label, no port, no scheme, no wildcard, no address literal. */\nconst HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;\n\n/** An IPv4 address: an entry of `jwks.hosts.http` is a name, and an address is not one. */\nconst IPV4_PATTERN = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n\n/** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\nconst LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n/**\n * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and\n * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or\n * is listed by name in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion\n * callers: both fetch a key set to decide who may call.\n *\n * The opt-in is by host NAME, never by address range: what a name resolves to can change, and the choice to\n * trust a name is the operator's. The port is ignored, so `identity-service` covers every port.\n */\nexport class JWKSUrlPolicy {\n /** Refuses an entry of `jwks.hosts.http` that is not a bare host name, and answers the entries lower-cased. */\n static resolveHttpHosts(opts: { scope: string; hosts?: unknown }): ReadonlySet<string> {\n const { scope, hosts } = opts;\n\n if (hosts === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(hosts)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http must be a list of host names`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of hosts) {\n const name = typeof entry === 'string' ? entry.trim().toLowerCase() : '';\n\n // The name must be what the URL parser makes of it: `2130706433`, `0x7f000001` and `1.2.3` are addresses the parser\n // rewrites (to `127.0.0.1`, `1.2.0.3`), so none of them is the name it looks like.\n if (\n !HOST_NAME_PATTERN.test(name) ||\n IPV4_PATTERN.test(name) ||\n !JWKSUrlPolicy.isParsedAsItself({ name })\n ) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list host names only: no port, scheme, wildcard or address, for example 'identity-service'`,\n });\n }\n\n resolved.add(name);\n }\n\n return resolved;\n }\n\n /** Whether `http://<name>` has `<name>` as its host once the URL parser has had its say. */\n private static isParsedAsItself(opts: { name: string }): boolean {\n try {\n return new URL(`http://${opts.name}`).hostname === opts.name;\n // eslint-disable-next-line venizia/no-silent-catch -- a name the parser refuses is not a host name: the caller refuses the entry\n } catch {\n return false;\n }\n }\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopback(hostname: string): boolean {\n return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /**\n * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in\n * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.\n */\n static assertUrl(opts: { scope: string; label: string; url: string; hosts?: unknown }): URL {\n const { scope, label, url } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} is not a valid URL`,\n });\n }\n\n if (parsed.protocol === 'https:') {\n return parsed;\n }\n\n if (parsed.protocol !== 'http:') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,\n });\n }\n\n const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });\n\n if (JWKSUrlPolicy.isLoopback(parsed.hostname) || allowed.has(parsed.hostname)) {\n return parsed;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host name in jwks.hosts.http`,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"jwks-url-policy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/jwks-url-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,gHAAgH;AAChH,MAAM,iBAAiB,GAAG,yEAAyE,CAAC;AAEpG,6HAA6H;AAC7H,MAAM,YAAY,GAAG,2BAA2B,CAAC;AAEjD;;;GAGG;AACH,MAAM,aAAa,GAAG,yEAAyE,CAAC;AAEhG,kDAAkD;AAClD,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,oGAAoG;AACpG,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAC5B,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B,8FAA8F;AAC9F,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;AAE5E,4DAA4D;AAC5D,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AAEtD,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC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@venizia/ignis-helpers/core';\n\n/** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */\nconst HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;\n\n/** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */\nconst IPV4_PATTERN = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n\n/**\n * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional\n * `:port`. Nothing else: no scheme, path, userinfo or wildcard.\n */\nconst ENTRY_PATTERN = /^(?<host>\\[[0-9a-f:.]+\\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;\n\n/** The port of an `http:` URL that names none. */\nconst DEFAULT_HTTP_PORT = '80';\n\n/** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */\nconst MAX_LABEL_LENGTH = 63;\nconst MAX_NAME_LENGTH = 253;\n\n/** The addresses that mean \"any local address\", not a host: as the URL parser writes them. */\nconst UNSPECIFIED_HOSTS: ReadonlySet<string> = new Set(['0.0.0.0', '[::]']);\n\n/** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\nconst LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n/**\n * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and\n * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or\n * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion\n * callers: both fetch a key set to decide who may call.\n *\n * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in\n * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a\n * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by\n * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is\n * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.\n */\nexport class JWKSUrlPolicy {\n /**\n * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries\n * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.\n * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.\n */\n static resolveHttpHosts(opts: { scope: string; hosts?: unknown }): ReadonlySet<string> {\n const { scope, hosts } = opts;\n\n if (hosts === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(hosts)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http must be a list of hosts`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of hosts) {\n const canonical =\n typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;\n\n if (canonical === undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,\n });\n }\n\n resolved.add(canonical);\n }\n\n return resolved;\n }\n\n /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */\n private static canonicalEntry(opts: { entry: string }): string | undefined {\n // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.\n const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());\n const { host, port } = matched?.groups ?? {};\n\n if (host === undefined) {\n return undefined;\n }\n\n // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.\n const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);\n\n if (\n !isAddress &&\n !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))\n ) {\n return undefined;\n }\n\n const parsed = JWKSUrlPolicy.parseHttp({\n authority: port === undefined ? host : `${host}:${port}`,\n });\n\n // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and\n // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.\n if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {\n return undefined;\n }\n\n if (port === undefined) {\n return host;\n }\n\n // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.\n const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (kept !== port || Number(port) < 1) {\n return undefined;\n }\n\n return `${host}:${port}`;\n }\n\n /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */\n private static isWithinLimits(opts: { name: string }): boolean {\n return (\n opts.name.length <= MAX_NAME_LENGTH &&\n opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH)\n );\n }\n\n /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */\n private static parseHttp(opts: { authority: string }): URL | undefined {\n try {\n return new URL(`http://${opts.authority}`);\n // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry\n } catch {\n return undefined;\n }\n }\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopback(hostname: string): boolean {\n return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /**\n * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in\n * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.\n */\n static assertUrl(opts: { scope: string; label: string; url: string; hosts?: unknown }): URL {\n const { scope, label, url } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} is not a valid URL`,\n });\n }\n\n if (parsed.protocol === 'https:') {\n return parsed;\n }\n\n if (parsed.protocol !== 'http:') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,\n });\n }\n\n const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });\n\n // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.\n if (parsed.port === '0') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,\n });\n }\n\n // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).\n const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (\n JWKSUrlPolicy.isLoopback(parsed.hostname) ||\n allowed.has(parsed.hostname) ||\n allowed.has(`${parsed.hostname}:${port}`)\n ) {\n return parsed;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,\n });\n }\n}\n"]}
@@ -9,7 +9,7 @@ export declare abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>
9
9
  scope: string;
10
10
  dataSource: ICasbinPolicySource;
11
11
  });
12
- protected get connector(): TCasbinPolicyConnector;
12
+ protected resolveConnector(): Promise<TCasbinPolicyConnector>;
13
13
  /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */
14
14
  protected query<TRow>(opts: {
15
15
  statement: SQL;
@@ -8,7 +8,7 @@ export class BaseFilteredAdapter extends BaseHelper {
8
8
  super({ scope: opts.scope });
9
9
  this.dataSource = opts.dataSource;
10
10
  }
11
- get connector() {
11
+ resolveConnector() {
12
12
  return PolicyConnectorResolver.resolve({
13
13
  source: this.dataSource,
14
14
  caller: 'BaseFilteredAdapter',
@@ -16,7 +16,8 @@ export class BaseFilteredAdapter extends BaseHelper {
16
16
  }
17
17
  /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */
18
18
  async query(opts) {
19
- const result = await this.connector.execute(opts.statement);
19
+ const connector = await this.resolveConnector();
20
+ const result = await connector.execute(opts.statement);
20
21
  return DrizzleResultUtility.readResultRows({ result });
21
22
  }
22
23
  isFiltered() {
@@ -1 +1 @@
1
- {"version":3,"file":"base-filtered.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/base-filtered.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,0LAA0L;AAC1L,MAAM,OAAgB,mBACpB,SAAQ,UAAU;IAKlB,YAAY,IAAwD;QAClE,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACpC,CAAC;IAED,IAAc,SAAS;QACrB,OAAO,uBAAuB,CAAC,OAAO,CAAC;YACrC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,qBAAqB;SAC9B,CAAC,CAAC;IACL,CAAC;IAED,2LAA2L;IACjL,KAAK,CAAC,KAAK,CAAO,IAAwB;QAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE5D,OAAO,oBAAoB,CAAC,cAAc,CAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IAC/D,CAAC;IAKD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;IAED,4DAA4D;IAC5D,KAAK,CAAC,UAAU,KAAmB,CAAC;IACpC,KAAK,CAAC,UAAU;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,SAAS,KAAmB,CAAC;IACnC,KAAK,CAAC,YAAY,KAAmB,CAAC;IACtC,KAAK,CAAC,oBAAoB,KAAmB,CAAC;IAE9C,+FAA+F;IACrF,KAAK,CAAC,SAAS,CAAC,IAAuC;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAC;QAE7C,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;CACF","sourcesContent":["import { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport { type FilteredAdapter, type Model } from 'casbin';\nimport type { SQL } from 'drizzle-orm';\nimport { CasbinModule } from '../enforcers/casbin-module';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicyFilter, ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Read-only base for casbin FilteredAdapters backed by a datasource - owns connector plumbing and no-op write methods; subclasses implement {@link loadFilteredPolicy} per principal. */\nexport abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>\n extends BaseHelper\n implements FilteredAdapter\n{\n protected readonly dataSource: ICasbinPolicySource;\n\n constructor(opts: { scope: string; dataSource: ICasbinPolicySource }) {\n super({ scope: opts.scope });\n this.dataSource = opts.dataSource;\n }\n\n protected get connector(): TCasbinPolicyConnector {\n return PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: 'BaseFilteredAdapter',\n });\n }\n\n /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */\n protected async query<TRow>(opts: { statement: SQL }): Promise<TRow[]> {\n const result = await this.connector.execute(opts.statement);\n\n return DrizzleResultUtility.readResultRows<TRow>({ result });\n }\n\n /** Load ONLY the policies matching `filter` into `model` (the store is read for one principal). */\n abstract loadFilteredPolicy(model: Model, filter: TFilter): Promise<void>;\n\n isFiltered(): boolean {\n return true;\n }\n\n // Read-only adapter - write methods are intentional no-ops.\n async loadPolicy(): Promise<void> {}\n async savePolicy(): Promise<boolean> {\n return true;\n }\n\n async addPolicy(): Promise<void> {}\n async removePolicy(): Promise<void> {}\n async removeFilteredPolicy(): Promise<void> {}\n\n /** Parse + load casbin policy lines into a model. Shared by subclasses' loadFilteredPolicy. */\n protected async loadLines(opts: { model: Model; lines: string[] }): Promise<void> {\n const { Helper } = await CasbinModule.load();\n\n for (const line of opts.lines) {\n Helper.loadPolicyLine(line, opts.model);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"base-filtered.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/base-filtered.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,0LAA0L;AAC1L,MAAM,OAAgB,mBACpB,SAAQ,UAAU;IAKlB,YAAY,IAAwD;QAClE,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACpC,CAAC;IAES,gBAAgB;QACxB,OAAO,uBAAuB,CAAC,OAAO,CAAC;YACrC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,qBAAqB;SAC9B,CAAC,CAAC;IACL,CAAC;IAED,2LAA2L;IACjL,KAAK,CAAC,KAAK,CAAO,IAAwB;QAClD,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEvD,OAAO,oBAAoB,CAAC,cAAc,CAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IAC/D,CAAC;IAKD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;IAED,4DAA4D;IAC5D,KAAK,CAAC,UAAU,KAAmB,CAAC;IACpC,KAAK,CAAC,UAAU;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,SAAS,KAAmB,CAAC;IACnC,KAAK,CAAC,YAAY,KAAmB,CAAC;IACtC,KAAK,CAAC,oBAAoB,KAAmB,CAAC;IAE9C,+FAA+F;IACrF,KAAK,CAAC,SAAS,CAAC,IAAuC;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAC;QAE7C,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;CACF","sourcesContent":["import { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport { type FilteredAdapter, type Model } from 'casbin';\nimport type { SQL } from 'drizzle-orm';\nimport { CasbinModule } from '../enforcers/casbin-module';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicyFilter, ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Read-only base for casbin FilteredAdapters backed by a datasource - owns connector plumbing and no-op write methods; subclasses implement {@link loadFilteredPolicy} per principal. */\nexport abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>\n extends BaseHelper\n implements FilteredAdapter\n{\n protected readonly dataSource: ICasbinPolicySource;\n\n constructor(opts: { scope: string; dataSource: ICasbinPolicySource }) {\n super({ scope: opts.scope });\n this.dataSource = opts.dataSource;\n }\n\n protected resolveConnector(): Promise<TCasbinPolicyConnector> {\n return PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: 'BaseFilteredAdapter',\n });\n }\n\n /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */\n protected async query<TRow>(opts: { statement: SQL }): Promise<TRow[]> {\n const connector = await this.resolveConnector();\n const result = await connector.execute(opts.statement);\n\n return DrizzleResultUtility.readResultRows<TRow>({ result });\n }\n\n /** Load ONLY the policies matching `filter` into `model` (the store is read for one principal). */\n abstract loadFilteredPolicy(model: Model, filter: TFilter): Promise<void>;\n\n isFiltered(): boolean {\n return true;\n }\n\n // Read-only adapter - write methods are intentional no-ops.\n async loadPolicy(): Promise<void> {}\n async savePolicy(): Promise<boolean> {\n return true;\n }\n\n async addPolicy(): Promise<void> {}\n async removePolicy(): Promise<void> {}\n async removeFilteredPolicy(): Promise<void> {}\n\n /** Parse + load casbin policy lines into a model. Shared by subclasses' loadFilteredPolicy. */\n protected async loadLines(opts: { model: Model; lines: string[] }): Promise<void> {\n const { Helper } = await CasbinModule.load();\n\n for (const line of opts.lines) {\n Helper.loadPolicyLine(line, opts.model);\n }\n }\n}\n"]}
@@ -12,6 +12,8 @@ export interface ICasbinPolicyFilter {
12
12
  export type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;
13
13
  /** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */
14
14
  export interface ICasbinPolicySource {
15
+ /** A datasource that opens on first use opens here; one that opens at start resolves at once. */
16
+ ensureOpen?(): Promise<void>;
15
17
  /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */
16
18
  getConnector?(): TCasbinPolicyConnector;
17
19
  /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authorize/adapters/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n/** Filter passed to loadFilteredPolicy: which principal's policies to load. */\nexport interface ICasbinPolicyFilter {\n principal: { type: string; id: IdType };\n}\n\n/** Drizzle connector for policy queries, typed on the shared `PgDatabase` base so postgres-js fits too. Declared here rather than imported from `@/connectors/postgres`: components depend on a minimal local contract, never a connector class. */\nexport type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;\n\n/** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */\nexport interface ICasbinPolicySource {\n /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */\n getConnector?(): TCasbinPolicyConnector;\n\n /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */\n connector?: TCasbinPolicyConnector;\n}\n\n/** Maps a logical table onto its physical name + schema. */\nexport interface IScopedCasbinTable {\n tableName: string;\n schemaName?: string;\n}\n\n/** All physical mapping the ScopedCasbinAdapter needs. App provides this; framework stays decoupled. */\nexport interface IScopedCasbinEntities {\n policyDefinition: IScopedCasbinTable & {\n metadata?: { columnName: string };\n };\n\n /** Permission catalog (id, code, ...). */\n permission: IScopedCasbinTable;\n\n /** Principal type labels used as casbin name prefixes. */\n principals: { user: string; role: string };\n\n /** Domain type labels (e.g. ['Merchant', 'Organizer']). */\n domainTypes: string[];\n\n /** Soft-delete handling for both tables. */\n softDelete?: { use: false } | { use: true; columnName: string };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authorize/adapters/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n/** Filter passed to loadFilteredPolicy: which principal's policies to load. */\nexport interface ICasbinPolicyFilter {\n principal: { type: string; id: IdType };\n}\n\n/** Drizzle connector for policy queries, typed on the shared `PgDatabase` base so postgres-js fits too. Declared here rather than imported from `@/connectors/postgres`: components depend on a minimal local contract, never a connector class. */\nexport type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;\n\n/** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */\nexport interface ICasbinPolicySource {\n /** A datasource that opens on first use opens here; one that opens at start resolves at once. */\n ensureOpen?(): Promise<void>;\n\n /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */\n getConnector?(): TCasbinPolicyConnector;\n\n /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */\n connector?: TCasbinPolicyConnector;\n}\n\n/** Maps a logical table onto its physical name + schema. */\nexport interface IScopedCasbinTable {\n tableName: string;\n schemaName?: string;\n}\n\n/** All physical mapping the ScopedCasbinAdapter needs. App provides this; framework stays decoupled. */\nexport interface IScopedCasbinEntities {\n policyDefinition: IScopedCasbinTable & {\n metadata?: { columnName: string };\n };\n\n /** Permission catalog (id, code, ...). */\n permission: IScopedCasbinTable;\n\n /** Principal type labels used as casbin name prefixes. */\n principals: { user: string; role: string };\n\n /** Domain type labels (e.g. ['Merchant', 'Organizer']). */\n domainTypes: string[];\n\n /** Soft-delete handling for both tables. */\n softDelete?: { use: false } | { use: true; columnName: string };\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import type { ICasbinPolicySource, TCasbinPolicyConnector } from './common/index.js';
2
2
  /** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */
3
3
  export declare class PolicyConnectorResolver {
4
- /** Resolve the wired connector off a policy datasource. */
4
+ /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */
5
5
  static resolve(opts: {
6
6
  source: ICasbinPolicySource;
7
7
  caller: string;
8
- }): TCasbinPolicyConnector;
8
+ }): Promise<TCasbinPolicyConnector>;
9
9
  }
10
10
  //# sourceMappingURL=connector.d.ts.map
@@ -1,9 +1,10 @@
1
1
  import { getError } from '@venizia/ignis-helpers/core';
2
2
  /** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */
3
3
  export class PolicyConnectorResolver {
4
- /** Resolve the wired connector off a policy datasource. */
5
- static resolve(opts) {
4
+ /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */
5
+ static async resolve(opts) {
6
6
  const { source, caller } = opts;
7
+ await source.ensureOpen?.();
7
8
  const resolved = source.getConnector?.() ?? source.connector;
8
9
  if (!resolved) {
9
10
  throw getError({
@@ -1 +1 @@
1
- {"version":3,"file":"connector.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,iGAAiG;AACjG,MAAM,OAAO,uBAAuB;IAClC,2DAA2D;IAC3D,MAAM,CAAC,OAAO,CAAC,IAAqD;QAClE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAChC,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC;QAE7D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,MAAM,gJAAgJ;aACpK,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */\nexport class PolicyConnectorResolver {\n /** Resolve the wired connector off a policy datasource. */\n static resolve(opts: { source: ICasbinPolicySource; caller: string }): TCasbinPolicyConnector {\n const { source, caller } = opts;\n const resolved = source.getConnector?.() ?? source.connector;\n\n if (!resolved) {\n throw getError({\n message: `[${caller}] datasource exposes neither a getConnector() accessor nor a wired connector - pass a datasource whose getConnector() lazily wires the driver.`,\n });\n }\n\n return resolved;\n }\n}\n"]}
1
+ {"version":3,"file":"connector.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,iGAAiG;AACjG,MAAM,OAAO,uBAAuB;IAClC,iIAAiI;IACjI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAGpB;QACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAEhC,MAAM,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;QAE5B,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC;QAE7D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,MAAM,gJAAgJ;aACpK,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */\nexport class PolicyConnectorResolver {\n /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */\n static async resolve(opts: {\n source: ICasbinPolicySource;\n caller: string;\n }): Promise<TCasbinPolicyConnector> {\n const { source, caller } = opts;\n\n await source.ensureOpen?.();\n\n const resolved = source.getConnector?.() ?? source.connector;\n\n if (!resolved) {\n throw getError({\n message: `[${caller}] datasource exposes neither a getConnector() accessor nor a wired connector - pass a datasource whose getConnector() lazily wires the driver.`,\n });\n }\n\n return resolved;\n }\n}\n"]}
@@ -89,7 +89,7 @@ export class CustomGrantExpander extends BaseHelper {
89
89
  return [];
90
90
  }
91
91
  const permissionTable = this.qualifiedTable({ table: this.permission });
92
- const connector = PolicyConnectorResolver.resolve({
92
+ const connector = await PolicyConnectorResolver.resolve({
93
93
  source: this.dataSource,
94
94
  caller: CustomGrantExpander.name,
95
95
  });
@@ -1 +1 @@
1
- {"version":3,"file":"custom-grant-expander.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/custom-grant-expander.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EACL,oBAAoB,EACpB,8BAA8B,EAC9B,2BAA2B,EAC3B,YAAY,GAEb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,MAAM,cAAc,GAAG,QAAQ,CAAC;AAWhC;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;IAKjD,YAAY,IAGX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;IAC7C,CAAC;IAED,yFAAyF;IACzF,eAAe,CAAC,IAKf;QACC,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,cAAc,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAAC;QAEjE,IAAI,cAAc,IAAI,CAAC,kBA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AAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,mBAAmB,CAAC,IAAI;SACjC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAA;;aAEjC,eAAe;0DAC8B,GAAG,CAAC,IAAI,CAC1D,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAA,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAChE,GAAG,CAAA,IAAI,CACR;mCAC4B,8BAA8B,CAAC,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,CACpG,EAAE,KAAK,EAAE,YAAY,EAAE,CACxB;KACJ,CAAC,CAAC;QAEH,OAAO,oBAAoB,CAAC,cAAc,CAKvC;YACD,MAAM;SACP,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base';\nimport { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport {\n AuthorizationActions,\n AuthorizationPermissionBuilder,\n AuthorizationPolicyVariants,\n GrantBuilder,\n type TCustomGrantMetadata,\n} from '@venizia/ignis-kernel';\nimport { sql, type SQL } from 'drizzle-orm';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicySource, IScopedCasbinEntities } from './common';\n\nconst DEFAULT_SCHEMA = 'public';\n\n/** A custom row that survived {@link CustomGrantExpander.rejectCustomRow}, ready for op-to-catalog resolution. */\nexport type TCustomGrantRow = {\n subjectId: IdType;\n objectSubject: string;\n ops: string[];\n domain: string;\n effect: string;\n};\n\n/**\n * Expands \"custom\" operation-subset grants (`metadata.ops`) into one casbin line per catalogued\n * operation. Isolated from the filtered-policy loader on purpose: it owns its own SQL\n * (`queryOperationCatalog`) and error vocabulary, and never reaches back into ScopedCasbinAdapter.\n */\nexport class CustomGrantExpander extends BaseHelper {\n protected readonly dataSource: ICasbinPolicySource;\n protected readonly permission: IScopedCasbinEntities['permission'];\n protected readonly softDelete: IScopedCasbinEntities['softDelete'];\n\n constructor(opts: {\n dataSource: ICasbinPolicySource;\n entities: Pick<IScopedCasbinEntities, 'permission' | 'softDelete'>;\n }) {\n super({ scope: CustomGrantExpander.name });\n this.dataSource = opts.dataSource;\n this.permission = opts.entities.permission;\n this.softDelete = opts.entities.softDelete;\n }\n\n /** Why a custom-looking grant row cannot be honoured, or null when it is well formed. */\n rejectCustomRow(opts: {\n row: { subjectId: IdType; objectCode: string; objectMethod: string };\n parsed: TCustomGrantMetadata | null;\n isCustomAction: boolean;\n metadataColumnName?: string;\n }): string | null {\n const { row, parsed, isCustomAction, metadataColumnName } = opts;\n\n if (isCustomAction && !metadataColumnName) {\n return `Skipping custom grant - entities.policyDefinition.metadata.columnName is not mapped, so metadata.ops cannot be read | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (isCustomAction && !parsed) {\n return `Skipping custom grant - metadata.ops is missing, empty, or not an array of non-empty strings | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (!isCustomAction && parsed) {\n return `Skipping grant - metadata.ops is present but action is not \"${AuthorizationActions.CUSTOM}\", so the intent is ambiguous | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (row.objectMethod !== AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD) {\n return `Skipping custom grant - the target must be a subject-level resource node | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n return null;\n }\n\n /** Resolve every custom row's ops in one catalog query, then emit one line per resolved operation. Unresolvable ops come back as `rejections` rather than being logged here - the caller owns the logger the tests swap. */\n async expandCustomGrants(opts: {\n subjectType: string;\n customRows: TCustomGrantRow[];\n }): Promise<{ lines: string[]; rejections: string[] }> {\n if (!opts.customRows.length) {\n return { lines: [], rejections: [] };\n }\n\n const seen = new Set<string>();\n const pairs: Array<{ subject: string; method: string }> = [];\n\n const candidates = opts.customRows.flatMap((row) =>\n row.ops.map((op) => ({ subject: row.objectSubject, method: op })),\n );\n\n for (const candidate of candidates) {\n const key = `${candidate.subject}.${candidate.method}`;\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n pairs.push(candidate);\n }\n\n const catalog = await this.queryOperationCatalog({ pairs });\n const byKey = new Map(catalog.map((entry) => [`${entry.subject}.${entry.method}`, entry]));\n const lines: string[] = [];\n const rejections: string[] = [];\n\n for (const row of opts.customRows) {\n const { valid, unknown } = GrantBuilder.getInstance().validateCustomGrantOps({\n ops: row.ops,\n subject: row.objectSubject,\n catalog,\n });\n\n if (unknown.length) {\n rejections.push(\n `Skipping unresolvable operations in a custom grant | subject id: ${row.subjectId} | resource: ${row.objectSubject} | unknown: ${unknown.join(', ')}`,\n );\n }\n\n for (const op of valid) {\n const entry = byKey.get(`${row.objectSubject}.${op}`)!;\n\n lines.push(\n `${AuthorizationPolicyVariants.GRANT.rule}, ${opts.subjectType}_${row.subjectId}, ${row.domain}, ${entry.code}, ${entry.action}, ${row.effect}`,\n );\n }\n }\n\n return { lines, rejections };\n }\n\n /** Schema-qualified table reference (`\"<schema>\".\"<table>\"`) for use after FROM/JOIN with an alias. */\n private qualifiedTable(opts: { table: { schemaName?: string; tableName: string } }): SQL {\n const { table } = opts;\n const schema = table.schemaName ?? DEFAULT_SCHEMA;\n\n return sql`${sql.identifier(schema)}.${sql.identifier(table.tableName)}`;\n }\n\n /** `AND <alias>.<col> IS NULL` when soft-delete is on, else empty. The alias is emitted raw to match the unquoted FROM alias - quoting folds it to a different case and breaks the join. */\n private softDeleteClause(opts: { alias: string }): SQL {\n const sd = this.softDelete;\n\n if (!sd?.use) {\n return sql.empty();\n }\n\n return sql` AND ${sql.raw(opts.alias)}.${sql.identifier(sd.columnName)} IS NULL`;\n }\n\n /** Resolve `(subject, method)` pairs to catalogued operations. One query for the whole extraction. */\n private async queryOperationCatalog(opts: {\n pairs: Array<{ subject: string; method: string }>;\n }): Promise<Array<{ subject: string; method: string; code: string; action: string }>> {\n if (!opts.pairs.length) {\n return [];\n }\n\n const permissionTable = this.qualifiedTable({ table: this.permission });\n const connector = PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: CustomGrantExpander.name,\n });\n\n const result = await connector.execute(sql`\n SELECT permission.subject, permission.method, permission.code, permission.action\n FROM ${permissionTable} permission\n WHERE (permission.subject, permission.method) IN (${sql.join(\n opts.pairs.map((pair) => sql`(${pair.subject}, ${pair.method})`),\n sql`, `,\n )})\n AND permission.method <> ${AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD}${this.softDeleteClause(\n { alias: 'permission' },\n )}\n `);\n\n return DrizzleResultUtility.readResultRows<{\n subject: string;\n method: string;\n code: string;\n action: string;\n }>({\n result,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"custom-grant-expander.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/custom-grant-expander.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EACL,oBAAoB,EACpB,8BAA8B,EAC9B,2BAA2B,EAC3B,YAAY,GAEb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,MAAM,cAAc,GAAG,QAAQ,CAAC;AAWhC;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;IAKjD,YAAY,IAGX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;IAC7C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QAED,MAAM,eAAe,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QACxE,MAAM,SAAS,GAAG,MAAM,uBAAuB,CAAC,OAAO,CAAC;YACtD,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,mBAAmB,CAAC,IAAI;SACjC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAA;;aAEjC,eAAe;0DAC8B,GAAG,CAAC,IAAI,CAC1D,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAA,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAChE,GAAG,CAAA,IAAI,CACR;mCAC4B,8BAA8B,CAAC,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,CACpG,EAAE,KAAK,EAAE,YAAY,EAAE,CACxB;KACJ,CAAC,CAAC;QAEH,OAAO,oBAAoB,CAAC,cAAc,CAKvC;YACD,MAAM;SACP,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base';\nimport { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport {\n AuthorizationActions,\n AuthorizationPermissionBuilder,\n AuthorizationPolicyVariants,\n GrantBuilder,\n type TCustomGrantMetadata,\n} from '@venizia/ignis-kernel';\nimport { sql, type SQL } from 'drizzle-orm';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicySource, IScopedCasbinEntities } from './common';\n\nconst DEFAULT_SCHEMA = 'public';\n\n/** A custom row that survived {@link CustomGrantExpander.rejectCustomRow}, ready for op-to-catalog resolution. */\nexport type TCustomGrantRow = {\n subjectId: IdType;\n objectSubject: string;\n ops: string[];\n domain: string;\n effect: string;\n};\n\n/**\n * Expands \"custom\" operation-subset grants (`metadata.ops`) into one casbin line per catalogued\n * operation. Isolated from the filtered-policy loader on purpose: it owns its own SQL\n * (`queryOperationCatalog`) and error vocabulary, and never reaches back into ScopedCasbinAdapter.\n */\nexport class CustomGrantExpander extends BaseHelper {\n protected readonly dataSource: ICasbinPolicySource;\n protected readonly permission: IScopedCasbinEntities['permission'];\n protected readonly softDelete: IScopedCasbinEntities['softDelete'];\n\n constructor(opts: {\n dataSource: ICasbinPolicySource;\n entities: Pick<IScopedCasbinEntities, 'permission' | 'softDelete'>;\n }) {\n super({ scope: CustomGrantExpander.name });\n this.dataSource = opts.dataSource;\n this.permission = opts.entities.permission;\n this.softDelete = opts.entities.softDelete;\n }\n\n /** Why a custom-looking grant row cannot be honoured, or null when it is well formed. */\n rejectCustomRow(opts: {\n row: { subjectId: IdType; objectCode: string; objectMethod: string };\n parsed: TCustomGrantMetadata | null;\n isCustomAction: boolean;\n metadataColumnName?: string;\n }): string | null {\n const { row, parsed, isCustomAction, metadataColumnName } = opts;\n\n if (isCustomAction && !metadataColumnName) {\n return `Skipping custom grant - entities.policyDefinition.metadata.columnName is not mapped, so metadata.ops cannot be read | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (isCustomAction && !parsed) {\n return `Skipping custom grant - metadata.ops is missing, empty, or not an array of non-empty strings | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (!isCustomAction && parsed) {\n return `Skipping grant - metadata.ops is present but action is not \"${AuthorizationActions.CUSTOM}\", so the intent is ambiguous | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (row.objectMethod !== AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD) {\n return `Skipping custom grant - the target must be a subject-level resource node | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n return null;\n }\n\n /** Resolve every custom row's ops in one catalog query, then emit one line per resolved operation. Unresolvable ops come back as `rejections` rather than being logged here - the caller owns the logger the tests swap. */\n async expandCustomGrants(opts: {\n subjectType: string;\n customRows: TCustomGrantRow[];\n }): Promise<{ lines: string[]; rejections: string[] }> {\n if (!opts.customRows.length) {\n return { lines: [], rejections: [] };\n }\n\n const seen = new Set<string>();\n const pairs: Array<{ subject: string; method: string }> = [];\n\n const candidates = opts.customRows.flatMap((row) =>\n row.ops.map((op) => ({ subject: row.objectSubject, method: op })),\n );\n\n for (const candidate of candidates) {\n const key = `${candidate.subject}.${candidate.method}`;\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n pairs.push(candidate);\n }\n\n const catalog = await this.queryOperationCatalog({ pairs });\n const byKey = new Map(catalog.map((entry) => [`${entry.subject}.${entry.method}`, entry]));\n const lines: string[] = [];\n const rejections: string[] = [];\n\n for (const row of opts.customRows) {\n const { valid, unknown } = GrantBuilder.getInstance().validateCustomGrantOps({\n ops: row.ops,\n subject: row.objectSubject,\n catalog,\n });\n\n if (unknown.length) {\n rejections.push(\n `Skipping unresolvable operations in a custom grant | subject id: ${row.subjectId} | resource: ${row.objectSubject} | unknown: ${unknown.join(', ')}`,\n );\n }\n\n for (const op of valid) {\n const entry = byKey.get(`${row.objectSubject}.${op}`)!;\n\n lines.push(\n `${AuthorizationPolicyVariants.GRANT.rule}, ${opts.subjectType}_${row.subjectId}, ${row.domain}, ${entry.code}, ${entry.action}, ${row.effect}`,\n );\n }\n }\n\n return { lines, rejections };\n }\n\n /** Schema-qualified table reference (`\"<schema>\".\"<table>\"`) for use after FROM/JOIN with an alias. */\n private qualifiedTable(opts: { table: { schemaName?: string; tableName: string } }): SQL {\n const { table } = opts;\n const schema = table.schemaName ?? DEFAULT_SCHEMA;\n\n return sql`${sql.identifier(schema)}.${sql.identifier(table.tableName)}`;\n }\n\n /** `AND <alias>.<col> IS NULL` when soft-delete is on, else empty. The alias is emitted raw to match the unquoted FROM alias - quoting folds it to a different case and breaks the join. */\n private softDeleteClause(opts: { alias: string }): SQL {\n const sd = this.softDelete;\n\n if (!sd?.use) {\n return sql.empty();\n }\n\n return sql` AND ${sql.raw(opts.alias)}.${sql.identifier(sd.columnName)} IS NULL`;\n }\n\n /** Resolve `(subject, method)` pairs to catalogued operations. One query for the whole extraction. */\n private async queryOperationCatalog(opts: {\n pairs: Array<{ subject: string; method: string }>;\n }): Promise<Array<{ subject: string; method: string; code: string; action: string }>> {\n if (!opts.pairs.length) {\n return [];\n }\n\n const permissionTable = this.qualifiedTable({ table: this.permission });\n const connector = await PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: CustomGrantExpander.name,\n });\n\n const result = await connector.execute(sql`\n SELECT permission.subject, permission.method, permission.code, permission.action\n FROM ${permissionTable} permission\n WHERE (permission.subject, permission.method) IN (${sql.join(\n opts.pairs.map((pair) => sql`(${pair.subject}, ${pair.method})`),\n sql`, `,\n )})\n AND permission.method <> ${AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD}${this.softDeleteClause(\n { alias: 'permission' },\n )}\n `);\n\n return DrizzleResultUtility.readResultRows<{\n subject: string;\n method: string;\n code: string;\n action: string;\n }>({\n result,\n });\n }\n}\n"]}
@@ -14,9 +14,9 @@
14
14
  "dependencies": {
15
15
  "@hono/zod-openapi": "^1.6.3",
16
16
  "@scalar/hono-api-reference": "^0.12.13",
17
- "@venizia/ignis": "0.4.8-5",
18
- "@venizia/ignis-boot": "0.4.8-5",
19
- "@venizia/ignis-helpers": "0.4.8-5",
17
+ "@venizia/ignis": "0.4.8-6",
18
+ "@venizia/ignis-boot": "0.4.8-6",
19
+ "@venizia/ignis-helpers": "0.4.8-6",
20
20
  "hono": "^4.13.13",
21
21
  "winston": "^3.19.0",
22
22
  "winston-daily-rotate-file": "^5.0.0",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "devDependencies": {
26
26
  "@types/bun": "^1.4.3",
27
- "@venizia/dev-configs": "0.4.8-2",
27
+ "@venizia/dev-configs": "0.4.8-3",
28
28
  "eslint": "^10.13.0",
29
29
  "oxlint": "1.89.0",
30
30
  "oxlint-tsgolint": "7.0.2004",
@@ -4,15 +4,15 @@
4
4
  "dependencies": {},
5
5
  "devDependencies": {
6
6
  "@types/bun": "^1.4.3",
7
- "@venizia/dev-configs": "0.4.8-2",
8
- "@venizia/ignis": "0.4.8-5",
7
+ "@venizia/dev-configs": "0.4.8-3",
8
+ "@venizia/ignis": "0.4.8-6",
9
9
  "eslint": "^10.13.0",
10
10
  "oxlint": "1.89.0",
11
11
  "oxlint-tsgolint": "7.0.2004",
12
12
  "typescript": "^6.0.3"
13
13
  },
14
14
  "peerDependencies": {
15
- "@venizia/ignis": "0.4.8-5"
15
+ "@venizia/ignis": "0.4.8-6"
16
16
  },
17
17
  "scripts": {
18
18
  "typecheck": "bun check",
@@ -4,7 +4,7 @@
4
4
  "dependencies": {},
5
5
  "devDependencies": {
6
6
  "@types/bun": "^1.4.3",
7
- "@venizia/dev-configs": "0.4.8-2",
7
+ "@venizia/dev-configs": "0.4.8-3",
8
8
  "eslint": "^10.13.0",
9
9
  "oxlint": "1.89.0",
10
10
  "oxlint-tsgolint": "7.0.2004",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis",
3
- "version": "0.4.8-5",
3
+ "version": "0.4.8-6",
4
4
  "description": "TypeScript server framework with decorator-based DI, the repository pattern and a component system, on Hono. Features auto-generated OpenAPI docs, Drizzle ORM type-safe SQL, JWT/Basic authentication, Casbin authorization, convention-based bootstrapping, and pluggable components for health checks, Swagger UI, mail, Socket.IO, and static assets. Built for Bun.",
5
5
  "keywords": [
6
6
  "access-control",
@@ -134,11 +134,11 @@
134
134
  "force-update": "sh ../../scripts/build/force-update.sh"
135
135
  },
136
136
  "dependencies": {
137
- "@venizia/ignis-connectors": "0.4.8-5",
138
- "@venizia/ignis-filter": "0.4.7-3",
139
- "@venizia/ignis-helpers": "0.4.8-5",
140
- "@venizia/ignis-inversion": "0.4.7-2",
141
- "@venizia/ignis-kernel": "0.4.8-5",
137
+ "@venizia/ignis-connectors": "0.4.8-6",
138
+ "@venizia/ignis-filter": "0.4.7-4",
139
+ "@venizia/ignis-helpers": "0.4.8-6",
140
+ "@venizia/ignis-inversion": "0.4.7-3",
141
+ "@venizia/ignis-kernel": "0.4.8-6",
142
142
  "reflect-metadata": "^0.2.2"
143
143
  },
144
144
  "devDependencies": {
@@ -151,8 +151,8 @@
151
151
  "@types/bun": "^1.4.3",
152
152
  "@types/nodemailer": "^8.0.2",
153
153
  "@types/pg": "^8.23.1",
154
- "@venizia/dev-configs": "0.4.8-2",
155
- "@venizia/ignis-boot": "0.4.8-5",
154
+ "@venizia/dev-configs": "0.4.8-3",
155
+ "@venizia/ignis-boot": "0.4.8-6",
156
156
  "casbin": "^5.51.1",
157
157
  "eslint": "^10.13.0",
158
158
  "meilisearch": "^0.62.0",