@venizia/ignis 0.4.8-1 → 0.4.8-10

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 (108) hide show
  1. package/README.md +7 -14
  2. package/dist/esm/base/applications/server.d.ts +12 -0
  3. package/dist/esm/base/applications/server.js +11 -0
  4. package/dist/esm/base/applications/server.js.map +1 -1
  5. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
  6. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
  7. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
  8. package/dist/esm/components/auth/authenticate/component.js +37 -1
  9. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  10. package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +1 -0
  11. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
  12. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
  13. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  14. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +2 -2
  15. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
  16. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +10 -3
  17. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
  18. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
  19. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
  20. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
  21. package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
  22. package/dist/esm/components/auth/authenticate/services/index.js +1 -0
  23. package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
  24. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +42 -0
  25. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +162 -0
  26. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
  27. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
  28. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
  29. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
  30. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
  31. package/dist/esm/components/auth/authorize/adapters/base-filtered.d.ts +1 -1
  32. package/dist/esm/components/auth/authorize/adapters/base-filtered.js +3 -2
  33. package/dist/esm/components/auth/authorize/adapters/base-filtered.js.map +1 -1
  34. package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +2 -0
  35. package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
  36. package/dist/esm/components/auth/authorize/adapters/connector.d.ts +2 -2
  37. package/dist/esm/components/auth/authorize/adapters/connector.js +3 -2
  38. package/dist/esm/components/auth/authorize/adapters/connector.js.map +1 -1
  39. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js +1 -1
  40. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
  41. package/dist/esm/components/health-check/reporter.js +2 -2
  42. package/dist/esm/components/health-check/reporter.js.map +1 -1
  43. package/dist/esm/components/index.d.ts +1 -0
  44. package/dist/esm/components/index.js +1 -0
  45. package/dist/esm/components/index.js.map +1 -1
  46. package/dist/esm/components/mail/common/types/verification.d.ts +1 -0
  47. package/dist/esm/components/mail/common/types/verification.js.map +1 -1
  48. package/dist/esm/components/mail/services/generators/numeric-code.d.ts +1 -6
  49. package/dist/esm/components/mail/services/generators/numeric-code.js +3 -31
  50. package/dist/esm/components/mail/services/generators/numeric-code.js.map +1 -1
  51. package/dist/esm/components/mail/services/generators/random-token.d.ts +4 -1
  52. package/dist/esm/components/mail/services/generators/random-token.js +9 -6
  53. package/dist/esm/components/mail/services/generators/random-token.js.map +1 -1
  54. package/dist/esm/components/mail/utilities/mime.utility.js +4 -4
  55. package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
  56. package/dist/esm/components/server-info/common/constants.d.ts +6 -0
  57. package/dist/esm/components/server-info/common/constants.js +6 -0
  58. package/dist/esm/components/server-info/common/constants.js.map +1 -0
  59. package/dist/esm/components/server-info/common/index.d.ts +5 -0
  60. package/dist/esm/components/server-info/common/index.js +5 -0
  61. package/dist/esm/components/server-info/common/index.js.map +1 -0
  62. package/dist/esm/components/server-info/common/keys.d.ts +5 -0
  63. package/dist/esm/components/server-info/common/keys.js +5 -0
  64. package/dist/esm/components/server-info/common/keys.js.map +1 -0
  65. package/dist/esm/components/server-info/common/rest-paths.d.ts +5 -0
  66. package/dist/esm/components/server-info/common/rest-paths.js +5 -0
  67. package/dist/esm/components/server-info/common/rest-paths.js.map +1 -0
  68. package/dist/esm/components/server-info/common/types.d.ts +68 -0
  69. package/dist/esm/components/server-info/common/types.js +2 -0
  70. package/dist/esm/components/server-info/common/types.js.map +1 -0
  71. package/dist/esm/components/server-info/component.d.ts +31 -0
  72. package/dist/esm/components/server-info/component.js +87 -0
  73. package/dist/esm/components/server-info/component.js.map +1 -0
  74. package/dist/esm/components/server-info/controller.d.ts +14 -0
  75. package/dist/esm/components/server-info/controller.js +68 -0
  76. package/dist/esm/components/server-info/controller.js.map +1 -0
  77. package/dist/esm/components/server-info/index.d.ts +5 -0
  78. package/dist/esm/components/server-info/index.js +5 -0
  79. package/dist/esm/components/server-info/index.js.map +1 -0
  80. package/dist/esm/components/server-info/reporter.d.ts +25 -0
  81. package/dist/esm/components/server-info/reporter.js +68 -0
  82. package/dist/esm/components/server-info/reporter.js.map +1 -0
  83. package/dist/esm/components/static-asset/common/constants.d.ts +2 -0
  84. package/dist/esm/components/static-asset/common/constants.js +2 -0
  85. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  86. package/dist/esm/components/static-asset/common/types.d.ts +6 -0
  87. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  88. package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
  89. package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
  90. package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
  91. package/dist/esm/components/static-asset/controller/factory.d.ts +1 -0
  92. package/dist/esm/components/static-asset/controller/factory.js +17 -9
  93. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  94. package/dist/esm/components/static-asset/controller/meta-link.js +1 -1
  95. package/dist/esm/components/static-asset/controller/meta-link.js.map +1 -1
  96. package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
  97. package/dist/esm/components/static-asset/controller/route-options.js +16 -3
  98. package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
  99. package/dist/esm/components/static-asset/ingest.d.ts +2 -2
  100. package/dist/esm/components/static-asset/ingest.js +2 -2
  101. package/dist/esm/components/static-asset/ingest.js.map +1 -1
  102. package/dist/esm/testing/assert-application-boots.d.ts +9 -0
  103. package/dist/esm/testing/assert-application-boots.js +11 -1
  104. package/dist/esm/testing/assert-application-boots.js.map +1 -1
  105. package/dist/presets/app/preset.json +4 -4
  106. package/dist/presets/lib/preset.json +3 -3
  107. package/dist/presets/shared/preset.json +1 -1
  108. package/package.json +8 -8
package/README.md CHANGED
@@ -110,6 +110,7 @@ Register a component with `this.component(...)` in `preConfigure()`.
110
110
  |---|---|---|
111
111
  | `ApiReferenceComponent` | `@venizia/ignis` | The OpenAPI document and a Scalar or Swagger UI explorer (`@scalar/hono-api-reference` or `@hono/swagger-ui`) |
112
112
  | `HealthCheckComponent` | `@venizia/ignis` | `GET /health`, `POST /health/ping`, and `GET /health/stats` (closed outside development unless you enable it) |
113
+ | `ServerInfoComponent` | `@venizia/ignis` | `GET /server/info/time`, a public route that carries only data safe to publish (the server clock) |
113
114
  | `AuthenticateComponent` | `@venizia/ignis` | JWT, Basic, and service-to-service authentication strategies |
114
115
  | `AuthorizeComponent` | `@venizia/ignis` | Casbin-based authorization (`casbin`) |
115
116
  | `RequestTrackerComponent` | `@venizia/ignis` | Logs each request and response - registered for you by `BaseApplication` |
@@ -130,28 +131,20 @@ you use.
130
131
 
131
132
  | Import | What it gives | Extra peers |
132
133
  |---|---|---|
133
- | `@venizia/ignis` | `BaseApplication`, the kernel in full, the root components, and everything in `/postgres` | none |
134
- | `/postgres` | Postgres datasources, entities, repositories, `ModelFactory` | none |
135
- | `/postgres/node-postgres` | `NodePostgresDriver` | `pg` |
136
- | `/postgres/postgres-js` | `PostgresJsDriver` | `postgres` |
137
- | `/postgres/pglite` | `PGliteDriver` | `@electric-sql/pglite` |
138
- | `/postgres/supabase` | Supabase auth context and pooler helpers | none |
139
- | `/relational` | The engine-neutral SQL tier (`DefaultRelationalRepository`, `BaseRelationalDataSource`) | none |
140
- | `/sqlite` | SQLite datasources and repositories | none |
141
- | `/sqlite/libsql` | `LibSqlDriver` | `@libsql/client` |
142
- | `/search`, `/search/controllers` | The engine-neutral search tier and its controllers | none |
143
- | `/typesense`, `/typesense/controllers` | The Typesense engine, and the search controllers | `typesense` for `/typesense` |
144
- | `/meilisearch` | The Meilisearch engine | `meilisearch` |
134
+ | `@venizia/ignis` | `BaseApplication`, the kernel in full, the root components, and the Postgres entry of `@venizia/ignis-connectors` (`/postgres`) | none |
145
135
  | `/grpc` | `GrpcComponent` (`BaseGrpcController` and `@rpc` come from the root) | none to load |
146
136
  | `/mail` | `MailComponent` | none to load |
147
137
  | `/socket-io` | `SocketIOComponent` | `socket.io`, `@socket.io/redis-adapter`, `@socket.io/redis-emitter` |
148
138
  | `/websocket` | `WebSocketComponent` | none |
149
139
  | `/static-asset` | `StaticAssetComponent` | none |
140
+ | `/testing` | Test-only: the `@venizia/ignis-connectors/testing` doubles and the application boot helper; never in the root barrel | none |
150
141
 
151
142
  "None to load" means the entry imports cleanly; the component loads its client library (for example
152
143
  `nodemailer` or `@connectrpc/connect`) when you configure it.
153
144
 
154
- The connector entries re-export `@venizia/ignis-connectors` under the same names. The kernel is
145
+ The root re-exports the Postgres entry of `@venizia/ignis-connectors` and nothing else of it. Every other
146
+ connector (a Postgres driver, SQLite, PGlite, search, `/raw-sql`, `/http`) is imported from
147
+ `@venizia/ignis-connectors`, so an app that uses one lists that package as a dependency. The kernel is
155
148
  re-exported in full from the root.
156
149
 
157
150
  ## Where it sits
@@ -169,7 +162,7 @@ Top of the chain. Depends on `@venizia/ignis-kernel`, `@venizia/ignis-connectors
169
162
  - [Components](https://ignis.venizia.ai/extensions/components/)
170
163
  - [All changelogs](https://ignis.venizia.ai/changelogs/)
171
164
 
172
- IGNIS is 0.x: a minor version can break. Pin exact versions and read the changelog before upgrading.
165
+ IGNIS is 0.x: a patch release can carry a breaking change. Pin exact versions and read the changelog before upgrading.
173
166
 
174
167
  MIT licensed - see [LICENSE.md](https://github.com/VENIZIA-AI/ignis/blob/main/packages/core-server/LICENSE.md).
175
168
 
@@ -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;
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/base/applications/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,IAAI,MAAM,WAAW,CAAC;AAW7B,MAAM,WAAW,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAW3C,qGAAqG;AACrG,MAAM,OAAO,eAAe;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,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,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,IAAI,MAAM,WAAW,CAAC;AAW7B,MAAM,WAAW,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAW3C,qGAAqG;AACrG,MAAM,OAAO,eAAe;IAC1B,2CAA2C;IAC3C,MAAM,CAAC,YAAY;QACjB,OAAO;YACL,UAAU,EAAE,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;YAC5D,SAA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,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"]}
@@ -5,6 +5,7 @@ import { type TContext } from '@venizia/ignis-kernel';
5
5
  /** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */
6
6
  export declare class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {
7
7
  static readonly REQUEST_ID_KEY = "requestId";
8
+ private static readonly CALLBACK_PARAMETERS;
8
9
  private isDebugMode;
9
10
  /**
10
11
  * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this
@@ -1,13 +1,14 @@
1
1
  import { NetworkUtility } from '../../../utilities/network.utility.js';
2
2
  import { Environment } from '@venizia/ignis-helpers';
3
3
  import { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';
4
- import { HTTP } from '@venizia/ignis-helpers/common';
4
+ import { HTTP, REDACTED } from '@venizia/ignis-helpers/common';
5
5
  import { createMiddleware } from 'hono/factory';
6
6
  import { REQUEST_ID_KEY, RequestErrors } from '@venizia/ignis-kernel';
7
7
  const TEXT_CONTENT_TYPE_PREFIX = 'text/';
8
8
  /** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */
9
9
  export class RequestSpyMiddleware extends BaseHelper {
10
10
  static { this.REQUEST_ID_KEY = REQUEST_ID_KEY; }
11
+ static { this.CALLBACK_PARAMETERS = new Set(['code', 'state']); }
11
12
  /**
12
13
  * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this
13
14
  * framework recognises as a development one enables body logging.
@@ -82,7 +83,13 @@ export class RequestSpyMiddleware extends BaseHelper {
82
83
  const path = req.path ?? '/';
83
84
  // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.
84
85
  const clientIp = incomingIp ?? forwardedIp ?? 'unknown';
85
- const query = req.query() ?? {};
86
+ // `code` and `state` are credentials in an OAuth callback and too common as plain names to mask everywhere.
87
+ const query = Object.fromEntries(Object.entries(req.query() ?? {}).map(([key, value]) => {
88
+ return [
89
+ key,
90
+ RequestSpyMiddleware.CALLBACK_PARAMETERS.has(key.toLowerCase()) ? REDACTED : value,
91
+ ];
92
+ }));
86
93
  if (this.isDebugMode) {
87
94
  const body = await this.parseBody({ req });
88
95
  this.logger.info('[%s][%s][=>] %s %s | query: %j | body: %j', requestId, clientIp, method.padEnd(8, ' '), path, query, body);
@@ -1 +1 @@
1
- {"version":3,"file":"request-spy.middleware.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/request-spy/request-spy.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAErD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAiB,MAAM,uBAAuB,CAAC;AAErF,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEzC,mPAAmP;AACnP,MAAM,OAAO,oBAAqB,SAAQ,UAAU;aAClC,mBAAc,GAAG,cAAc,CAAC;IAIhD;;;;;;;;;OASG;IACH;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAC1B,MAAM,GAAG,GAAG,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,CAAC;QAC/C,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,GAAG,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzE,CAAC;IAED,8PAA8P;IAC9P,KAAK,CAAC,SAAS,CAAC,IAA8B;QAC5C,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAE/D,IAAI,CAAC,WAAW,EAAE,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E,CAAC,CAAC;gBAC3C,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,2CAA2C,EAC3C,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,KAAK,EACL,IAAI,CACL,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,4FAA4F;gBAC5F,yFAAyF;gBACzF,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,EAAE,CAAC;oBACxF,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;gBAChC,CAAC;gBAED,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,gCAAgC,EAChC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,KAAK,CACN,CAAC;YACJ,CAAC;YAED,MAAM,IAAI,EAAE,CAAC;YAEb,MAAM,QAAQ,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACpD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,oCAAoC,EACpC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,QAAQ,CACT,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { NetworkUtility } from '@/utilities/network.utility';\nimport { Environment } from '@venizia/ignis-helpers';\nimport { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport { createMiddleware } from 'hono/factory';\nimport type { MiddlewareHandler } from 'hono/types';\nimport { REQUEST_ID_KEY, RequestErrors, type TContext } from '@venizia/ignis-kernel';\n\nconst TEXT_CONTENT_TYPE_PREFIX = 'text/';\n\n/** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */\nexport class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {\n static readonly REQUEST_ID_KEY = REQUEST_ID_KEY;\n\n private isDebugMode: boolean;\n\n /**\n * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this\n * framework recognises as a development one enables body logging.\n *\n * The previous test was `env !== 'production'`, which enabled it for an unset `NODE_ENV` and for\n * every pre-production name that carries real user data - `staging`, `uat`, `alpha`, `beta`, and\n * the abbreviation `prod`. `development-envs.test.ts` pins those as NOT development for exactly\n * that reason. Redaction is no defence here: it masks secret-SHAPED keys, so `nationalId`,\n * `cardNumber` and `ssn` were written verbatim.\n */\n constructor() {\n super({ scope: 'SpyMW' });\n const env = Environment.ambient?.toLowerCase();\n this.isDebugMode = !!env && EnvironmentNames.DEVELOPMENT_ENVS.has(env);\n }\n\n /** Parses the body by Content-Type without draining it for the handler: JSON and form bodies go through the request cache, `text/*` is read from a clone (from the cache once something read it), and any other type is described by its size, never read. */\n async parseBody(opts: { req: TContext['req'] }): Promise<unknown> {\n const contentType = opts.req.header(HTTP.Headers.CONTENT_TYPE);\n\n if (!contentType) {\n return null;\n }\n\n // Only an explicit zero short-circuits: a CHUNKED request carries no Content-Length, so gating on the header's presence would skip every streamed body and let a malformed one detonate deeper as a 500.\n const contentLength = opts.req.header(HTTP.Headers.CONTENT_LENGTH);\n\n if (contentLength === '0' || !opts.req.raw.body) {\n return null;\n }\n\n try {\n if (contentType.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n const rs = await opts.req.json();\n\n return rs;\n }\n\n if (\n contentType.includes(HTTP.HeaderValues.MULTIPART_FORM_DATA) ||\n contentType.includes(HTTP.HeaderValues.APPLICATION_FORM_URLENCODED)\n ) {\n const rs = await opts.req.parseBody();\n\n return rs;\n }\n\n if (contentType === HTTP.HeaderValues.APPLICATION_OCTET_STREAM) {\n return opts.req.raw.body;\n }\n\n // Anything else is read, if at all, from a clone: a handler may stream `req.raw.body` on (an upload proxy), and reading the request itself would drain it and mangle binary bytes.\n // A body an earlier middleware read cannot be cloned; Hono's cache serves it instead.\n if (contentType.startsWith(TEXT_CONTENT_TYPE_PREFIX)) {\n let rs: string;\n\n if (opts.req.raw.bodyUsed) {\n const cached = await opts.req.text();\n rs = cached;\n } else {\n const cloned = await opts.req.raw.clone().text();\n rs = cloned;\n }\n\n return rs;\n }\n\n return `<${contentLength ?? 'unknown'} bytes, ${contentType}>`;\n } catch {\n throw getError({\n error: RequestErrors.BODY_MALFORMED,\n message: 'Malformed Body Payload',\n });\n }\n }\n\n /** Returns a Hono middleware that logs request details and duration. */\n value() {\n return createMiddleware(async (context, next) => {\n const t = performance.now();\n const { req } = context;\n\n const requestId = context.get(RequestSpyMiddleware.REQUEST_ID_KEY);\n const incomingIp = NetworkUtility.getIncomingIp(context);\n const forwardedIp = req.header('x-real-ip') ?? req.header('x-forwarded-for') ?? null;\n\n const method = req.method;\n const path = req.path ?? '/';\n\n // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.\n const clientIp = incomingIp ?? forwardedIp ?? 'unknown';\n const query = req.query() ?? {};\n\n if (this.isDebugMode) {\n const body = await this.parseBody({ req });\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j | body: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n body,\n );\n } else {\n // Only JSON is parsed here: its clean 400 on a malformed body is a contract. Any other body\n // would be read for a log line that never prints it, before the route's own size checks.\n if (req.header(HTTP.Headers.CONTENT_TYPE)?.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n await this.parseBody({ req });\n }\n\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n );\n }\n\n await next();\n\n const duration = (performance.now() - t).toFixed(2);\n this.logger.info(\n '[%s][%s][<=] %s %s | Took: %s (ms)',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n duration,\n );\n });\n }\n}\n"]}
1
+ {"version":3,"file":"request-spy.middleware.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/request-spy/request-spy.middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACrF,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAiB,MAAM,uBAAuB,CAAC;AAErF,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEzC,mPAAmP;AACnP,MAAM,OAAO,oBAAqB,SAAQ,UAAU;aAClC,mBAAc,GAAG,cAAc,CAAC;aACxB,wBAAmB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAIzE;;;;;;;;;OASG;IACH;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAC1B,MAAM,GAAG,GAAG,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,CAAC;QAC/C,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,GAAG,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzE,CAAC;IAED,8PAA8P;IAC9P,KAAK,CAAC,SAAS,CAAC,IAA8B;QAC5C,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG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I,CACd,oCAAoC,EACpC,SAAS,EACT,QAAQ,EACR,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,EACrB,IAAI,EACJ,QAAQ,CACT,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { NetworkUtility } from '@/utilities/network.utility';\nimport { Environment } from '@venizia/ignis-helpers';\nimport { BaseHelper, EnvironmentNames, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, REDACTED } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport { createMiddleware } from 'hono/factory';\nimport type { MiddlewareHandler } from 'hono/types';\nimport { REQUEST_ID_KEY, RequestErrors, type TContext } from '@venizia/ignis-kernel';\n\nconst TEXT_CONTENT_TYPE_PREFIX = 'text/';\n\n/** Logs incoming/outgoing request details. The BODY is parsed and logged only in a recognised development environment - see the constructor for why that test is fail-closed; elsewhere only a JSON body is parsed, for its malformed-body 400. */\nexport class RequestSpyMiddleware extends BaseHelper implements IProvider<MiddlewareHandler> {\n static readonly REQUEST_ID_KEY = REQUEST_ID_KEY;\n private static readonly CALLBACK_PARAMETERS = new Set(['code', 'state']);\n\n private isDebugMode: boolean;\n\n /**\n * Fail-CLOSED, matching {@link BaseAppErrorMiddleware.isProduction}: only an environment this\n * framework recognises as a development one enables body logging.\n *\n * The previous test was `env !== 'production'`, which enabled it for an unset `NODE_ENV` and for\n * every pre-production name that carries real user data - `staging`, `uat`, `alpha`, `beta`, and\n * the abbreviation `prod`. `development-envs.test.ts` pins those as NOT development for exactly\n * that reason. Redaction is no defence here: it masks secret-SHAPED keys, so `nationalId`,\n * `cardNumber` and `ssn` were written verbatim.\n */\n constructor() {\n super({ scope: 'SpyMW' });\n const env = Environment.ambient?.toLowerCase();\n this.isDebugMode = !!env && EnvironmentNames.DEVELOPMENT_ENVS.has(env);\n }\n\n /** Parses the body by Content-Type without draining it for the handler: JSON and form bodies go through the request cache, `text/*` is read from a clone (from the cache once something read it), and any other type is described by its size, never read. */\n async parseBody(opts: { req: TContext['req'] }): Promise<unknown> {\n const contentType = opts.req.header(HTTP.Headers.CONTENT_TYPE);\n\n if (!contentType) {\n return null;\n }\n\n // Only an explicit zero short-circuits: a CHUNKED request carries no Content-Length, so gating on the header's presence would skip every streamed body and let a malformed one detonate deeper as a 500.\n const contentLength = opts.req.header(HTTP.Headers.CONTENT_LENGTH);\n\n if (contentLength === '0' || !opts.req.raw.body) {\n return null;\n }\n\n try {\n if (contentType.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n const rs = await opts.req.json();\n\n return rs;\n }\n\n if (\n contentType.includes(HTTP.HeaderValues.MULTIPART_FORM_DATA) ||\n contentType.includes(HTTP.HeaderValues.APPLICATION_FORM_URLENCODED)\n ) {\n const rs = await opts.req.parseBody();\n\n return rs;\n }\n\n if (contentType === HTTP.HeaderValues.APPLICATION_OCTET_STREAM) {\n return opts.req.raw.body;\n }\n\n // Anything else is read, if at all, from a clone: a handler may stream `req.raw.body` on (an upload proxy), and reading the request itself would drain it and mangle binary bytes.\n // A body an earlier middleware read cannot be cloned; Hono's cache serves it instead.\n if (contentType.startsWith(TEXT_CONTENT_TYPE_PREFIX)) {\n let rs: string;\n\n if (opts.req.raw.bodyUsed) {\n const cached = await opts.req.text();\n rs = cached;\n } else {\n const cloned = await opts.req.raw.clone().text();\n rs = cloned;\n }\n\n return rs;\n }\n\n return `<${contentLength ?? 'unknown'} bytes, ${contentType}>`;\n } catch {\n throw getError({\n error: RequestErrors.BODY_MALFORMED,\n message: 'Malformed Body Payload',\n });\n }\n }\n\n /** Returns a Hono middleware that logs request details and duration. */\n value() {\n return createMiddleware(async (context, next) => {\n const t = performance.now();\n const { req } = context;\n\n const requestId = context.get(RequestSpyMiddleware.REQUEST_ID_KEY);\n const incomingIp = NetworkUtility.getIncomingIp(context);\n const forwardedIp = req.header('x-real-ip') ?? req.header('x-forwarded-for') ?? null;\n\n const method = req.method;\n const path = req.path ?? '/';\n\n // Best-effort, never fatal: a unix socket, some proxies and any in-process call yield no connection info - refusing to serve because the client IP is unknown turns a logging gap into an outage.\n const clientIp = incomingIp ?? forwardedIp ?? 'unknown';\n // `code` and `state` are credentials in an OAuth callback and too common as plain names to mask everywhere.\n const query = Object.fromEntries(\n Object.entries(req.query() ?? {}).map(([key, value]) => {\n return [\n key,\n RequestSpyMiddleware.CALLBACK_PARAMETERS.has(key.toLowerCase()) ? REDACTED : value,\n ];\n }),\n );\n\n if (this.isDebugMode) {\n const body = await this.parseBody({ req });\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j | body: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n body,\n );\n } else {\n // Only JSON is parsed here: its clean 400 on a malformed body is a contract. Any other body\n // would be read for a log line that never prints it, before the route's own size checks.\n if (req.header(HTTP.Headers.CONTENT_TYPE)?.includes(HTTP.HeaderValues.APPLICATION_JSON)) {\n await this.parseBody({ req });\n }\n\n this.logger.info(\n '[%s][%s][=>] %s %s | query: %j',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n query,\n );\n }\n\n await next();\n\n const duration = (performance.now() - t).toFixed(2);\n this.logger.info(\n '[%s][%s][<=] %s %s | Took: %s (ms)',\n requestId,\n clientIp,\n method.padEnd(8, ' '),\n path,\n duration,\n );\n });\n }\n}\n"]}
@@ -16,8 +16,9 @@ import { Binding } from '@venizia/ignis-inversion';
16
16
  import { AuthenticateBindingKeys, Authentication, AuthenticationStrategyRegistry, BaseComponent, controller, CoreBindings, inject, JOSEStandards, JWKSKeyFormats, JWKSModes, ServiceAssertion, } from '@venizia/ignis-kernel';
17
17
  import { AuthControllerFactory, JWKSController } from './controllers/index.js';
18
18
  import { ServiceCertsController } from './controllers/service-certs/index.js';
19
- import { BasicTokenService, JWKSIssuerTokenService, JWKSVerifierTokenService, JWSTokenService, } from './services/index.js';
19
+ import { AbstractBearerTokenService, BasicTokenService, JWKSIssuerTokenService, JWKSVerifierTokenService, JWSTokenService, } from './services/index.js';
20
20
  import { JoseLoader } from './services/jose-loader.js';
21
+ import { JWKSUrlPolicy } from './services/jwks-url-policy.js';
21
22
  import { ServiceAssertionSignerService } from './services/service/signer.service.js';
22
23
  import { ServiceAssertionVerifierService } from './services/service/verifier.service.js';
23
24
  import { ServiceAuthenticationStrategy } from './strategies/service.strategy.js';
@@ -118,6 +119,13 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
118
119
  message: '[defineJWSAuth] getTokenExpiresFn is required',
119
120
  });
120
121
  }
122
+ // The boot refuses a configuration without claims, and a service refuses the same when built.
123
+ AbstractBearerTokenService.resolveClaimsConfig({
124
+ scope: 'defineJWSAuth',
125
+ options: jwsOptions,
126
+ pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],
127
+ });
128
+ JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });
121
129
  this.application
122
130
  .bind({ key: AuthenticateBindingKeys.JWT_OPTIONS })
123
131
  .toValue(jwsOptions);
@@ -147,6 +155,11 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
147
155
  message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',
148
156
  });
149
157
  }
158
+ AbstractBearerTokenService.resolveClaimsConfig({
159
+ scope: 'defineJWKSAuth',
160
+ options: issuerOpts,
161
+ pinnedAlgorithms: [issuerOpts.algorithm],
162
+ });
150
163
  this.application
151
164
  .bind({ key: AuthenticateBindingKeys.JWKS_OPTIONS })
152
165
  .toValue(issuerOpts);
@@ -164,6 +177,16 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
164
177
  if (!verifierOpts.jwksUrl) {
165
178
  throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });
166
179
  }
180
+ AbstractBearerTokenService.resolveClaimsConfig({
181
+ scope: 'defineJWKSAuth',
182
+ options: verifierOpts,
183
+ });
184
+ JWKSUrlPolicy.assertUrl({
185
+ scope: 'defineJWKSAuth',
186
+ label: 'jwksUrl',
187
+ url: verifierOpts.jwksUrl,
188
+ hosts: verifierOpts.jwks?.hosts?.http,
189
+ });
167
190
  this.application
168
191
  .bind({ key: AuthenticateBindingKeys.JWKS_OPTIONS })
169
192
  .toValue(verifierOpts);
@@ -205,6 +228,19 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
205
228
  message: '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',
206
229
  });
207
230
  }
231
+ // A caller's key set decides who may call: https, loopback, or a host listed in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.
232
+ JWKSUrlPolicy.resolveHttpHosts({
233
+ scope: 'defineServiceAuth',
234
+ hosts: serviceOptions.jwks?.hosts?.http,
235
+ });
236
+ for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {
237
+ JWKSUrlPolicy.assertUrl({
238
+ scope: 'defineServiceAuth',
239
+ label: `callers[${JSON.stringify(caller)}].jwksUrl`,
240
+ url: typeof entry === 'string' ? entry : entry.jwksUrl,
241
+ hosts: serviceOptions.jwks?.hosts?.http,
242
+ });
243
+ }
208
244
  this.application.service(ServiceAssertionVerifierService);
209
245
  if (serviceOptions.keys) {
210
246
  this.application.service(ServiceAssertionSignerService);
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,O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C;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;AAnTY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAmTjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
1
+ {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,0BAA0B,EAC1B,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE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;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 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"]}
@@ -153,6 +153,7 @@ export declare class AuthControllerFactory {
153
153
  }): RouteConfig & {
154
154
  getRoutingPath(): RouteConfig["path"] extends infer T ? T extends RouteConfig["path"] ? T extends `${infer Start}/{${infer Param}}${infer Rest}` ? `${Start}/:${Param}${Rest extends `${infer Start_1}/{${infer Param_1}}${infer Rest_1}` ? `${Start_1}/:${Param_1}${Rest_1 extends `${infer Start_2}/{${infer Param_2}}${infer Rest_2}` ? `${Start_2}/:${Param_2}${Rest_2 extends `${infer Start_3}/{${infer Param_3}}${infer Rest_3}` ? `${Start_3}/:${Param_3}${Rest_3 extends `${infer Start_4}/{${infer Param_4}}${infer Rest_4}` ? `${Start_4}/:${Param_4}${Rest_4 extends `${infer Start_5}/{${infer Param_5}}${infer Rest_5}` ? `${Start_5}/:${Param_5}${Rest_5 extends `${infer Start_6}/{${infer Param_6}}${infer Rest_6}` ? `${Start_6}/:${Param_6}${Rest_6 extends `${infer Start_7}/{${infer Param_7}}${infer Rest_7}` ? `${Start_7}/:${Param_7}${Rest_7 extends `${infer Start_8}/{${infer Param_8}}${infer Rest_8}` ? `${Start_8}/:${Param_8}${Rest_8 extends `${infer Start_9}/{${infer Param_9}}${infer Rest_9}` ? `${Start_9}/:${Param_9}${Rest_9 extends `${infer Start_10}/{${infer Param_10}}${infer Rest_10}` ? `${Start_10}/:${Param_10}${any}` : Rest_9}` : Rest_8}` : Rest_7}` : Rest_6}` : Rest_5}` : Rest_4}` : Rest_3}` : Rest_2}` : Rest_1}` : Rest}` : T : never : never;
155
155
  };
156
+ bindDefaultRoutes(): ValueOrPromise<void>;
156
157
  scope: string;
157
158
  identifier: string;
158
159
  get logger(): import("@venizia/ignis-helpers").ILogger;
@@ -1,10 +1,24 @@
1
1
  import type { AESAlgorithmType } from '@venizia/ignis-helpers';
2
2
  import { AES } from '@venizia/ignis-helpers';
3
3
  import type { ValueOrPromise } from '@venizia/ignis-helpers/common';
4
- import type { IJWTIssueClaims, IJWTSignOptions, IJWTTokenPayload, IPayloadFieldCodec, TContext, TGetTokenExpiresFn } from '@venizia/ignis-kernel';
4
+ import type { IJWTClaimsOptions, IJWTIssueClaims, IJWTTokenPayload, IPayloadFieldCodec, TContext, TGetTokenExpiresFn } from '@venizia/ignis-kernel';
5
5
  import { BaseService } from '@venizia/ignis-kernel';
6
6
  import type { Env } from 'hono';
7
- import type { JWTPayload, JWTVerifyResult, SignJWT } from 'jose';
7
+ import type { JWTPayload, JWTVerifyOptions, JWTVerifyResult, SignJWT } from 'jose';
8
+ /** What a token service is configured with for claims: the required `claims`, the `verify` checks, and the removed `sign` it refuses. */
9
+ export interface IClaimsConfigSource {
10
+ claims?: unknown;
11
+ verify?: unknown;
12
+ /** Removed: refused with a message that points to `claims`. */
13
+ sign?: unknown;
14
+ }
15
+ /** What {@link AbstractBearerTokenService.resolveClaimsConfig} answers: the validated claims and the verify options jose receives. */
16
+ export interface IResolvedClaimsConfig {
17
+ claims: IJWTClaimsOptions;
18
+ verify: JWTVerifyOptions & {
19
+ algorithms: string[];
20
+ };
21
+ }
8
22
  /** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */
9
23
  export declare abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {
10
24
  /** Standard JWT fields that are never encrypted. */
@@ -12,14 +26,36 @@ export declare abstract class AbstractBearerTokenService<E extends Env = Env> ex
12
26
  protected aes: AES | null;
13
27
  protected applicationSecret: string | null;
14
28
  protected fieldCodecs: Map<string, IPayloadFieldCodec>;
15
- /** Configured `iss` / `aud`. Authoritative over anything the payload carries. */
16
- protected signOptions: IJWTSignOptions | null;
29
+ /** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */
30
+ protected claimOptions: IJWTClaimsOptions | null;
31
+ /** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */
32
+ protected verifyOptions: JWTVerifyOptions | null;
33
+ /** The keys a `claims` object may hold. */
34
+ static readonly CLAIM_KEYS: ReadonlyArray<string>;
35
+ /**
36
+ * Validates the claims configuration of a token service and answers what the service uses. It throws, naming the
37
+ * key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a
38
+ * non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /
39
+ * `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it
40
+ * no `aud` is stamped and none is checked.
41
+ * `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.
42
+ * The component calls it at boot, and a service calls it when it is built, so neither can start without them.
43
+ */
44
+ static resolveClaimsConfig(opts: {
45
+ scope: string;
46
+ options: IClaimsConfigSource;
47
+ pinnedAlgorithms?: string[];
48
+ }): IResolvedClaimsConfig;
49
+ /** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */
50
+ protected configureClaims(opts: {
51
+ options: IClaimsConfigSource;
52
+ pinnedAlgorithms?: string[];
53
+ }): void;
17
54
  /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */
18
55
  protected configurePayloadEncryption(opts: {
19
56
  aesAlgorithm?: AESAlgorithmType;
20
57
  applicationSecret?: string;
21
58
  fieldCodecs?: IPayloadFieldCodec[];
22
- sign?: IJWTSignOptions;
23
59
  }): void;
24
60
  extractCredentials(context: TContext<E, string>): {
25
61
  type: string;
@@ -29,17 +65,32 @@ export declare abstract class AbstractBearerTokenService<E extends Env = Env> ex
29
65
  type: string;
30
66
  token: string;
31
67
  }): Promise<IJWTTokenPayload>;
68
+ /**
69
+ * A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service
70
+ * assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.
71
+ */
72
+ protected assertNotServiceAssertion(opts: {
73
+ token: string;
74
+ }): Promise<void>;
32
75
  generate(opts: {
33
76
  payload: IJWTTokenPayload;
34
77
  getTokenExpiresFn?: TGetTokenExpiresFn;
35
78
  /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */
36
79
  claims?: IJWTIssueClaims;
37
80
  }): Promise<string>;
81
+ /** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */
38
82
  protected serializeField(opts: {
39
83
  key: string;
40
84
  value: any;
41
85
  }): string;
86
+ /**
87
+ * With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;
88
+ * without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,
89
+ * so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An
90
+ * `undefined` claim is skipped, as JSON drops it.
91
+ */
42
92
  encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>>;
93
+ /** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */
43
94
  protected deserializeField(opts: {
44
95
  key: string;
45
96
  value: string;