@venizia/ignis 0.5.0-1 → 0.5.0-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.
- package/dist/esm/base/applications/boot-steps.d.ts +0 -1
- package/dist/esm/base/applications/boot-steps.js +0 -9
- package/dist/esm/base/applications/boot-steps.js.map +1 -1
- package/dist/esm/components/api-reference/common/constants.d.ts +2 -3
- package/dist/esm/components/api-reference/common/constants.js +2 -5
- package/dist/esm/components/api-reference/common/constants.js.map +1 -1
- package/dist/esm/components/api-reference/component.js +1 -1
- package/dist/esm/components/api-reference/component.js.map +1 -1
- package/dist/esm/components/api-reference/ui/factory.js +1 -1
- package/dist/esm/components/api-reference/ui/factory.js.map +1 -1
- package/dist/esm/components/auth/authenticate/component.js +1 -1
- package/dist/esm/components/auth/authenticate/component.js.map +1 -1
- package/dist/esm/components/auth/authorize/enforcers/casbin.enforcer.js +1 -1
- package/dist/esm/components/auth/authorize/enforcers/casbin.enforcer.js.map +1 -1
- package/dist/esm/components/socket-io/common/keys.d.ts +2 -2
- package/dist/esm/components/socket-io/common/keys.js.map +1 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +0 -1
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js +6 -10
- package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
- package/dist/esm/components/websocket/common/keys.d.ts +2 -2
- package/dist/esm/components/websocket/common/keys.js.map +1 -1
- package/dist/esm/testing/assert-application-boots.js +1 -1
- package/dist/esm/testing/assert-application-boots.js.map +1 -1
- package/dist/presets/app/preset.json +5 -5
- package/dist/presets/lib/preset.json +4 -4
- package/dist/presets/shared/preset.json +2 -2
- package/package.json +9 -9
|
@@ -7,7 +7,6 @@ export declare class ServerBootSteps extends BootSteps {
|
|
|
7
7
|
static readonly HYDRATE_SECRETS = "hydrateSecrets";
|
|
8
8
|
static readonly WIRE_SECRET_ROTATABLES = "wireSecretRotatables";
|
|
9
9
|
static readonly VALIDATE_SCOPE_FILTER_SUPPORT = "validateScopeFilterSupport";
|
|
10
|
-
static readonly SCHEME_SET: Set<string>;
|
|
11
10
|
}
|
|
12
11
|
/** Union of the step names in `ServerBootSteps`, accepted by `BootSequence.insertAfter` and `skipSteps`. */
|
|
13
12
|
export type TServerBootStep = TConstValue<typeof ServerBootSteps>;
|
|
@@ -6,14 +6,5 @@ export class ServerBootSteps extends BootSteps {
|
|
|
6
6
|
static { this.HYDRATE_SECRETS = 'hydrateSecrets'; }
|
|
7
7
|
static { this.WIRE_SECRET_ROTATABLES = 'wireSecretRotatables'; }
|
|
8
8
|
static { this.VALIDATE_SCOPE_FILTER_SUPPORT = 'validateScopeFilterSupport'; }
|
|
9
|
-
// The kernel's names plus these; `isValid` is inherited and reads this set through `this`.
|
|
10
|
-
static { this.SCHEME_SET = new Set([
|
|
11
|
-
...BootSteps.SCHEME_SET,
|
|
12
|
-
this.PRINT_START_UP_INFO,
|
|
13
|
-
this.VALIDATE_ENVS,
|
|
14
|
-
this.HYDRATE_SECRETS,
|
|
15
|
-
this.WIRE_SECRET_ROTATABLES,
|
|
16
|
-
this.VALIDATE_SCOPE_FILTER_SUPPORT,
|
|
17
|
-
]); }
|
|
18
9
|
}
|
|
19
10
|
//# sourceMappingURL=boot-steps.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boot-steps.js","sourceRoot":"","sources":["../../../../src/base/applications/boot-steps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGlD,mKAAmK;AACnK,MAAM,OAAO,eAAgB,SAAQ,SAAS;aAC5B,wBAAmB,GAAG,kBAAkB,CAAC;aACzC,kBAAa,GAAG,cAAc,CAAC;aAC/B,oBAAe,GAAG,gBAAgB,CAAC;aACnC,2BAAsB,GAAG,sBAAsB,CAAC;aAChD,kCAA6B,GAAG,4BAA4B,CAAC
|
|
1
|
+
{"version":3,"file":"boot-steps.js","sourceRoot":"","sources":["../../../../src/base/applications/boot-steps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGlD,mKAAmK;AACnK,MAAM,OAAO,eAAgB,SAAQ,SAAS;aAC5B,wBAAmB,GAAG,kBAAkB,CAAC;aACzC,kBAAa,GAAG,cAAc,CAAC;aAC/B,oBAAe,GAAG,gBAAgB,CAAC;aACnC,2BAAsB,GAAG,sBAAsB,CAAC;aAChD,kCAA6B,GAAG,4BAA4B,CAAC","sourcesContent":["import { BootSteps } from '@venizia/ignis-kernel';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** The kernel's step names plus the ones only a server runs - the full vocabulary `BaseApplication.getBootSequence()` publishes for `BootSequence.insertAfter`. */\nexport class ServerBootSteps extends BootSteps {\n static readonly PRINT_START_UP_INFO = 'printStartUpInfo';\n static readonly VALIDATE_ENVS = 'validateEnvs';\n static readonly HYDRATE_SECRETS = 'hydrateSecrets';\n static readonly WIRE_SECRET_ROTATABLES = 'wireSecretRotatables';\n static readonly VALIDATE_SCOPE_FILTER_SUPPORT = 'validateScopeFilterSupport';\n}\n\n/** Union of the step names in `ServerBootSteps`, accepted by `BootSequence.insertAfter` and `skipSteps`. */\nexport type TServerBootStep = TConstValue<typeof ServerBootSteps>;\n"]}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
+
import { ConstClass } from '@venizia/ignis-helpers/common';
|
|
1
2
|
/** The document UI implementations the API reference can render. `isValid` checks a string against them. */
|
|
2
|
-
export declare class DocumentUITypes {
|
|
3
|
+
export declare class DocumentUITypes extends ConstClass {
|
|
3
4
|
static readonly SWAGGER = "swagger";
|
|
4
5
|
static readonly SCALAR = "scalar";
|
|
5
|
-
static readonly SCHEME_SET: Set<string>;
|
|
6
|
-
static isValid(value: string): boolean;
|
|
7
6
|
}
|
|
8
7
|
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -1,10 +1,7 @@
|
|
|
1
|
+
import { ConstClass } from '@venizia/ignis-helpers/common';
|
|
1
2
|
/** The document UI implementations the API reference can render. `isValid` checks a string against them. */
|
|
2
|
-
export class DocumentUITypes {
|
|
3
|
+
export class DocumentUITypes extends ConstClass {
|
|
3
4
|
static { this.SWAGGER = 'swagger'; }
|
|
4
5
|
static { this.SCALAR = 'scalar'; }
|
|
5
|
-
static { this.SCHEME_SET = new Set([this.SWAGGER, this.SCALAR]); }
|
|
6
|
-
static isValid(value) {
|
|
7
|
-
return this.SCHEME_SET.has(value);
|
|
8
|
-
}
|
|
9
6
|
}
|
|
10
7
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/api-reference/common/constants.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/components/api-reference/common/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,4GAA4G;AAC5G,MAAM,OAAO,eAAgB,SAAQ,UAAU;aAC7B,YAAO,GAAG,SAAS,CAAC;aACpB,WAAM,GAAG,QAAQ,CAAC","sourcesContent":["import { ConstClass } from '@venizia/ignis-helpers/common';\n\n/** The document UI implementations the API reference can render. `isValid` checks a string against them. */\nexport class DocumentUITypes extends ConstClass {\n static readonly SWAGGER = 'swagger';\n static readonly SCALAR = 'scalar';\n}\n"]}
|
|
@@ -116,7 +116,7 @@ let ApiReferenceComponent = ApiReferenceComponent_1 = class ApiReferenceComponen
|
|
|
116
116
|
if (!uiProviderFactory.isBound(uiType)) {
|
|
117
117
|
if (!DocumentUITypes.isValid(uiType)) {
|
|
118
118
|
throw getError({
|
|
119
|
-
message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${
|
|
119
|
+
message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${DocumentUITypes.values()}`,
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
122
|
uiProviderFactory.register({ type: uiType });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../src/components/api-reference/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAA6B,MAAM,UAAU,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEzC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAExC,MAAM,6BAA6B,GAAyB;IAC1D,WAAW,EAAE;QACX,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;QACtB,GAAG,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE;QAC9B,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC1C;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,uBAAuB;QAChC,IAAI,EAAE;YACJ,KAAK,EAAE,mBAAmB;YAC1B,OAAO,EAAE,OAAO;YAChB,WAAW,EAAE,oCAAoC;SAClD;KACF;CACF,CAAC;AAEF,gGAAgG;AAChG,MAAM,YAAY,GAAG,CAAC,QAAmC,EAAU,EAAE;IACnE,MAAM,MAAM,GAAG,QAAQ;SACpB,MAAM,CAAC,CAAC,OAAO,EAAqB,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;SACxD,IAAI,CAAC,GAAG,CAAC;SACT,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,EAA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EAAE,MAAM;YACZ,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC;QAEH,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAC1C,iBAAiB,EACjB,cAAc,CAAC,gBAAgB,EAC/B,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAChE,CAAC;QAEF,MAAM,eAAe,GAAG,YAAY,EAAE,eAAe,IAAI,EAAE,CAAC;QAC5D,MAAM,sBAAsB,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QAE/D,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,sBAAsB,EAAE,CAAC;YACpD,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAChF,CAAC;IACH,CAAC;CACF,CAAA;AApHY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAoHjC","sourcesContent":["import { type BaseApplication } from '@/base/applications';\nimport { inject } from '@/base/metadata';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseComponent, Binding, CoreBindings } from '@venizia/ignis-kernel';\nimport type { Context, Next } from 'hono';\nimport { Authentication } from '../auth';\nimport { ServiceAssertion } from '@venizia/ignis-kernel';\nimport { ApiReferenceBindingKeys, DocumentUITypes, type IApiReferenceOptions } from './common';\nimport { UIProviderFactory } from './ui';\n\nconst DEFAULT_OPENAPI_VERSION = '3.0.0';\n\nconst DEFAULT_API_REFERENCE_OPTIONS: IApiReferenceOptions = {\n restOptions: {\n base: { path: '/doc' },\n doc: { path: '/openapi.json' },\n ui: { path: '/explorer', type: 'scalar' },\n },\n explorer: {\n openapi: DEFAULT_OPENAPI_VERSION,\n info: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'API documentation for your service',\n },\n },\n};\n\n/** Joins rest path segments into a single absolute path (no empty or duplicated separators). */\nconst joinRestPath = (segments: Array<string | undefined>): string => {\n const joined = segments\n .filter((segment): segment is string => Boolean(segment))\n .join('/')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '');\n\n return joined.startsWith('/') ? joined : `/${joined}`;\n};\n\n/**\n * Serves the OpenAPI document and an interactive UI for it. Paths and UI type come from `IApiReferenceOptions` bound at `ApiReferenceBindingKeys.API_REFERENCE_OPTIONS`; `info` is always taken from the application info.\n *\n * @example\n * ```typescript\n * import { ApiReferenceComponent, BaseApplication } from '@venizia/ignis';\n *\n * abstract class App extends BaseApplication {\n * preConfigure(): void {\n * this.component(ApiReferenceComponent);\n * }\n * }\n * ```\n */\nexport class ApiReferenceComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: ApiReferenceComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [ApiReferenceBindingKeys.API_REFERENCE_OPTIONS]: Binding.bind({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n }).toValue(DEFAULT_API_REFERENCE_OPTIONS),\n },\n });\n }\n\n override async binding() {\n const boundOptions = this.application.get({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n isOptional: true,\n });\n\n const defaultRestOptions = DEFAULT_API_REFERENCE_OPTIONS.restOptions!;\n const restOptions = {\n base: { ...defaultRestOptions.base, ...boundOptions?.restOptions?.base },\n doc: { ...defaultRestOptions.doc, ...boundOptions?.restOptions?.doc },\n ui: { ...defaultRestOptions.ui, ...boundOptions?.restOptions?.ui },\n };\n\n // A fresh explorer object per application: mutating the bound one (or the module default) leaks this application's info/servers into every later application in the process.\n const explorer: NonNullable<IApiReferenceOptions['explorer']> = {\n ...DEFAULT_API_REFERENCE_OPTIONS.explorer,\n ...boundOptions?.explorer,\n };\n\n const rootRouter = this.application.getRootRouter();\n const configs = this.application.getProjectConfigs();\n\n const appInfo = await this.application.getAppInfo();\n const info = {\n title: appInfo.name,\n version: appInfo.version,\n description: appInfo.description,\n contact: appInfo.author,\n };\n\n if (!explorer.servers?.length) {\n explorer.servers = [\n {\n url: ['http://', this.application.getServerAddress(), configs.path.base ?? ''].join(''),\n description: 'Local Application Server URL',\n },\n ];\n }\n\n const docPath = joinRestPath([restOptions.base.path, restOptions.doc.path]);\n const uiPath = joinRestPath([restOptions.base.path, restOptions.ui.path]);\n\n rootRouter.doc(docPath, {\n ...explorer,\n openapi: explorer.openapi ?? DEFAULT_OPENAPI_VERSION,\n info,\n });\n\n const uiType = restOptions.ui.type ?? DocumentUITypes.SWAGGER;\n const uiProviderFactory = UIProviderFactory.getInstance();\n\n // A custom provider registered on the factory is honoured; only unknown types are rejected.\n if (!uiProviderFactory.isBound(uiType)) {\n if (!DocumentUITypes.isValid(uiType)) {\n throw getError({\n message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${[...DocumentUITypes.SCHEME_SET]}`,\n });\n }\n\n uiProviderFactory.register({ type: uiType });\n }\n\n const docUrl = joinRestPath([configs.path.base, docPath]);\n const uiProvider = uiProviderFactory.getProvider({ type: uiType });\n\n rootRouter.get(uiPath, async (context: Context, next: Next) => {\n return uiProvider.render(\n context,\n {\n title: appInfo.name,\n url: docUrl,\n ...(boundOptions?.uiConfig ?? {}),\n },\n next,\n );\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_JWT, {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_BASIC, {\n type: 'http',\n scheme: 'basic',\n });\n\n rootRouter.openAPIRegistry.registerComponent(\n 'securitySchemes',\n Authentication.STRATEGY_SERVICE,\n { type: 'apiKey', in: 'header', name: ServiceAssertion.HEADER },\n );\n\n const securitySchemes = boundOptions?.securitySchemes ?? {};\n const securitySchemesEntries = Object.entries(securitySchemes);\n\n for (const [name, scheme] of securitySchemesEntries) {\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', name, scheme);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../src/components/api-reference/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAA6B,MAAM,UAAU,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAEzC,MAAM,uBAAuB,GAAG,OAAO,CAAC;AAExC,MAAM,6BAA6B,GAAyB;IAC1D,WAAW,EAAE;QACX,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;QACtB,GAAG,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE;QAC9B,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC1C;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,uBAAuB;QAChC,IAAI,EAAE;YACJ,KAAK,EAAE,mBAAmB;YAC1B,OAAO,EAAE,OAAO;YAChB,WAAW,EAAE,oCAAoC;SAClD;KACF;CACF,CAAC;AAEF,gGAAgG;AAChG,MAAM,YAAY,GAAG,CAAC,QAAmC,EAAU,EAAE;IACnE,MAAM,MAAM,GAAG,QAAQ;SACpB,MAAM,CAAC,CAAC,OAAO,EAAqB,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;SACxD,IAAI,CAAC,GAAG,CAAC;SACT,OAAO,CAAC,MAAM,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,cAAc,CAAC,cAAc,EAAE;YAC7F,IAAI,EAAE,MAAM;YACZ,MAAM,EAAE,OAAO;SAChB,CAAC,CAAC;QAEH,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAC1C,iBAAiB,EACjB,cAAc,CAAC,gBAAgB,EAC/B,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAChE,CAAC;QAEF,MAAM,eAAe,GAAG,YAAY,EAAE,eAAe,IAAI,EAAE,CAAC;QAC5D,MAAM,sBAAsB,GAAG,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QAE/D,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,sBAAsB,EAAE,CAAC;YACpD,UAAU,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QAChF,CAAC;IACH,CAAC;CACF,CAAA;AApHY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAoHjC","sourcesContent":["import { type BaseApplication } from '@/base/applications';\nimport { inject } from '@/base/metadata';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BaseComponent, Binding, CoreBindings } from '@venizia/ignis-kernel';\nimport type { Context, Next } from 'hono';\nimport { Authentication } from '../auth';\nimport { ServiceAssertion } from '@venizia/ignis-kernel';\nimport { ApiReferenceBindingKeys, DocumentUITypes, type IApiReferenceOptions } from './common';\nimport { UIProviderFactory } from './ui';\n\nconst DEFAULT_OPENAPI_VERSION = '3.0.0';\n\nconst DEFAULT_API_REFERENCE_OPTIONS: IApiReferenceOptions = {\n restOptions: {\n base: { path: '/doc' },\n doc: { path: '/openapi.json' },\n ui: { path: '/explorer', type: 'scalar' },\n },\n explorer: {\n openapi: DEFAULT_OPENAPI_VERSION,\n info: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'API documentation for your service',\n },\n },\n};\n\n/** Joins rest path segments into a single absolute path (no empty or duplicated separators). */\nconst joinRestPath = (segments: Array<string | undefined>): string => {\n const joined = segments\n .filter((segment): segment is string => Boolean(segment))\n .join('/')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '');\n\n return joined.startsWith('/') ? joined : `/${joined}`;\n};\n\n/**\n * Serves the OpenAPI document and an interactive UI for it. Paths and UI type come from `IApiReferenceOptions` bound at `ApiReferenceBindingKeys.API_REFERENCE_OPTIONS`; `info` is always taken from the application info.\n *\n * @example\n * ```typescript\n * import { ApiReferenceComponent, BaseApplication } from '@venizia/ignis';\n *\n * abstract class App extends BaseApplication {\n * preConfigure(): void {\n * this.component(ApiReferenceComponent);\n * }\n * }\n * ```\n */\nexport class ApiReferenceComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: ApiReferenceComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [ApiReferenceBindingKeys.API_REFERENCE_OPTIONS]: Binding.bind({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n }).toValue(DEFAULT_API_REFERENCE_OPTIONS),\n },\n });\n }\n\n override async binding() {\n const boundOptions = this.application.get({\n key: ApiReferenceBindingKeys.API_REFERENCE_OPTIONS,\n isOptional: true,\n });\n\n const defaultRestOptions = DEFAULT_API_REFERENCE_OPTIONS.restOptions!;\n const restOptions = {\n base: { ...defaultRestOptions.base, ...boundOptions?.restOptions?.base },\n doc: { ...defaultRestOptions.doc, ...boundOptions?.restOptions?.doc },\n ui: { ...defaultRestOptions.ui, ...boundOptions?.restOptions?.ui },\n };\n\n // A fresh explorer object per application: mutating the bound one (or the module default) leaks this application's info/servers into every later application in the process.\n const explorer: NonNullable<IApiReferenceOptions['explorer']> = {\n ...DEFAULT_API_REFERENCE_OPTIONS.explorer,\n ...boundOptions?.explorer,\n };\n\n const rootRouter = this.application.getRootRouter();\n const configs = this.application.getProjectConfigs();\n\n const appInfo = await this.application.getAppInfo();\n const info = {\n title: appInfo.name,\n version: appInfo.version,\n description: appInfo.description,\n contact: appInfo.author,\n };\n\n if (!explorer.servers?.length) {\n explorer.servers = [\n {\n url: ['http://', this.application.getServerAddress(), configs.path.base ?? ''].join(''),\n description: 'Local Application Server URL',\n },\n ];\n }\n\n const docPath = joinRestPath([restOptions.base.path, restOptions.doc.path]);\n const uiPath = joinRestPath([restOptions.base.path, restOptions.ui.path]);\n\n rootRouter.doc(docPath, {\n ...explorer,\n openapi: explorer.openapi ?? DEFAULT_OPENAPI_VERSION,\n info,\n });\n\n const uiType = restOptions.ui.type ?? DocumentUITypes.SWAGGER;\n const uiProviderFactory = UIProviderFactory.getInstance();\n\n // A custom provider registered on the factory is honoured; only unknown types are rejected.\n if (!uiProviderFactory.isBound(uiType)) {\n if (!DocumentUITypes.isValid(uiType)) {\n throw getError({\n message: `[binding] Invalid document UI Type | uiType: ${uiType} | valids: ${DocumentUITypes.values()}`,\n });\n }\n\n uiProviderFactory.register({ type: uiType });\n }\n\n const docUrl = joinRestPath([configs.path.base, docPath]);\n const uiProvider = uiProviderFactory.getProvider({ type: uiType });\n\n rootRouter.get(uiPath, async (context: Context, next: Next) => {\n return uiProvider.render(\n context,\n {\n title: appInfo.name,\n url: docUrl,\n ...(boundOptions?.uiConfig ?? {}),\n },\n next,\n );\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_JWT, {\n type: 'http',\n scheme: 'bearer',\n bearerFormat: 'JWT',\n });\n\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', Authentication.STRATEGY_BASIC, {\n type: 'http',\n scheme: 'basic',\n });\n\n rootRouter.openAPIRegistry.registerComponent(\n 'securitySchemes',\n Authentication.STRATEGY_SERVICE,\n { type: 'apiKey', in: 'header', name: ServiceAssertion.HEADER },\n );\n\n const securitySchemes = boundOptions?.securitySchemes ?? {};\n const securitySchemesEntries = Object.entries(securitySchemes);\n\n for (const [name, scheme] of securitySchemesEntries) {\n rootRouter.openAPIRegistry.registerComponent('securitySchemes', name, scheme);\n }\n }\n}\n"]}
|
|
@@ -39,7 +39,7 @@ export class UIProviderFactory extends MemoryStorageHelper {
|
|
|
39
39
|
}
|
|
40
40
|
default: {
|
|
41
41
|
throw getError({
|
|
42
|
-
message: `[register] Invalid document UI Type | uiType: ${opts.type} | valids: ${
|
|
42
|
+
message: `[register] Invalid document UI Type | uiType: ${opts.type} | valids: ${DocumentUITypes.values()}`,
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/components/api-reference/ui/factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C,qLAAqL;AACrL,MAAM,OAAO,iBAAkB,SAAQ,mBAErC;IAGA,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,iBAAiB,CAAC,QAAQ,EAAE,CAAC;YAChC,iBAAiB,CAAC,QAAQ,GAAG,IAAI,iBAAiB,EAAE,CAAC;QACvD,CAAC;QAED,OAAO,iBAAiB,CAAC,QAAQ,CAAC;IACpC,CAAC;IAED,gFAAgF;IAChF,WAAW,CAAC,EAAE,IAAI,EAAsB;QACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAEhC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,gEAAgE,IAAI,iBAAiB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C,CAAC;gBACR,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,iDAAiD,IAAI,CAAC,IAAI,cAAc,eAAe,CAAC,MAAM,EAAE,EAAE;iBAC5G,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;IAED,sBAAsB;QACpB,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC;IACrB,CAAC;CACF","sourcesContent":["import type { IGetProviderParams, IUIProvider } from '../common';\nimport { DocumentUITypes } from '../common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { MemoryStorageHelper } from '@venizia/ignis-helpers';\nimport { ScalarUIProvider } from './scalar';\nimport { SwaggerUIProvider } from './swagger';\n\n/** Process-wide registry of UI providers by type; obtain it with `getInstance()`. `register` creates the built-in `swagger` and `scalar` providers and throws for any other type. */\nexport class UIProviderFactory extends MemoryStorageHelper<{\n [key: string | symbol]: IUIProvider;\n}> {\n private static instance: UIProviderFactory;\n\n static getInstance() {\n if (!UIProviderFactory.instance) {\n UIProviderFactory.instance = new UIProviderFactory();\n }\n\n return UIProviderFactory.instance;\n }\n\n // One lookup, not a `isBound` probe followed by a second `get` of the same key.\n getProvider({ type }: IGetProviderParams): IUIProvider {\n const provider = this.get(type);\n\n if (!provider) {\n throw getError({\n message: `[UIProviderFactory][getProvider] Unknown UI Provider | type: ${type} | available: ${this.keys().join(', ')}`,\n });\n }\n\n return provider;\n }\n\n register(opts: { type: string }): void {\n if (this.isBound(opts.type)) {\n this.logger\n .for(this.register.name)\n .warn('Skip registering BOUNDED Document UI | type: %s', opts.type);\n\n return;\n }\n\n switch (opts.type) {\n case DocumentUITypes.SWAGGER: {\n this.set(opts.type, new SwaggerUIProvider());\n\n return;\n }\n case DocumentUITypes.SCALAR: {\n this.set(opts.type, new ScalarUIProvider());\n\n return;\n }\n default: {\n throw getError({\n message: `[register] Invalid document UI Type | uiType: ${opts.type} | valids: ${DocumentUITypes.values()}`,\n });\n }\n }\n }\n\n getRegisteredProviders() {\n return this.keys();\n }\n}\n"]}
|
|
@@ -143,7 +143,7 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
|
|
|
143
143
|
}
|
|
144
144
|
if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {
|
|
145
145
|
throw getError({
|
|
146
|
-
message: `[defineJWKSAuth] keys.format is required and must be one of: ${
|
|
146
|
+
message: `[defineJWKSAuth] keys.format is required and must be one of: ${JWKSKeyFormats.values().join(', ')}`,
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
149
|
if (!issuerOpts.kid) {
|
|
@@ -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,EAGZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAGjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EACL,0BAA0B,EAC1B,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B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AAC,IAAI,CAAC,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;YAE/E,OAAO;QACT,CAAC;QAED,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,0EAA0E;aACpF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,cAAc,GAAG,qBAAqB,CAAC,KAAK,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAC/E,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AAzVY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAyVjC","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 IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\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({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n const standard: string = jwtOptions.standard;\n\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application.bind({ key: AuthenticateBindingKeys.JWS_OPTIONS }).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({ key: AuthenticateBindingKeys.JWKS_ISSUER_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 trusted: verifierOpts.jwks?.trusted,\n });\n\n this.application\n .bind({ key: AuthenticateBindingKeys.JWKS_VERIFIER_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 an origin listed in jwks.trusted. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveTrustedOrigins({\n scope: 'defineServiceAuth',\n trusted: serviceOptions.jwks?.trusted,\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 trusted: serviceOptions.jwks?.trusted,\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.bind({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH }).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.bind({ key: AuthenticateBindingKeys.BASIC_OPTIONS }).toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.build(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAA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AAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CAyVjC","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 IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\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({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n const standard: string = jwtOptions.standard;\n\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application.bind({ key: AuthenticateBindingKeys.JWS_OPTIONS }).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.values().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({ key: AuthenticateBindingKeys.JWKS_ISSUER_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 trusted: verifierOpts.jwks?.trusted,\n });\n\n this.application\n .bind({ key: AuthenticateBindingKeys.JWKS_VERIFIER_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 an origin listed in jwks.trusted. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveTrustedOrigins({\n scope: 'defineServiceAuth',\n trusted: serviceOptions.jwks?.trusted,\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 trusted: serviceOptions.jwks?.trusted,\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.bind({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH }).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.bind({ key: AuthenticateBindingKeys.BASIC_OPTIONS }).toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.build(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
|
|
@@ -247,7 +247,7 @@ let CasbinAuthorizationEnforcer = CasbinAuthorizationEnforcer_1 = class CasbinAu
|
|
|
247
247
|
}
|
|
248
248
|
default: {
|
|
249
249
|
throw getError({
|
|
250
|
-
message: `[resolveDomainMatchingFn] Unsupported func: ${opts.name} | Valids: [${
|
|
250
|
+
message: `[resolveDomainMatchingFn] Unsupported func: ${opts.name} | Valids: [${CasbinDomainMatchingFunctions.values().join(', ')}]`,
|
|
251
251
|
});
|
|
252
252
|
}
|
|
253
253
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"casbin.enforcer.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/enforcers/casbin.enforcer.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAQnF,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,EAC1B,2BAA2B,EAC3B,oBAAoB,EACpB,6BAA6B,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,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAhbY,2BAA2B;IAoBnC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,oBAAoB,CAAC,eAAe,CAAC,0BAA0B,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;;GApBhF,2BAA2B,CAgbvC","sourcesContent":["import { type TContext } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { BaseHelper, BasePoolHelper, getError } from '@venizia/ignis-helpers/core';\nimport { type TNullable } from '@venizia/ignis-helpers/common';\nimport type {\n Enforcer as CasbinEnforcerType,\n Helper as CasbinHelperType,\n RoleManager as CasbinRoleManagerType,\n} from 'casbin';\nimport { type Env } from 'hono';\nimport { AuthorizationPermissionBuilder } from '@venizia/ignis-kernel';\nimport {\n AuthorizationDecisions,\n AuthorizationDomainScopes,\n AuthorizationEnforcerTypes,\n AuthorizationPolicyVariants,\n AuthorizeBindingKeys,\n CasbinDomainMatchingFunctions,\n CasbinEnforcerModelDrivers,\n CasbinRuleVariants,\n type IAuthorizationEnforcer,\n type IAuthorizationUser,\n type ICasbinEnforcerOptions,\n type ICasbinRules,\n type IAuthorizationRequest,\n type TAuthorizationDecision,\n type TCasbinDomainMatchingFunction,\n} from '@venizia/ignis-kernel';\nimport { DomainHierarchyRoleManager } from '../role-managers/domain-hierarchy';\nimport { CasbinModule } from './casbin-module';\nimport { MembershipRoleManager } from '../role-managers/membership';\nimport { ResourceRoleManager } from '../role-managers/resource';\nimport { PolicyLineCodec } from './policy-line-codec';\nimport { UserPolicyLineCache } from './user-policy-line-cache';\n\n/** Payload shape for the scoped/custom path, matching defaultScopedPayloadFn(). */\ntype TNormalizePayloadFn<E extends Env, TAction, TResource> = (opts: {\n user: IAuthorizationUser;\n action: TAction;\n resource: TResource;\n context: TContext<E, string>;\n}) => { subject: string; resource: string; action: string; domain?: string };\n\n/** `addDomainHierarchy` lives on casbin's `DefaultRoleManager`, not on the `RoleManager` interface or the `Enforcer` facade - feature-detect it on whatever `getNamedRoleManager` returns. */\ninterface ICasbinRoleManagerWithDomainHierarchy {\n addDomainHierarchy?(rm: CasbinRoleManagerType): Promise<void>;\n}\n\n// Wraps casbin (optional peer dep). Each request borrows its own pooled enforcer; any error during use destroys it (fail-closed). Pooled enforcers carry no adapter - only extractUserLines uses one.\n\n/** Authorization enforcer backed by casbin (an optional peer dependency); `configure()` throws when `options.model` is missing. */\nexport class CasbinAuthorizationEnforcer<\n E extends Env = Env,\n TAction extends string = string,\n TResource extends string = string,\n>\n extends BaseHelper\n implements IAuthorizationEnforcer<E, TAction, TResource, ICasbinRules>\n{\n name = CasbinAuthorizationEnforcer.name;\n private readonly MIN_EXPIRES_IN = 10_000;\n\n private pool: TNullable<BasePoolHelper<CasbinEnforcerType>> = null;\n private helper: TNullable<typeof CasbinHelperType> = null;\n // Lazily created on first cache use (see requireRedisCache) - one instance for the enforcer's lifetime so its single-flight de-dup map actually dedupes.\n private userPolicyLineCache: TNullable<UserPolicyLineCache> = null;\n\n // Memoized in configure() (options are fixed after) to avoid rebuilding this closure on every evaluate() (hot path).\n private resolvedPayloadFn: TNullable<TNormalizePayloadFn<E, TAction, TResource>> = null;\n\n constructor(\n @inject({ key: AuthorizeBindingKeys.enforcerOptions(AuthorizationEnforcerTypes.CASBIN) })\n private options: ICasbinEnforcerOptions<E, TAction, TResource>,\n ) {\n super({ scope: CasbinAuthorizationEnforcer.name });\n }\n\n // Lifecycle\n\n async configure(): Promise<void> {\n const casbin = await CasbinModule.load();\n\n if (!this.options.model) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] options.model is required.',\n });\n }\n\n this.helper = casbin.Helper;\n\n this.resolvedPayloadFn = this.options.normalizePayloadFn ?? this.defaultScopedPayloadFn();\n\n const { cached } = this.options;\n\n if (cached.use) {\n this.validateExpiresIn({ expiresIn: cached.options.expiresIn });\n }\n\n this.pool = new BasePoolHelper<CasbinEnforcerType>({\n scope: `${CasbinAuthorizationEnforcer.name}.Pool`,\n size: this.options.poolSize ?? 16,\n acquireTimeoutMs: this.options.poolAcquireTimeoutMs ?? 5000,\n create: async () => {\n const model = this.resolveModel({ casbin, model: this.options.model });\n\n const enforcer = await casbin.newEnforcer(model);\n await this.registerMatchers({ enforcer, casbin });\n this.assertMatcherCompilesSync({ enforcer });\n\n return enforcer;\n },\n });\n await this.pool.warmup();\n\n this.logger\n .for(this.configure.name)\n .info(\n 'Casbin enforcer pool ready (size: %s, cached: %s)',\n this.options.poolSize ?? 16,\n cached.use ? cached.driver : 'none',\n );\n }\n\n destroy(): void {\n this.pool?.destroy().catch((error) => {\n this.logger.for(this.destroy.name).warn('Pool destroy failed: %s', error);\n });\n }\n\n /** casbin compiles the matcher lazily (first enforce, not newEnforcer/buildRoleLinks); this dummy enforceSync forces the compile at warmup so syntax / unregistered-function / arity errors fail boot. */\n protected assertMatcherCompilesSync(opts: { enforcer: CasbinEnforcerType }) {\n try {\n if (this.options.isScoped || this.options.normalizePayloadFn) {\n opts.enforcer.enforceSync('::warmup', '::warmup', '::warmup', '::warmup');\n\n return;\n }\n\n opts.enforcer.enforceSync('::warmup', '::warmup', '::warmup');\n } catch (error) {\n throw getError({\n message: `[CasbinAuthorizationEnforcer] Matcher smoke test failed at warmup - the model matcher did not compile (check matcher syntax, that every referenced function is registered, and the request arity). ${String(error)}`,\n });\n }\n }\n\n // IAuthorizationEnforcer - public API\n\n async buildRules(opts: {\n user: IAuthorizationUser;\n context: TContext<E, string>;\n }): Promise<ICasbinRules> {\n const { user } = opts;\n const cached = this.options.cached;\n\n let lines: string[];\n\n if (cached.use) {\n const fetched = await this.requireRedisCache().fetch({ user });\n lines = fetched;\n } else {\n const extracted = await this.extractUserLines({ user });\n lines = extracted;\n }\n\n return { user, lines };\n }\n\n async evaluate(opts: {\n rules: ICasbinRules;\n request: IAuthorizationRequest<TAction, TResource>;\n context: TContext<E, string>;\n }): Promise<TAuthorizationDecision> {\n if (!this.pool) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] Not configured. Call configure() first.',\n });\n }\n\n if (!opts.request?.action || !opts.request?.resource) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] request.action and request.resource are required.',\n });\n }\n\n const { rules, request, context } = opts;\n const { user, lines } = rules;\n\n return this.pool.use({\n execution: async (enforcer) => {\n await this.loadPolicyLinesIntoModel({ enforcer, lines });\n\n const normalizePayloadFn = this.resolvedPayloadFn;\n\n if (!normalizePayloadFn) {\n const subject = `${user.principalType}_${user.userId}`;\n const isAllowed = this.enforceWithExplain({\n enforcer,\n vals: [subject, String(request.resource), String(request.action)],\n });\n\n return isAllowed ? AuthorizationDecisions.ALLOW : AuthorizationDecisions.DENY;\n }\n\n const normalized = normalizePayloadFn({\n user,\n action: request.action,\n resource: request.resource,\n context,\n });\n\n // Scoped model is 4-token (sub, dom, obj, act): a request with no resolvable domain still needs one - default SYSTEM_WIDE, never the 3-arg path, which misaligns args and silently misjudges.\n const domain =\n normalized.domain ??\n request.domain ??\n (this.options.isScoped ? AuthorizationDomainScopes.SYSTEM_WIDE : undefined);\n\n const vals = domain\n ? [normalized.subject, domain, normalized.resource, normalized.action]\n : [normalized.subject, normalized.resource, normalized.action];\n const isAllowed = this.enforceWithExplain({ enforcer, vals });\n\n return isAllowed ? AuthorizationDecisions.ALLOW : AuthorizationDecisions.DENY;\n },\n });\n }\n\n /** On DENY, logs the deciding policy rule; matchedPolicy is `[]` when nothing matched (default-deny). */\n protected enforceWithExplain(opts: { enforcer: CasbinEnforcerType; vals: string[] }): boolean {\n const [isAllowed, matchedPolicy] = opts.enforcer.enforceExSync(...opts.vals);\n\n if (!isAllowed) {\n this.logger\n .for(this.evaluate.name)\n .info(\n 'DENY | request: [%s] | matchedPolicy: %s',\n opts.vals.join(', '),\n matchedPolicy.length ? matchedPolicy.join(', ') : '<none - default-deny>',\n );\n }\n\n return isAllowed;\n }\n\n // Cache management - optional IAuthorizationEnforcer members (on-demand)\n async invalidateUserCache(opts: {\n user: IAuthorizationUser;\n }): Promise<{ invalidatedKeys: number }> {\n const { cacheKey, invalidatedKeys } = await this.requireRedisCache().invalidate({\n user: opts.user,\n });\n\n this.logger\n .for(this.invalidateUserCache.name)\n .info(\n 'Invalidated authz cache | user: %s | key: %s | deleted: %s',\n opts.user.userId,\n cacheKey,\n invalidatedKeys,\n );\n\n return { invalidatedKeys };\n }\n\n async rebuildUserCache(opts: {\n user: IAuthorizationUser;\n }): Promise<{ cacheKey: string; lineCount: number }> {\n // Extraction runs on an isolated throwaway enforcer (not a serving model), so a concurrent request cannot make us cache another user's policies under this key.\n const { cacheKey, lines } = await this.requireRedisCache().rebuild({ user: opts.user });\n\n this.logger\n .for(this.rebuildUserCache.name)\n .info(\n 'Rebuilt authz cache | user: %s | key: %s | lines: %s',\n opts.user.userId,\n cacheKey,\n lines.length,\n );\n\n return { cacheKey, lineCount: lines.length };\n }\n\n /** Narrow `options.cached` to the redis variant and lazily create the per-user line cache - memoized so its single-flight de-dup map is shared across calls rather than reset on every access. */\n protected requireRedisCache(): UserPolicyLineCache {\n const { cached } = this.options;\n\n if (!cached.use) {\n throw getError({\n message:\n '[CasbinAuthorizationEnforcer] Cache management requires the redis cache driver, but caching is disabled.',\n });\n }\n\n return (this.userPolicyLineCache ??= new UserPolicyLineCache({\n cached,\n loadLines: (opts) => this.extractUserLines(opts),\n }));\n }\n\n // Matchers & model resolvers\n\n protected async registerMatchers(opts: {\n enforcer: CasbinEnforcerType;\n casbin: typeof import('casbin');\n }): Promise<void> {\n const { enforcer, casbin } = opts;\n const { domainMatching, isScoped } = this.options;\n\n if (domainMatching) {\n if (!enforcer.getNamedRoleManager(domainMatching.roleDefinition)) {\n throw getError({\n message: `[registerMatchers] Role definition \"${domainMatching.roleDefinition}\" is not declared in the Casbin model. Declare it under [role_definition] (e.g. \\`g = _, _, _\\`) before enabling domainMatching.`,\n });\n }\n\n const matchFn = this.resolveDomainMatchingFn({ casbin, name: domainMatching.fn });\n await enforcer.addNamedDomainMatchingFunc(domainMatching.roleDefinition, matchFn);\n }\n\n if (isScoped) {\n await enforcer.addNamedDomainMatchingFunc(CasbinRuleVariants.G, casbin.Util.keyMatchFunc);\n await enforcer.addFunction('objectMatch', AuthorizationPermissionBuilder.objectMatch);\n\n // A dedicated role manager for the resource axis, NOT addNamedMatchingFunc: a matching func sets casbin's `hasPattern`, which makes every hasLink rebuild the whole g4 graph.\n enforcer.setNamedRoleManager(\n AuthorizationPolicyVariants.RESOURCE_INHERITS.rule,\n new ResourceRoleManager(),\n );\n\n // Shared across g2, g3, and the reversed `g` instance below: casbin never puts the\n // `g`-axis hierarchy manager in rmMap, so it never receives addLink and would miss\n // per-request g3 edges - g2 needs the same freshness for a just-created child domain.\n // This is a per-REQUEST overlay: `clear()` empties it every buildRoleLinks cycle, and it is\n // repopulated from whatever `g3` lines this principal's own policy line set carries.\n const domainHierarchyOverlay = new Map<string, Set<string>>();\n\n // g2 (membership) and g3 (domain nesting, request-domain-first) sit on their own axes.\n enforcer.setNamedRoleManager(\n CasbinRuleVariants.G2,\n new MembershipRoleManager({ overlay: domainHierarchyOverlay }),\n );\n\n enforcer.setNamedRoleManager(\n CasbinRuleVariants.G3,\n new DomainHierarchyRoleManager({ overlay: domainHierarchyOverlay }),\n );\n\n // addNamedDomainMatchingFunc(G, keyMatchFunc) above must stay: generateTempRoles ORs\n // hasDomainPattern with hasDomainHierarchy, and role_inherits `*` rides the keyMatch path.\n const gRoleManager = enforcer.getNamedRoleManager(CasbinRuleVariants.G) as\n | (CasbinRoleManagerType & ICasbinRoleManagerWithDomainHierarchy)\n | undefined;\n\n if (!gRoleManager?.addDomainHierarchy) {\n throw getError({\n message:\n '[registerMatchers] The \"g\" role manager does not expose addDomainHierarchy() - the scoped model requires casbin\\'s DefaultRoleManager on the g axis (present in casbin ^5.51.1, this package\\'s pinned range). Upgrade casbin, or check that a custom role manager was not substituted for \"g\".',\n });\n }\n\n await gRoleManager.addDomainHierarchy(\n new DomainHierarchyRoleManager({ reversed: true, overlay: domainHierarchyOverlay }),\n );\n }\n\n await enforcer.buildRoleLinks();\n }\n\n /** Map a CasbinDomainMatchingFunctions value to casbin's Util.*Func matcher. */\n protected resolveDomainMatchingFn(opts: {\n casbin: typeof import('casbin');\n name: TCasbinDomainMatchingFunction;\n }): (arg1: string, arg2: string) => boolean {\n // casbin Util built-ins: (requestValue, policyValue) => match. keyMatchFunc only special-cases `*` (never splits on `/` or `:`), so it cannot pattern-match a `Merchant_<uuid>`; see CasbinDomainMatchingFunctions for per-function semantics.\n const { Util } = opts.casbin;\n\n switch (opts.name) {\n case CasbinDomainMatchingFunctions.KEY_MATCH: {\n return Util.keyMatchFunc;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_2: {\n return Util.keyMatch2Func;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_3: {\n return Util.keyMatch3Func;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_4: {\n return Util.keyMatch4Func;\n }\n case CasbinDomainMatchingFunctions.REGEX_MATCH: {\n return Util.regexMatchFunc;\n }\n default: {\n throw getError({\n message: `[resolveDomainMatchingFn] Unsupported func: ${opts.name} | Valids: [${[...CasbinDomainMatchingFunctions.SCHEME_SET].join(', ')}]`,\n });\n }\n }\n }\n\n /** Default (sub,dom,obj,act) payload for the scoped model; domain comes from request.domain. */\n protected defaultScopedPayloadFn(): TNormalizePayloadFn<E, TAction, TResource> | undefined {\n if (!this.options.isScoped) {\n return undefined;\n }\n\n return (opts: {\n user: IAuthorizationUser;\n action: TAction;\n resource: TResource;\n }): { subject: string; resource: string; action: string; domain?: string } => {\n // No domain here - evaluate() fills it from request.domain (set by the provider).\n return {\n subject: `${opts.user.principalType}_${opts.user.userId}`,\n resource: String(opts.resource),\n action: String(opts.action),\n };\n };\n }\n\n protected resolveModel(opts: {\n casbin: typeof import('casbin');\n model: ICasbinEnforcerOptions['model'];\n }) {\n const { casbin, model } = opts;\n\n switch (model.driver) {\n case CasbinEnforcerModelDrivers.FILE: {\n return casbin.newModelFromFile(model.definition);\n }\n case CasbinEnforcerModelDrivers.TEXT: {\n return casbin.newModelFromString(model.definition);\n }\n default: {\n throw getError({\n message: `[resolveModel] Invalid model.driver | Valids: [${CasbinEnforcerModelDrivers.FILE}, ${CasbinEnforcerModelDrivers.TEXT}]`,\n });\n }\n }\n }\n\n protected validateExpiresIn(opts: { expiresIn: number }): void {\n if (opts.expiresIn >= this.MIN_EXPIRES_IN) {\n return;\n }\n\n throw getError({\n message: `[CasbinAuthorizationEnforcer] cached.options.expiresIn must be >= ${this.MIN_EXPIRES_IN} (ms) | Received: ${opts.expiresIn}`,\n });\n }\n\n // Policy loading internals\n\n /** Resolves this enforcer's model, then delegates the isolated-enforcer extraction (own model + adapter, never a pooled serving one, so concurrent requests cannot change what we cache) to PolicyLineCodec. */\n protected async extractUserLines(opts: { user: IAuthorizationUser }): Promise<string[]> {\n const casbin = await CasbinModule.load();\n const model = this.resolveModel({ casbin, model: this.options.model });\n\n return PolicyLineCodec.extractUserLines({\n casbin,\n model,\n adapter: this.options.adapter,\n user: opts.user,\n });\n }\n\n /** Requires configure() to have resolved the casbin Helper; the clearPolicy + loadPolicyLine + buildRoleLinks ordering lives in PolicyLineCodec. */\n protected async loadPolicyLinesIntoModel(opts: {\n enforcer: CasbinEnforcerType;\n lines: string[];\n }): Promise<void> {\n if (!this.helper) {\n throw getError({\n message: '[loadPolicyLinesIntoModel] Not configured. Call configure() first.',\n });\n }\n\n await PolicyLineCodec.loadLinesIntoModel({\n enforcer: opts.enforcer,\n lines: opts.lines,\n helper: this.helper,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"casbin.enforcer.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/enforcers/casbin.enforcer.ts"],"names":[],"mappings":";;;;;;;;;;;;;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,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,IAGxC;QACC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,oEAAoE;aAC9E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,eAAe,CAAC,kBAAkB,CAAC;YACvC,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,MAAM,EAAE,IAAI,CAAC,MAAM;SACpB,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAhbY,2BAA2B;IAoBnC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,oBAAoB,CAAC,eAAe,CAAC,0BAA0B,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;;GApBhF,2BAA2B,CAgbvC","sourcesContent":["import { type TContext } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { BaseHelper, BasePoolHelper, getError } from '@venizia/ignis-helpers/core';\nimport { type TNullable } from '@venizia/ignis-helpers/common';\nimport type {\n Enforcer as CasbinEnforcerType,\n Helper as CasbinHelperType,\n RoleManager as CasbinRoleManagerType,\n} from 'casbin';\nimport { type Env } from 'hono';\nimport { AuthorizationPermissionBuilder } from '@venizia/ignis-kernel';\nimport {\n AuthorizationDecisions,\n AuthorizationDomainScopes,\n AuthorizationEnforcerTypes,\n AuthorizationPolicyVariants,\n AuthorizeBindingKeys,\n CasbinDomainMatchingFunctions,\n CasbinEnforcerModelDrivers,\n CasbinRuleVariants,\n type IAuthorizationEnforcer,\n type IAuthorizationUser,\n type ICasbinEnforcerOptions,\n type ICasbinRules,\n type IAuthorizationRequest,\n type TAuthorizationDecision,\n type TCasbinDomainMatchingFunction,\n} from '@venizia/ignis-kernel';\nimport { DomainHierarchyRoleManager } from '../role-managers/domain-hierarchy';\nimport { CasbinModule } from './casbin-module';\nimport { MembershipRoleManager } from '../role-managers/membership';\nimport { ResourceRoleManager } from '../role-managers/resource';\nimport { PolicyLineCodec } from './policy-line-codec';\nimport { UserPolicyLineCache } from './user-policy-line-cache';\n\n/** Payload shape for the scoped/custom path, matching defaultScopedPayloadFn(). */\ntype TNormalizePayloadFn<E extends Env, TAction, TResource> = (opts: {\n user: IAuthorizationUser;\n action: TAction;\n resource: TResource;\n context: TContext<E, string>;\n}) => { subject: string; resource: string; action: string; domain?: string };\n\n/** `addDomainHierarchy` lives on casbin's `DefaultRoleManager`, not on the `RoleManager` interface or the `Enforcer` facade - feature-detect it on whatever `getNamedRoleManager` returns. */\ninterface ICasbinRoleManagerWithDomainHierarchy {\n addDomainHierarchy?(rm: CasbinRoleManagerType): Promise<void>;\n}\n\n// Wraps casbin (optional peer dep). Each request borrows its own pooled enforcer; any error during use destroys it (fail-closed). Pooled enforcers carry no adapter - only extractUserLines uses one.\n\n/** Authorization enforcer backed by casbin (an optional peer dependency); `configure()` throws when `options.model` is missing. */\nexport class CasbinAuthorizationEnforcer<\n E extends Env = Env,\n TAction extends string = string,\n TResource extends string = string,\n>\n extends BaseHelper\n implements IAuthorizationEnforcer<E, TAction, TResource, ICasbinRules>\n{\n name = CasbinAuthorizationEnforcer.name;\n private readonly MIN_EXPIRES_IN = 10_000;\n\n private pool: TNullable<BasePoolHelper<CasbinEnforcerType>> = null;\n private helper: TNullable<typeof CasbinHelperType> = null;\n // Lazily created on first cache use (see requireRedisCache) - one instance for the enforcer's lifetime so its single-flight de-dup map actually dedupes.\n private userPolicyLineCache: TNullable<UserPolicyLineCache> = null;\n\n // Memoized in configure() (options are fixed after) to avoid rebuilding this closure on every evaluate() (hot path).\n private resolvedPayloadFn: TNullable<TNormalizePayloadFn<E, TAction, TResource>> = null;\n\n constructor(\n @inject({ key: AuthorizeBindingKeys.enforcerOptions(AuthorizationEnforcerTypes.CASBIN) })\n private options: ICasbinEnforcerOptions<E, TAction, TResource>,\n ) {\n super({ scope: CasbinAuthorizationEnforcer.name });\n }\n\n // Lifecycle\n\n async configure(): Promise<void> {\n const casbin = await CasbinModule.load();\n\n if (!this.options.model) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] options.model is required.',\n });\n }\n\n this.helper = casbin.Helper;\n\n this.resolvedPayloadFn = this.options.normalizePayloadFn ?? this.defaultScopedPayloadFn();\n\n const { cached } = this.options;\n\n if (cached.use) {\n this.validateExpiresIn({ expiresIn: cached.options.expiresIn });\n }\n\n this.pool = new BasePoolHelper<CasbinEnforcerType>({\n scope: `${CasbinAuthorizationEnforcer.name}.Pool`,\n size: this.options.poolSize ?? 16,\n acquireTimeoutMs: this.options.poolAcquireTimeoutMs ?? 5000,\n create: async () => {\n const model = this.resolveModel({ casbin, model: this.options.model });\n\n const enforcer = await casbin.newEnforcer(model);\n await this.registerMatchers({ enforcer, casbin });\n this.assertMatcherCompilesSync({ enforcer });\n\n return enforcer;\n },\n });\n await this.pool.warmup();\n\n this.logger\n .for(this.configure.name)\n .info(\n 'Casbin enforcer pool ready (size: %s, cached: %s)',\n this.options.poolSize ?? 16,\n cached.use ? cached.driver : 'none',\n );\n }\n\n destroy(): void {\n this.pool?.destroy().catch((error) => {\n this.logger.for(this.destroy.name).warn('Pool destroy failed: %s', error);\n });\n }\n\n /** casbin compiles the matcher lazily (first enforce, not newEnforcer/buildRoleLinks); this dummy enforceSync forces the compile at warmup so syntax / unregistered-function / arity errors fail boot. */\n protected assertMatcherCompilesSync(opts: { enforcer: CasbinEnforcerType }) {\n try {\n if (this.options.isScoped || this.options.normalizePayloadFn) {\n opts.enforcer.enforceSync('::warmup', '::warmup', '::warmup', '::warmup');\n\n return;\n }\n\n opts.enforcer.enforceSync('::warmup', '::warmup', '::warmup');\n } catch (error) {\n throw getError({\n message: `[CasbinAuthorizationEnforcer] Matcher smoke test failed at warmup - the model matcher did not compile (check matcher syntax, that every referenced function is registered, and the request arity). ${String(error)}`,\n });\n }\n }\n\n // IAuthorizationEnforcer - public API\n\n async buildRules(opts: {\n user: IAuthorizationUser;\n context: TContext<E, string>;\n }): Promise<ICasbinRules> {\n const { user } = opts;\n const cached = this.options.cached;\n\n let lines: string[];\n\n if (cached.use) {\n const fetched = await this.requireRedisCache().fetch({ user });\n lines = fetched;\n } else {\n const extracted = await this.extractUserLines({ user });\n lines = extracted;\n }\n\n return { user, lines };\n }\n\n async evaluate(opts: {\n rules: ICasbinRules;\n request: IAuthorizationRequest<TAction, TResource>;\n context: TContext<E, string>;\n }): Promise<TAuthorizationDecision> {\n if (!this.pool) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] Not configured. Call configure() first.',\n });\n }\n\n if (!opts.request?.action || !opts.request?.resource) {\n throw getError({\n message: '[CasbinAuthorizationEnforcer] request.action and request.resource are required.',\n });\n }\n\n const { rules, request, context } = opts;\n const { user, lines } = rules;\n\n return this.pool.use({\n execution: async (enforcer) => {\n await this.loadPolicyLinesIntoModel({ enforcer, lines });\n\n const normalizePayloadFn = this.resolvedPayloadFn;\n\n if (!normalizePayloadFn) {\n const subject = `${user.principalType}_${user.userId}`;\n const isAllowed = this.enforceWithExplain({\n enforcer,\n vals: [subject, String(request.resource), String(request.action)],\n });\n\n return isAllowed ? AuthorizationDecisions.ALLOW : AuthorizationDecisions.DENY;\n }\n\n const normalized = normalizePayloadFn({\n user,\n action: request.action,\n resource: request.resource,\n context,\n });\n\n // Scoped model is 4-token (sub, dom, obj, act): a request with no resolvable domain still needs one - default SYSTEM_WIDE, never the 3-arg path, which misaligns args and silently misjudges.\n const domain =\n normalized.domain ??\n request.domain ??\n (this.options.isScoped ? AuthorizationDomainScopes.SYSTEM_WIDE : undefined);\n\n const vals = domain\n ? [normalized.subject, domain, normalized.resource, normalized.action]\n : [normalized.subject, normalized.resource, normalized.action];\n const isAllowed = this.enforceWithExplain({ enforcer, vals });\n\n return isAllowed ? AuthorizationDecisions.ALLOW : AuthorizationDecisions.DENY;\n },\n });\n }\n\n /** On DENY, logs the deciding policy rule; matchedPolicy is `[]` when nothing matched (default-deny). */\n protected enforceWithExplain(opts: { enforcer: CasbinEnforcerType; vals: string[] }): boolean {\n const [isAllowed, matchedPolicy] = opts.enforcer.enforceExSync(...opts.vals);\n\n if (!isAllowed) {\n this.logger\n .for(this.evaluate.name)\n .info(\n 'DENY | request: [%s] | matchedPolicy: %s',\n opts.vals.join(', '),\n matchedPolicy.length ? matchedPolicy.join(', ') : '<none - default-deny>',\n );\n }\n\n return isAllowed;\n }\n\n // Cache management - optional IAuthorizationEnforcer members (on-demand)\n async invalidateUserCache(opts: {\n user: IAuthorizationUser;\n }): Promise<{ invalidatedKeys: number }> {\n const { cacheKey, invalidatedKeys } = await this.requireRedisCache().invalidate({\n user: opts.user,\n });\n\n this.logger\n .for(this.invalidateUserCache.name)\n .info(\n 'Invalidated authz cache | user: %s | key: %s | deleted: %s',\n opts.user.userId,\n cacheKey,\n invalidatedKeys,\n );\n\n return { invalidatedKeys };\n }\n\n async rebuildUserCache(opts: {\n user: IAuthorizationUser;\n }): Promise<{ cacheKey: string; lineCount: number }> {\n // Extraction runs on an isolated throwaway enforcer (not a serving model), so a concurrent request cannot make us cache another user's policies under this key.\n const { cacheKey, lines } = await this.requireRedisCache().rebuild({ user: opts.user });\n\n this.logger\n .for(this.rebuildUserCache.name)\n .info(\n 'Rebuilt authz cache | user: %s | key: %s | lines: %s',\n opts.user.userId,\n cacheKey,\n lines.length,\n );\n\n return { cacheKey, lineCount: lines.length };\n }\n\n /** Narrow `options.cached` to the redis variant and lazily create the per-user line cache - memoized so its single-flight de-dup map is shared across calls rather than reset on every access. */\n protected requireRedisCache(): UserPolicyLineCache {\n const { cached } = this.options;\n\n if (!cached.use) {\n throw getError({\n message:\n '[CasbinAuthorizationEnforcer] Cache management requires the redis cache driver, but caching is disabled.',\n });\n }\n\n return (this.userPolicyLineCache ??= new UserPolicyLineCache({\n cached,\n loadLines: (opts) => this.extractUserLines(opts),\n }));\n }\n\n // Matchers & model resolvers\n\n protected async registerMatchers(opts: {\n enforcer: CasbinEnforcerType;\n casbin: typeof import('casbin');\n }): Promise<void> {\n const { enforcer, casbin } = opts;\n const { domainMatching, isScoped } = this.options;\n\n if (domainMatching) {\n if (!enforcer.getNamedRoleManager(domainMatching.roleDefinition)) {\n throw getError({\n message: `[registerMatchers] Role definition \"${domainMatching.roleDefinition}\" is not declared in the Casbin model. Declare it under [role_definition] (e.g. \\`g = _, _, _\\`) before enabling domainMatching.`,\n });\n }\n\n const matchFn = this.resolveDomainMatchingFn({ casbin, name: domainMatching.fn });\n await enforcer.addNamedDomainMatchingFunc(domainMatching.roleDefinition, matchFn);\n }\n\n if (isScoped) {\n await enforcer.addNamedDomainMatchingFunc(CasbinRuleVariants.G, casbin.Util.keyMatchFunc);\n await enforcer.addFunction('objectMatch', AuthorizationPermissionBuilder.objectMatch);\n\n // A dedicated role manager for the resource axis, NOT addNamedMatchingFunc: a matching func sets casbin's `hasPattern`, which makes every hasLink rebuild the whole g4 graph.\n enforcer.setNamedRoleManager(\n AuthorizationPolicyVariants.RESOURCE_INHERITS.rule,\n new ResourceRoleManager(),\n );\n\n // Shared across g2, g3, and the reversed `g` instance below: casbin never puts the\n // `g`-axis hierarchy manager in rmMap, so it never receives addLink and would miss\n // per-request g3 edges - g2 needs the same freshness for a just-created child domain.\n // This is a per-REQUEST overlay: `clear()` empties it every buildRoleLinks cycle, and it is\n // repopulated from whatever `g3` lines this principal's own policy line set carries.\n const domainHierarchyOverlay = new Map<string, Set<string>>();\n\n // g2 (membership) and g3 (domain nesting, request-domain-first) sit on their own axes.\n enforcer.setNamedRoleManager(\n CasbinRuleVariants.G2,\n new MembershipRoleManager({ overlay: domainHierarchyOverlay }),\n );\n\n enforcer.setNamedRoleManager(\n CasbinRuleVariants.G3,\n new DomainHierarchyRoleManager({ overlay: domainHierarchyOverlay }),\n );\n\n // addNamedDomainMatchingFunc(G, keyMatchFunc) above must stay: generateTempRoles ORs\n // hasDomainPattern with hasDomainHierarchy, and role_inherits `*` rides the keyMatch path.\n const gRoleManager = enforcer.getNamedRoleManager(CasbinRuleVariants.G) as\n | (CasbinRoleManagerType & ICasbinRoleManagerWithDomainHierarchy)\n | undefined;\n\n if (!gRoleManager?.addDomainHierarchy) {\n throw getError({\n message:\n '[registerMatchers] The \"g\" role manager does not expose addDomainHierarchy() - the scoped model requires casbin\\'s DefaultRoleManager on the g axis (present in casbin ^5.51.1, this package\\'s pinned range). Upgrade casbin, or check that a custom role manager was not substituted for \"g\".',\n });\n }\n\n await gRoleManager.addDomainHierarchy(\n new DomainHierarchyRoleManager({ reversed: true, overlay: domainHierarchyOverlay }),\n );\n }\n\n await enforcer.buildRoleLinks();\n }\n\n /** Map a CasbinDomainMatchingFunctions value to casbin's Util.*Func matcher. */\n protected resolveDomainMatchingFn(opts: {\n casbin: typeof import('casbin');\n name: TCasbinDomainMatchingFunction;\n }): (arg1: string, arg2: string) => boolean {\n // casbin Util built-ins: (requestValue, policyValue) => match. keyMatchFunc only special-cases `*` (never splits on `/` or `:`), so it cannot pattern-match a `Merchant_<uuid>`; see CasbinDomainMatchingFunctions for per-function semantics.\n const { Util } = opts.casbin;\n\n switch (opts.name) {\n case CasbinDomainMatchingFunctions.KEY_MATCH: {\n return Util.keyMatchFunc;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_2: {\n return Util.keyMatch2Func;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_3: {\n return Util.keyMatch3Func;\n }\n case CasbinDomainMatchingFunctions.KEY_MATCH_4: {\n return Util.keyMatch4Func;\n }\n case CasbinDomainMatchingFunctions.REGEX_MATCH: {\n return Util.regexMatchFunc;\n }\n default: {\n throw getError({\n message: `[resolveDomainMatchingFn] Unsupported func: ${opts.name} | Valids: [${CasbinDomainMatchingFunctions.values().join(', ')}]`,\n });\n }\n }\n }\n\n /** Default (sub,dom,obj,act) payload for the scoped model; domain comes from request.domain. */\n protected defaultScopedPayloadFn(): TNormalizePayloadFn<E, TAction, TResource> | undefined {\n if (!this.options.isScoped) {\n return undefined;\n }\n\n return (opts: {\n user: IAuthorizationUser;\n action: TAction;\n resource: TResource;\n }): { subject: string; resource: string; action: string; domain?: string } => {\n // No domain here - evaluate() fills it from request.domain (set by the provider).\n return {\n subject: `${opts.user.principalType}_${opts.user.userId}`,\n resource: String(opts.resource),\n action: String(opts.action),\n };\n };\n }\n\n protected resolveModel(opts: {\n casbin: typeof import('casbin');\n model: ICasbinEnforcerOptions['model'];\n }) {\n const { casbin, model } = opts;\n\n switch (model.driver) {\n case CasbinEnforcerModelDrivers.FILE: {\n return casbin.newModelFromFile(model.definition);\n }\n case CasbinEnforcerModelDrivers.TEXT: {\n return casbin.newModelFromString(model.definition);\n }\n default: {\n throw getError({\n message: `[resolveModel] Invalid model.driver | Valids: [${CasbinEnforcerModelDrivers.FILE}, ${CasbinEnforcerModelDrivers.TEXT}]`,\n });\n }\n }\n }\n\n protected validateExpiresIn(opts: { expiresIn: number }): void {\n if (opts.expiresIn >= this.MIN_EXPIRES_IN) {\n return;\n }\n\n throw getError({\n message: `[CasbinAuthorizationEnforcer] cached.options.expiresIn must be >= ${this.MIN_EXPIRES_IN} (ms) | Received: ${opts.expiresIn}`,\n });\n }\n\n // Policy loading internals\n\n /** Resolves this enforcer's model, then delegates the isolated-enforcer extraction (own model + adapter, never a pooled serving one, so concurrent requests cannot change what we cache) to PolicyLineCodec. */\n protected async extractUserLines(opts: { user: IAuthorizationUser }): Promise<string[]> {\n const casbin = await CasbinModule.load();\n const model = this.resolveModel({ casbin, model: this.options.model });\n\n return PolicyLineCodec.extractUserLines({\n casbin,\n model,\n adapter: this.options.adapter,\n user: opts.user,\n });\n }\n\n /** Requires configure() to have resolved the casbin Helper; the clearPolicy + loadPolicyLine + buildRoleLinks ordering lives in PolicyLineCodec. */\n protected async loadPolicyLinesIntoModel(opts: {\n enforcer: CasbinEnforcerType;\n lines: string[];\n }): Promise<void> {\n if (!this.helper) {\n throw getError({\n message: '[loadPolicyLinesIntoModel] Not configured. Call configure() first.',\n });\n }\n\n await PolicyLineCodec.loadLinesIntoModel({\n enforcer: opts.enforcer,\n lines: opts.lines,\n helper: this.helper,\n });\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { IRedisHelper } from '@venizia/ignis-helpers';
|
|
2
2
|
import type { SocketIOServerHelper, TSocketIOAuthenticateFn, TSocketIOClientConnectedFn, TSocketIOValidateRoomFn } from '@venizia/ignis-helpers/socket-io';
|
|
3
3
|
import type { ServerOptions } from 'socket.io';
|
|
4
4
|
/** Container keys of the Socket.IO component: the server instance, its options, the Redis connection and the handlers an application binds. */
|
|
5
5
|
export declare class SocketIOBindingKeys {
|
|
6
6
|
static readonly SOCKET_IO_INSTANCE: import("@venizia/ignis-inversion").TBindingKey<SocketIOServerHelper>;
|
|
7
7
|
static readonly SERVER_OPTIONS: import("@venizia/ignis-inversion").TBindingKey<Partial<ServerOptions>>;
|
|
8
|
-
static readonly REDIS_CONNECTION: import("@venizia/ignis-inversion").TBindingKey<
|
|
8
|
+
static readonly REDIS_CONNECTION: import("@venizia/ignis-inversion").TBindingKey<IRedisHelper | null>;
|
|
9
9
|
static readonly AUTHENTICATE_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TSocketIOAuthenticateFn | null>;
|
|
10
10
|
static readonly VALIDATE_ROOM_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TSocketIOValidateRoomFn | null>;
|
|
11
11
|
static readonly CLIENT_CONNECTED_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TSocketIOClientConnectedFn | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../../../../src/components/socket-io/common/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAUvD,+IAA+I;AAC/I,MAAM,OAAO,mBAAmB;aACd,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAuB;QAC3E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC;aAEa,mBAAc,GAAG,WAAW,CAAC,KAAK,CAAyB;QACzE,GAAG,EAAE,+BAA+B;KACrC,CAAC,CAAC;aAEa,qBAAgB,GAAG,WAAW,CAAC,KAAK,
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../../../../src/components/socket-io/common/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAUvD,+IAA+I;AAC/I,MAAM,OAAO,mBAAmB;aACd,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAuB;QAC3E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC;aAEa,mBAAc,GAAG,WAAW,CAAC,KAAK,CAAyB;QACzE,GAAG,EAAE,+BAA+B;KACrC,CAAC,CAAC;aAEa,qBAAgB,GAAG,WAAW,CAAC,KAAK,CAAsB;QACxE,GAAG,EAAE,iCAAiC;KACvC,CAAC,CAAC;aAEa,yBAAoB,GAAG,WAAW,CAAC,KAAK,CAAiC;QACvF,GAAG,EAAE,qCAAqC;KAC3C,CAAC,CAAC;aAEa,0BAAqB,GAAG,WAAW,CAAC,KAAK,CAAiC;QACxF,GAAG,EAAE,sCAAsC;KAC5C,CAAC,CAAC;aAEa,6BAAwB,GAAG,WAAW,CAAC,KAAK,CAAoC;QAC9F,GAAG,EAAE,yCAAyC;KAC/C,CAAC,CAAC","sourcesContent":["import { BindingKeys } from '@venizia/ignis-inversion';\nimport type { IRedisHelper } from '@venizia/ignis-helpers';\nimport type {\n SocketIOServerHelper,\n TSocketIOAuthenticateFn,\n TSocketIOClientConnectedFn,\n TSocketIOValidateRoomFn,\n} from '@venizia/ignis-helpers/socket-io';\nimport type { ServerOptions } from 'socket.io';\n\n/** Container keys of the Socket.IO component: the server instance, its options, the Redis connection and the handlers an application binds. */\nexport class SocketIOBindingKeys {\n static readonly SOCKET_IO_INSTANCE = BindingKeys.build<SocketIOServerHelper>({\n key: '@app/socket-io/instance',\n });\n\n static readonly SERVER_OPTIONS = BindingKeys.build<Partial<ServerOptions>>({\n key: '@app/socket-io/server-options',\n });\n\n static readonly REDIS_CONNECTION = BindingKeys.build<IRedisHelper | null>({\n key: '@app/socket-io/redis-connection',\n });\n\n static readonly AUTHENTICATE_HANDLER = BindingKeys.build<TSocketIOAuthenticateFn | null>({\n key: '@app/socket-io/authenticate-handler',\n });\n\n static readonly VALIDATE_ROOM_HANDLER = BindingKeys.build<TSocketIOValidateRoomFn | null>({\n key: '@app/socket-io/validate-room-handler',\n });\n\n static readonly CLIENT_CONNECTED_HANDLER = BindingKeys.build<TSocketIOClientConnectedFn | null>({\n key: '@app/socket-io/client-connected-handler',\n });\n}\n"]}
|
|
@@ -3,7 +3,6 @@ import type { IStaticAssetCommitTokenPayload } from '../common/types.js';
|
|
|
3
3
|
export declare class StaticAssetCommitTokenUtility {
|
|
4
4
|
private static encode;
|
|
5
5
|
private static sign;
|
|
6
|
-
private static isRecord;
|
|
7
6
|
private static isStringRecord;
|
|
8
7
|
/** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */
|
|
9
8
|
private static parse;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';
|
|
2
|
-
import { getError } from '@venizia/ignis-helpers/core';
|
|
2
|
+
import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
|
|
3
3
|
import { StaticAssetTokenStages } from '../common/constants.js';
|
|
4
4
|
import { StaticAssetErrors } from '../common/errors.js';
|
|
5
5
|
/** Signs and reads the token the commit route trusts instead of a key a caller names. */
|
|
@@ -15,12 +15,8 @@ export class StaticAssetCommitTokenUtility {
|
|
|
15
15
|
opts: { outputEncoding: HashOutputEncodings.BASE64URL },
|
|
16
16
|
});
|
|
17
17
|
}
|
|
18
|
-
static isRecord(value) {
|
|
19
|
-
return typeof value === 'object' && value !== null;
|
|
20
|
-
}
|
|
21
18
|
static isStringRecord(value) {
|
|
22
|
-
return (
|
|
23
|
-
!Array.isArray(value) &&
|
|
19
|
+
return (RecordUtility.isPlainRecord(value) &&
|
|
24
20
|
Object.values(value).every((entry) => typeof entry === 'string'));
|
|
25
21
|
}
|
|
26
22
|
/** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */
|
|
@@ -32,13 +28,13 @@ export class StaticAssetCommitTokenUtility {
|
|
|
32
28
|
catch {
|
|
33
29
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
34
30
|
}
|
|
35
|
-
if (!
|
|
31
|
+
if (!RecordUtility.isRecord(parsed)) {
|
|
36
32
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
37
33
|
}
|
|
38
34
|
const { bucket, object, expiresAt, owner, metadata, stage, pin } = parsed;
|
|
39
|
-
if (!
|
|
35
|
+
if (!RecordUtility.isRecord(bucket) ||
|
|
40
36
|
typeof bucket.name !== 'string' ||
|
|
41
|
-
!
|
|
37
|
+
!RecordUtility.isRecord(object) ||
|
|
42
38
|
typeof object.key !== 'string' ||
|
|
43
39
|
typeof expiresAt !== 'number' ||
|
|
44
40
|
typeof owner !== 'string' ||
|
|
@@ -71,7 +67,7 @@ export class StaticAssetCommitTokenUtility {
|
|
|
71
67
|
}
|
|
72
68
|
static parsePin(opts) {
|
|
73
69
|
const { pin } = opts;
|
|
74
|
-
if (!
|
|
70
|
+
if (!RecordUtility.isRecord(pin) ||
|
|
75
71
|
typeof pin.etag !== 'string' ||
|
|
76
72
|
(pin.versionId !== undefined && typeof pin.versionId !== 'string')) {
|
|
77
73
|
throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commit-token.utility.js","sourceRoot":"","sources":["../../../../../src/components/static-asset/utilities/commit-token.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"commit-token.utility.js","sourceRoot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,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,KAAK,CAAC;QAEhC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YAC9C,MAAM,QAAQ,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,CAAC;QACzD,CAAC;QAED,IACE,CAAC,IAAI,CAAC,MAAM,CAAC;YACX,KAAK,EAAE,SAAS;YAChB,QAAQ,EAAE,6BAA6B,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;SAClE,CAAC,EACF,CAAC;YACD,MAAM,QAAQ,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,CAAC;QACzD,CAAC;QAED,MAAM,OAAO,GAAG,6BAA6B,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAE9D,IAAI,OAAO,CAAC,SAAS,IAAI,GAAG,EAAE,CAAC;YAC7B,MAAM,QAAQ,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,CAAC;QACzD,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { Hash, HashAlgorithms, HashOutputEncodings } from '@venizia/ignis-helpers';\nimport { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport { StaticAssetTokenStages } from '../common/constants';\nimport { StaticAssetErrors } from '../common/errors';\nimport type {\n IStaticAssetCommitTokenPayload,\n IStaticAssetPin,\n TStaticAssetTokenMetadata,\n} from '../common/types';\n\n/** Signs and reads the token the commit route trusts instead of a key a caller names. */\nexport class StaticAssetCommitTokenUtility {\n private static encode(payload: IStaticAssetCommitTokenPayload): string {\n return Buffer.from(JSON.stringify(payload)).toString('base64url');\n }\n\n // `Hash.hmac` refuses an empty secret: an unkeyed signature is one anyone can compute.\n private static sign(opts: { body: string; secretKey: string }): string {\n return Hash.withAlgorithm(HashAlgorithms.SHA256).hmac({\n message: opts.body,\n secret: opts.secretKey,\n opts: { outputEncoding: HashOutputEncodings.BASE64URL },\n });\n }\n\n private static isStringRecord(value: unknown): value is TStaticAssetTokenMetadata {\n return (\n RecordUtility.isPlainRecord(value) &&\n Object.values(value).every((entry) => typeof entry === 'string')\n );\n }\n\n /** A signed body that is not the current payload shape is refused as invalid: a token minted before the shape changed still carries a good signature. */\n private static parse(opts: { body: string }): IStaticAssetCommitTokenPayload {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(Buffer.from(opts.body, 'base64url').toString('utf8'));\n } catch {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (!RecordUtility.isRecord(parsed)) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const { bucket, object, expiresAt, owner, metadata, stage, pin } = parsed;\n\n if (\n !RecordUtility.isRecord(bucket) ||\n typeof bucket.name !== 'string' ||\n !RecordUtility.isRecord(object) ||\n typeof object.key !== 'string' ||\n typeof expiresAt !== 'number' ||\n typeof owner !== 'string' ||\n !StaticAssetCommitTokenUtility.isStringRecord(metadata)\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (stage === StaticAssetTokenStages.ISSUED) {\n return {\n bucket: { name: bucket.name },\n object: { key: object.key },\n expiresAt,\n owner,\n metadata,\n stage,\n };\n }\n\n // A validated token without its pin would commit unpinned content: it is no token.\n if (stage !== StaticAssetTokenStages.VALIDATED) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n return {\n bucket: { name: bucket.name },\n object: { key: object.key },\n expiresAt,\n owner,\n metadata,\n stage,\n pin: StaticAssetCommitTokenUtility.parsePin({ pin }),\n };\n }\n\n private static parsePin(opts: { pin: unknown }): IStaticAssetPin {\n const { pin } = opts;\n\n if (\n !RecordUtility.isRecord(pin) ||\n typeof pin.etag !== 'string' ||\n (pin.versionId !== undefined && typeof pin.versionId !== 'string')\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n return { etag: pin.etag, versionId: pin.versionId };\n }\n\n /** Signs the payload so the commit route can trust the key it is handed. */\n static build(opts: { payload: IStaticAssetCommitTokenPayload; secretKey: string }): string {\n const body = StaticAssetCommitTokenUtility.encode(opts.payload);\n\n return `${body}.${StaticAssetCommitTokenUtility.sign({ body, secretKey: opts.secretKey })}`;\n }\n\n /**\n * Reads a commit token back, or throws.\n *\n * Verification happens BEFORE any storage call, which is what makes the commit route refuse to be a\n * name prober: a forged token fails without a round trip, so timing says nothing about what exists.\n */\n static read(opts: {\n token: string;\n secretKey: string;\n now?: number;\n }): IStaticAssetCommitTokenPayload {\n const { token, secretKey, now = Date.now() } = opts;\n const parts = token.split('.');\n const [body, signature] = parts;\n\n if (parts.length !== 2 || !body || !signature) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n if (\n !Hash.equals({\n value: signature,\n expected: StaticAssetCommitTokenUtility.sign({ body, secretKey }),\n })\n ) {\n throw getError(StaticAssetErrors.INVALID_COMMIT_TOKEN);\n }\n\n const payload = StaticAssetCommitTokenUtility.parse({ body });\n\n if (payload.expiresAt <= now) {\n throw getError(StaticAssetErrors.EXPIRED_COMMIT_TOKEN);\n }\n\n return payload;\n }\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { IRedisHelper, TWebSocketAuthenticateFn, TWebSocketClientConnectedFn, TWebSocketClientDisconnectedFn, TWebSocketHandshakeFn, TWebSocketMessageHandler, TWebSocketOutboundTransformer, TWebSocketValidateRoomFn, WebSocketServerHelper } from '@venizia/ignis-helpers';
|
|
2
2
|
import type { IServerOptions } from './types.js';
|
|
3
3
|
/** Container keys of the WebSocket component: the server instance, its options, the Redis connection and the handlers an application binds. */
|
|
4
4
|
export declare class WebSocketBindingKeys {
|
|
5
5
|
static readonly WEBSOCKET_INSTANCE: import("@venizia/ignis-inversion").TBindingKey<WebSocketServerHelper<Record<string, unknown>, Record<string, unknown>>>;
|
|
6
6
|
static readonly SERVER_OPTIONS: import("@venizia/ignis-inversion").TBindingKey<Partial<IServerOptions>>;
|
|
7
|
-
static readonly REDIS_CONNECTION: import("@venizia/ignis-inversion").TBindingKey<
|
|
7
|
+
static readonly REDIS_CONNECTION: import("@venizia/ignis-inversion").TBindingKey<IRedisHelper | null>;
|
|
8
8
|
static readonly AUTHENTICATE_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TWebSocketAuthenticateFn | null>;
|
|
9
9
|
static readonly VALIDATE_ROOM_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TWebSocketValidateRoomFn | null>;
|
|
10
10
|
static readonly CLIENT_CONNECTED_HANDLER: import("@venizia/ignis-inversion").TBindingKey<TWebSocketClientConnectedFn | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../../../../src/components/websocket/common/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAcvD,+IAA+I;AAC/I,MAAM,OAAO,oBAAoB;aACf,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAwB;QAC5E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC;aAEa,mBAAc,GAAG,WAAW,CAAC,KAAK,CAA0B;QAC1E,GAAG,EAAE,+BAA+B;KACrC,CAAC,CAAC;aAEa,qBAAgB,GAAG,WAAW,CAAC,KAAK,
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../../../../src/components/websocket/common/keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAcvD,+IAA+I;AAC/I,MAAM,OAAO,oBAAoB;aACf,uBAAkB,GAAG,WAAW,CAAC,KAAK,CAAwB;QAC5E,GAAG,EAAE,yBAAyB;KAC/B,CAAC,CAAC;aAEa,mBAAc,GAAG,WAAW,CAAC,KAAK,CAA0B;QAC1E,GAAG,EAAE,+BAA+B;KACrC,CAAC,CAAC;aAEa,qBAAgB,GAAG,WAAW,CAAC,KAAK,CAAsB;QACxE,GAAG,EAAE,iCAAiC;KACvC,CAAC,CAAC;aAEa,yBAAoB,GAAG,WAAW,CAAC,KAAK,CAAkC;QACxF,GAAG,EAAE,qCAAqC;KAC3C,CAAC,CAAC;aAEa,0BAAqB,GAAG,WAAW,CAAC,KAAK,CAAkC;QACzF,GAAG,EAAE,sCAAsC;KAC5C,CAAC,CAAC;aAEa,6BAAwB,GAAG,WAAW,CAAC,KAAK,CAAqC;QAC/F,GAAG,EAAE,yCAAyC;KAC/C,CAAC,CAAC;aAEa,gCAA2B,GACzC,WAAW,CAAC,KAAK,CAAwC;QACvD,GAAG,EAAE,4CAA4C;KAClD,CAAC,CAAC;aAEW,oBAAe,GAAG,WAAW,CAAC,KAAK,CAAkC;QACnF,GAAG,EAAE,gCAAgC;KACtC,CAAC,CAAC;aAEa,yBAAoB,GAAG,WAAW,CAAC,KAAK,CAAuC;QAC7F,GAAG,EAAE,qCAAqC;KAC3C,CAAC,CAAC;aAEa,sBAAiB,GAAG,WAAW,CAAC,KAAK,CAA+B;QAClF,GAAG,EAAE,kCAAkC;KACxC,CAAC,CAAC","sourcesContent":["import { BindingKeys } from '@venizia/ignis-inversion';\nimport type {\n IRedisHelper,\n TWebSocketAuthenticateFn,\n TWebSocketClientConnectedFn,\n TWebSocketClientDisconnectedFn,\n TWebSocketHandshakeFn,\n TWebSocketMessageHandler,\n TWebSocketOutboundTransformer,\n TWebSocketValidateRoomFn,\n WebSocketServerHelper,\n} from '@venizia/ignis-helpers';\nimport type { IServerOptions } from './types';\n\n/** Container keys of the WebSocket component: the server instance, its options, the Redis connection and the handlers an application binds. */\nexport class WebSocketBindingKeys {\n static readonly WEBSOCKET_INSTANCE = BindingKeys.build<WebSocketServerHelper>({\n key: '@app/websocket/instance',\n });\n\n static readonly SERVER_OPTIONS = BindingKeys.build<Partial<IServerOptions>>({\n key: '@app/websocket/server-options',\n });\n\n static readonly REDIS_CONNECTION = BindingKeys.build<IRedisHelper | null>({\n key: '@app/websocket/redis-connection',\n });\n\n static readonly AUTHENTICATE_HANDLER = BindingKeys.build<TWebSocketAuthenticateFn | null>({\n key: '@app/websocket/authenticate-handler',\n });\n\n static readonly VALIDATE_ROOM_HANDLER = BindingKeys.build<TWebSocketValidateRoomFn | null>({\n key: '@app/websocket/validate-room-handler',\n });\n\n static readonly CLIENT_CONNECTED_HANDLER = BindingKeys.build<TWebSocketClientConnectedFn | null>({\n key: '@app/websocket/client-connected-handler',\n });\n\n static readonly CLIENT_DISCONNECTED_HANDLER =\n BindingKeys.build<TWebSocketClientDisconnectedFn | null>({\n key: '@app/websocket/client-disconnected-handler',\n });\n\n static readonly MESSAGE_HANDLER = BindingKeys.build<TWebSocketMessageHandler | null>({\n key: '@app/websocket/message-handler',\n });\n\n static readonly OUTBOUND_TRANSFORMER = BindingKeys.build<TWebSocketOutboundTransformer | null>({\n key: '@app/websocket/outbound-transformer',\n });\n\n static readonly HANDSHAKE_HANDLER = BindingKeys.build<TWebSocketHandshakeFn | null>({\n key: '@app/websocket/handshake-handler',\n });\n}\n"]}
|
|
@@ -142,7 +142,7 @@ export class ApplicationBootAssertion {
|
|
|
142
142
|
const { keepDataSources = [], skipComponents = [], skipSteps = DEFAULT_SKIPPED_STEPS, verifyBindings = true, skipBindings = [], allowNoControllers = false, routes = true, } = options;
|
|
143
143
|
for (const step of skipSteps) {
|
|
144
144
|
if (!ServerBootSteps.isValid(step)) {
|
|
145
|
-
fail(`Unknown boot step in skipSteps: '${String(step)}' | Expected one of: ${
|
|
145
|
+
fail(`Unknown boot step in skipSteps: '${String(step)}' | Expected one of: ${ServerBootSteps.values().join(', ')}`);
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
let target;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert-application-boots.js","sourceRoot":"","sources":["../../../src/testing/assert-application-boots.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAwB,MAAM,qBAAqB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AC,UAAU,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,EACpE,CAAC;gBACD,IAAI,CACF,iNAAiN,CAClN,CAAC;YACJ,CAAC;YAED,IAAI,MAAM,EAAE,CAAC;gBACX,uBAAuB,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;YACnD,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,qBAAqB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAE7C,IAAI,OAAO,EAAE,CAAC;gBACZ,MAAM,CAAC,MAAM;qBACV,GAAG,CAAC,iCAAiC,CAAC;qBACtC,IAAI,CACH,oCAAoC,OAAO,oDAAoD,OAAO,oEAAoE,CAC3K,CAAC;YACN,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;gBAAS,CAAC;YACT,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;gBACtC,KAAK,CAAC,OAAO,EAAE,CAAC;YAClB,CAAC;YAED,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;gBACrC,OAAO,OAAO,CAAC,UAAU,CAAC;YAC5B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,UAAU,GAAG,kBAAkB,CAAC;YAC1C,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { BaseApplication } from '@/base/applications';\nimport { ServerBootSteps, type TServerBootStep } from '@/base/applications';\nimport type { IConfigurable, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BindingVerifier, isClass } from '@venizia/ignis-inversion';\nimport {\n type AbstractRestController,\n AuthorizationEnforcerRegistry,\n type Binding,\n BindingNamespaces,\n BindingValueTypes,\n ControllerTransports,\n CoreBindings,\n MetadataRegistry,\n} from '@venizia/ignis-kernel';\n\n/** A class (matched against the instance's constructor) or a string (matched against the binding key or the class name). */\nexport type TBootProbeTarget = TClass<unknown> | string;\n\n/** Options of `ApplicationBootAssertion.assert`; each field narrows or relaxes what the boot probe runs and verifies. */\nexport interface IAssertApplicationBootsOptions {\n /**\n * Datasources whose real `configure()` runs. Every other datasource is bound and resolved but not\n * configured, so no connection is made. Close a kept one with `await application.stop()`.\n *\n * @default []\n */\n keepDataSources?: TBootProbeTarget[];\n\n /**\n * Components whose `configure()` (and so their `binding()`) is skipped, for the few that need\n * infrastructure. What a skipped component would have registered is not registered.\n *\n * @default []\n */\n skipComponents?: TBootProbeTarget[];\n\n /**\n * Boot steps that do not run, so a remote secrets provider is never contacted. A value REPLACES\n * the default; an unknown name rejects before anything boots.\n *\n * @default [ServerBootSteps.HYDRATE_SECRETS, ServerBootSteps.WIRE_SECRET_ROTATABLES]\n */\n skipSteps?: TServerBootStep[];\n\n /**\n * After boot, resolves every service and repository with the shared core of\n * `@venizia/ignis-inversion`, so an injection nobody references at boot still fails. An explicit value\n * wins over the application's own `bootChecks`, whose boot step is off for the run.\n *\n * @default true\n */\n verifyBindings?: boolean;\n\n /**\n * Services or repositories the verification leaves unresolved, for one whose constructor needs\n * infrastructure. A class (exact), a class name or a binding key. A name that matches nothing rejects.\n *\n * @default []\n */\n skipBindings?: TBootProbeTarget[];\n\n /**\n * Whether an application that registered no controller passes. Off, it fails: it proves nothing, for example when the artifact index was empty.\n *\n * @default false\n */\n allowNoControllers?: boolean;\n\n /**\n * This helper's own check that no method and path is mounted twice. IGNIS boot does not detect that.\n *\n * @default true\n */\n routes?: boolean;\n}\n\n/** The boot sequence is the contract; these two are what the helper wraps on one instance. */\nconst WRAPPED_METHODS = ['registerDynamicBindings', 'getBootSequence'] as const;\n\nconst DEFAULT_SKIPPED_STEPS: TServerBootStep[] = [\n ServerBootSteps.HYDRATE_SECRETS,\n ServerBootSteps.WIRE_SECRET_ROTATABLES,\n];\n\n/** Methods a route entry may carry that are middleware, not a mounted handler. */\nconst NON_ROUTE_METHOD = 'ALL';\n\nconst bootedApplications = new WeakSet<object>();\n\ninterface IProbeBinding {\n key: string;\n}\n\ninterface IDynamicBindingsOptions {\n namespace: string;\n onBeforeConfigure?: (opts: { binding: Binding<IConfigurable> }) => Promise<void>;\n onAfterConfigure?: (opts: {\n binding: Binding<IConfigurable>;\n instance: IConfigurable;\n }) => Promise<void>;\n}\n\n/** What the helper replaced, so every path puts it back. */\ninterface IPatch {\n restore: () => void;\n}\n\nconst matchesTarget = (opts: {\n targets: TBootProbeTarget[];\n binding: IProbeBinding;\n instance: IConfigurable;\n}): boolean => {\n const { targets, binding, instance } = opts;\n const className: string | undefined = instance?.constructor?.name;\n\n return targets.some((target) =>\n typeof target === 'string'\n ? target === binding.key || target === className\n : instance?.constructor === target,\n );\n};\n\nconst fail = (message: string): never => {\n throw getError({ message: `[ApplicationBootAssertion.assert] ${message}` });\n};\n\n/** Replaces `object[name]` and returns the way back, even when `name` was inherited. */\nconst patchProperty = (opts: { object: object; name: string; value: unknown }): IPatch => {\n const { object, name, value } = opts;\n const descriptor = Object.getOwnPropertyDescriptor(object, name);\n\n Object.defineProperty(object, name, { value, configurable: true, writable: true });\n\n return {\n restore: () => {\n if (descriptor) {\n Object.defineProperty(object, name, descriptor);\n\n return;\n }\n\n Reflect.deleteProperty(object, name);\n },\n };\n};\n\nconst normalizePath = (path: string): string => {\n const withParams = path.replace(/:[A-Za-z0-9_]+/g, ':param').replace(/\\/{2,}/g, '/');\n\n return withParams.length > 1 ? withParams.replace(/\\/$/, '') : withParams;\n};\n\n/** The helper's own check: IGNIS mounts a method and path twice without complaint, and the first one wins. */\nconst assertNoDuplicateRoutes = (opts: { application: BaseApplication }): void => {\n const { application } = opts;\n // signature -> controller key -> how many times that controller declares it\n const mounted = new Map<string, Map<string, number>>();\n\n const record = (signature: string, key: string, declarations: number): void => {\n const owners = mounted.get(signature) ?? new Map<string, number>();\n owners.set(key, Math.max(owners.get(key) ?? 0, declarations));\n mounted.set(signature, owners);\n };\n\n for (const binding of application.findByTag<AbstractRestController>({\n tag: BindingNamespaces.CONTROLLER,\n })) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n const metadata = target\n ? MetadataRegistry.getInstance().getControllerMetadata({ target })\n : undefined;\n\n if (!metadata?.path || metadata.transport === ControllerTransports.GRPC) {\n continue;\n }\n\n // A bound controller is a class; this narrows it for the `prototype` read below.\n if (!isClass(target)) {\n continue;\n }\n\n const instance = application.get<AbstractRestController>({\n key: binding.key,\n isOptional: true,\n });\n\n // Hono's `routes` has one entry PER HANDLER (a validator, an authenticate and the handler of one route are three\n // entries with the same method and path), so an entry is not a declaration: a controller counts once per signature.\n for (const route of instance?.getRouter().routes ?? []) {\n if (route.method === NON_ROUTE_METHOD) {\n continue;\n }\n\n record(`${route.method} ${normalizePath(`${metadata.path}/${route.path}`)}`, binding.key, 1);\n }\n\n // What the router cannot show: one controller declaring a method and path twice. Decorated routes are one\n // metadata entry per declaration, so those are counted there.\n const declared = new Map<string, number>();\n\n for (const route of MetadataRegistry.getInstance()\n .getRoutes({ target: target.prototype })\n ?.values() ?? []) {\n const signature = `${String(route.method).toUpperCase()} ${normalizePath(`${metadata.path}/${route.path}`)}`;\n declared.set(signature, (declared.get(signature) ?? 0) + 1);\n }\n\n for (const [signature, declarations] of declared) {\n record(signature, binding.key, declarations);\n }\n }\n\n const duplicates = [...mounted.entries()].filter(\n ([, owners]) =>\n owners.size > 1 || [...owners.values()].some((declarations) => declarations > 1),\n );\n\n if (duplicates.length === 0) {\n return;\n }\n\n const lines = duplicates.map(\n ([signature, owners]) =>\n `${signature} | controllers: ${[...owners]\n .map(([key, declarations]) =>\n declarations > 1 ? `${key} (declared ${declarations} times)` : key,\n )\n .join(', ')}`,\n );\n fail(\n `${duplicates.length} route(s) are mounted more than once, and only the first one answers | ${lines.join(' ; ')} | This is the helper's own check (IGNIS boot does not detect it); pass { routes: false } to turn it off`,\n );\n};\n\n/**\n * Proves an IGNIS application boots, without a datasource connection, a socket or a secrets provider:\n * it runs the application's own boot sequence (`init()` then `initialize()`) and never calls `start()`,\n * so no socket is opened and no post-start hook runs.\n *\n * Datasources are bound and resolved but not configured, unless named in `keepDataSources`; the\n * secrets steps are skipped; every other step and every component runs as in a real boot. A component\n * that opens Redis, Kafka or S3 in `binding()` therefore runs for real: name it in `skipComponents`.\n * `setupMiddlewares()` is not run: it is the application's own start-time step, user code that may open\n * connections, and the probe cannot know it is free of side effects. The framework's default stack (CORS, body\n * limit, request id) is a boot step of `initialize()`, so an invalid `configs.middlewares` value still fails here.\n * When the boot fails inside a component, one warning names it; the rejection is still the original error. When the\n * boot fails, the rejection is the original error. The application stays booted and is returned;\n * a failed boot leaves a half-booted instance, so build a new one rather than reuse it.\n *\n * It wraps `registerDynamicBindings` and `getBootSequence` on THIS instance only (an application's\n * own override of either still runs) and restores them whatever happens.\n *\n * It owns the process-wide `AuthorizationEnforcerRegistry` for the duration of the check: it resets it before it\n * boots, so a second boot in the same process (another probe, or a test boot after this one) does not fail with\n * `Enforcer already registered`. An application still running in the same process loses its enforcer registrations\n * and its authorize options, so its requests are then decided by the no-enforcer default (deny unless configured\n * otherwise): do not run the probe in a process that serves an application.\n *\n * @example\n * ```typescript\n * import { ApplicationBootAssertion } from '@venizia/ignis/testing';\n * import { test } from 'bun:test';\n * import { Application } from './application';\n *\n * test('the application boots offline', async () => {\n * await ApplicationBootAssertion.assert({\n * application: () => new Application({ scope: 'Application', config: { host: '127.0.0.1', port: 0, path: { base: '/', isStrict: true } } }),\n * options: { skipComponents: ['MailComponent'], allowNoControllers: true },\n * });\n * });\n * ```\n */\nexport class ApplicationBootAssertion {\n static async assert<Application extends BaseApplication>(opts: {\n application: Application | (() => Application | Promise<Application>);\n options?: IAssertApplicationBootsOptions;\n }): Promise<Application> {\n const { application, options = {} } = opts;\n const {\n keepDataSources = [],\n skipComponents = [],\n skipSteps = DEFAULT_SKIPPED_STEPS,\n verifyBindings = true,\n skipBindings = [],\n allowNoControllers = false,\n routes = true,\n } = options;\n\n for (const step of skipSteps) {\n if (!ServerBootSteps.isValid(step)) {\n fail(\n `Unknown boot step in skipSteps: '${String(step)}' | Expected one of: ${[...ServerBootSteps.SCHEME_SET].join(', ')}`,\n );\n }\n }\n\n let target: Application;\n\n if (typeof application === 'function') {\n const built = await application();\n target = built;\n } else {\n target = application;\n }\n\n if (\n bootedApplications.has(target) ||\n Object.keys(target['registeredBindings'] ?? {}).length > 0\n ) {\n fail(\n `This application instance was already booted | A failed or finished boot leaves registrations behind, so build a new instance (pass a factory) for each call`,\n );\n }\n\n bootedApplications.add(target);\n\n for (const name of WRAPPED_METHODS) {\n if (typeof target[name] !== 'function') {\n fail(\n `The kernel method '${name}' is missing on this application | The helper cannot keep a boot offline without it, so it refuses to boot`,\n );\n }\n }\n\n const skippedSteps = new Set<string>(skipSteps);\n const patches: IPatch[] = [];\n let sweepsSeen = 0;\n // The components whose `configure()` is running, innermost last: when the boot rejects, the last one is where it failed.\n const configuringComponents: string[] = [];\n\n const neutralise = async (entry: {\n namespace: string;\n binding: Binding<IConfigurable>;\n }): Promise<void> => {\n const { namespace, binding } = entry;\n const isDataSource = namespace === BindingNamespaces.DATASOURCE;\n const isComponent = namespace === BindingNamespaces.COMPONENT;\n\n if (!isDataSource && !isComponent) {\n return;\n }\n\n const instance = target.get<IConfigurable>({ key: binding.key, isOptional: false });\n\n if (typeof instance?.configure !== 'function') {\n return;\n }\n\n const shouldRun = isDataSource\n ? matchesTarget({ targets: keepDataSources, binding, instance })\n : !matchesTarget({ targets: skipComponents, binding, instance });\n\n if (shouldRun) {\n return;\n }\n\n patches.push(patchProperty({ object: instance, name: 'configure', value: async () => {} }));\n };\n\n const originalRegisterDynamicBindings: (opts: IDynamicBindingsOptions) => Promise<void> =\n target['registerDynamicBindings'];\n const originalGetBootSequence: () => Array<{ name: string }> = target['getBootSequence'];\n\n const wrappedRegister = async (sweepOptions: IDynamicBindingsOptions): Promise<void> => {\n sweepsSeen += 1;\n const userBefore = sweepOptions.onBeforeConfigure;\n const userAfter = sweepOptions.onAfterConfigure;\n\n return originalRegisterDynamicBindings.call(target, {\n ...sweepOptions,\n onBeforeConfigure: async ({ binding }) => {\n await neutralise({ namespace: sweepOptions.namespace, binding });\n\n if (sweepOptions.namespace === BindingNamespaces.COMPONENT) {\n const instance = target.get<IConfigurable>({ key: binding.key, isOptional: true });\n configuringComponents.push(String(instance?.constructor?.name ?? binding.key));\n }\n\n await userBefore?.({ binding });\n },\n onAfterConfigure: async ({ binding, instance }) => {\n if (sweepOptions.namespace === BindingNamespaces.COMPONENT) {\n configuringComponents.pop();\n }\n\n await userAfter?.({ binding, instance });\n },\n });\n };\n\n patches.push(\n patchProperty({ object: target, name: 'registerDynamicBindings', value: wrappedRegister }),\n );\n patches.push(\n patchProperty({\n object: target,\n name: 'getBootSequence',\n value: () =>\n originalGetBootSequence.call(target).filter((step) => !skippedSteps.has(step.name)),\n }),\n );\n\n if (target['registerDynamicBindings'] !== wrappedRegister) {\n patches.forEach((patch) => patch.restore());\n fail(\n `The wrap of 'registerDynamicBindings' did not take effect | Refusing to boot against real infrastructure`,\n );\n }\n\n const configs = target['configs'];\n const originalBootChecks = configs.bootChecks;\n const originalBinding = originalBootChecks?.binding;\n configs.bootChecks = {\n ...originalBootChecks,\n binding: {\n allowManual: originalBinding?.allowManual ?? true,\n allowOverride: originalBinding?.allowOverride ?? true,\n doVerify: false,\n },\n };\n\n AuthorizationEnforcerRegistry.getInstance().reset();\n\n try {\n if (!target.isBound({ key: CoreBindings.APPLICATION_INSTANCE })) {\n target.init();\n }\n\n await target.initialize();\n\n const sweepsExpected = [\n ServerBootSteps.REGISTER_DATA_SOURCES,\n ServerBootSteps.REGISTER_COMPONENTS,\n ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n ].some((step) => !skippedSteps.has(step));\n\n if (sweepsExpected && sweepsSeen === 0) {\n fail(\n `The boot never went through 'registerDynamicBindings' | The wrap did not take effect, so datasources may have been configured`,\n );\n }\n\n if (verifyBindings) {\n BindingVerifier.assertResolve({\n container: target,\n namespaces: [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY],\n skip: skipBindings,\n scope: 'verifyBindings',\n });\n }\n\n if (\n !allowNoControllers &&\n target.findByTag({ tag: BindingNamespaces.CONTROLLER }).length === 0\n ) {\n fail(\n `The application registered no controller | A boot that registers nothing proves nothing: check the artifact index (for example the AutoArtifacts plugin under 'bun test'), or pass { allowNoControllers: true }`,\n );\n }\n\n if (routes) {\n assertNoDuplicateRoutes({ application: target });\n }\n\n return target;\n } catch (error) {\n const failing = configuringComponents.at(-1);\n\n if (failing) {\n target.logger\n .for('ApplicationBootAssertion.assert')\n .warn(\n `The boot failed inside component ${failing} | If it needs infrastructure, skipComponents: ['${failing}'] skips it, and skipBindings lists the services that depend on it`,\n );\n }\n\n throw error;\n } finally {\n for (const patch of patches.reverse()) {\n patch.restore();\n }\n\n if (originalBootChecks === undefined) {\n delete configs.bootChecks;\n } else {\n configs.bootChecks = originalBootChecks;\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"assert-application-boots.js","sourceRoot":"","sources":["../../../src/testing/assert-application-boots.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAwB,MAAM,qBAAqB,CAAC;AAE5E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EAEL,6BAA6B,EAE7B,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,YAAY,EACZ,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AA+D/B,8FAA8F;AAC9F,MAAM,eAAe,GAAG,CAAC,yBAAyB,EAAE,iBAAiB,CAAU,CAAC;AAEhF,MAAM,qBAAqB,GAAsB;IAC/C,eAAe,CAAC,eAAe;IAC/B,eAAe,CAAC,sBAAsB;CACvC,CAAC;AAEF,kFAAkF;AAClF,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAE/B,MAAM,kBAAkB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ACN,CAAC;YAED,MAAM,KAAK,CAAC;QACd,CAAC;gBAAS,CAAC;YACT,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;gBACtC,KAAK,CAAC,OAAO,EAAE,CAAC;YAClB,CAAC;YAED,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;gBACrC,OAAO,OAAO,CAAC,UAAU,CAAC;YAC5B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,UAAU,GAAG,kBAAkB,CAAC;YAC1C,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { BaseApplication } from '@/base/applications';\nimport { ServerBootSteps, type TServerBootStep } from '@/base/applications';\nimport type { IConfigurable, TClass } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { BindingVerifier, isClass } from '@venizia/ignis-inversion';\nimport {\n type AbstractRestController,\n AuthorizationEnforcerRegistry,\n type Binding,\n BindingNamespaces,\n BindingValueTypes,\n ControllerTransports,\n CoreBindings,\n MetadataRegistry,\n} from '@venizia/ignis-kernel';\n\n/** A class (matched against the instance's constructor) or a string (matched against the binding key or the class name). */\nexport type TBootProbeTarget = TClass<unknown> | string;\n\n/** Options of `ApplicationBootAssertion.assert`; each field narrows or relaxes what the boot probe runs and verifies. */\nexport interface IAssertApplicationBootsOptions {\n /**\n * Datasources whose real `configure()` runs. Every other datasource is bound and resolved but not\n * configured, so no connection is made. Close a kept one with `await application.stop()`.\n *\n * @default []\n */\n keepDataSources?: TBootProbeTarget[];\n\n /**\n * Components whose `configure()` (and so their `binding()`) is skipped, for the few that need\n * infrastructure. What a skipped component would have registered is not registered.\n *\n * @default []\n */\n skipComponents?: TBootProbeTarget[];\n\n /**\n * Boot steps that do not run, so a remote secrets provider is never contacted. A value REPLACES\n * the default; an unknown name rejects before anything boots.\n *\n * @default [ServerBootSteps.HYDRATE_SECRETS, ServerBootSteps.WIRE_SECRET_ROTATABLES]\n */\n skipSteps?: TServerBootStep[];\n\n /**\n * After boot, resolves every service and repository with the shared core of\n * `@venizia/ignis-inversion`, so an injection nobody references at boot still fails. An explicit value\n * wins over the application's own `bootChecks`, whose boot step is off for the run.\n *\n * @default true\n */\n verifyBindings?: boolean;\n\n /**\n * Services or repositories the verification leaves unresolved, for one whose constructor needs\n * infrastructure. A class (exact), a class name or a binding key. A name that matches nothing rejects.\n *\n * @default []\n */\n skipBindings?: TBootProbeTarget[];\n\n /**\n * Whether an application that registered no controller passes. Off, it fails: it proves nothing, for example when the artifact index was empty.\n *\n * @default false\n */\n allowNoControllers?: boolean;\n\n /**\n * This helper's own check that no method and path is mounted twice. IGNIS boot does not detect that.\n *\n * @default true\n */\n routes?: boolean;\n}\n\n/** The boot sequence is the contract; these two are what the helper wraps on one instance. */\nconst WRAPPED_METHODS = ['registerDynamicBindings', 'getBootSequence'] as const;\n\nconst DEFAULT_SKIPPED_STEPS: TServerBootStep[] = [\n ServerBootSteps.HYDRATE_SECRETS,\n ServerBootSteps.WIRE_SECRET_ROTATABLES,\n];\n\n/** Methods a route entry may carry that are middleware, not a mounted handler. */\nconst NON_ROUTE_METHOD = 'ALL';\n\nconst bootedApplications = new WeakSet<object>();\n\ninterface IProbeBinding {\n key: string;\n}\n\ninterface IDynamicBindingsOptions {\n namespace: string;\n onBeforeConfigure?: (opts: { binding: Binding<IConfigurable> }) => Promise<void>;\n onAfterConfigure?: (opts: {\n binding: Binding<IConfigurable>;\n instance: IConfigurable;\n }) => Promise<void>;\n}\n\n/** What the helper replaced, so every path puts it back. */\ninterface IPatch {\n restore: () => void;\n}\n\nconst matchesTarget = (opts: {\n targets: TBootProbeTarget[];\n binding: IProbeBinding;\n instance: IConfigurable;\n}): boolean => {\n const { targets, binding, instance } = opts;\n const className: string | undefined = instance?.constructor?.name;\n\n return targets.some((target) =>\n typeof target === 'string'\n ? target === binding.key || target === className\n : instance?.constructor === target,\n );\n};\n\nconst fail = (message: string): never => {\n throw getError({ message: `[ApplicationBootAssertion.assert] ${message}` });\n};\n\n/** Replaces `object[name]` and returns the way back, even when `name` was inherited. */\nconst patchProperty = (opts: { object: object; name: string; value: unknown }): IPatch => {\n const { object, name, value } = opts;\n const descriptor = Object.getOwnPropertyDescriptor(object, name);\n\n Object.defineProperty(object, name, { value, configurable: true, writable: true });\n\n return {\n restore: () => {\n if (descriptor) {\n Object.defineProperty(object, name, descriptor);\n\n return;\n }\n\n Reflect.deleteProperty(object, name);\n },\n };\n};\n\nconst normalizePath = (path: string): string => {\n const withParams = path.replace(/:[A-Za-z0-9_]+/g, ':param').replace(/\\/{2,}/g, '/');\n\n return withParams.length > 1 ? withParams.replace(/\\/$/, '') : withParams;\n};\n\n/** The helper's own check: IGNIS mounts a method and path twice without complaint, and the first one wins. */\nconst assertNoDuplicateRoutes = (opts: { application: BaseApplication }): void => {\n const { application } = opts;\n // signature -> controller key -> how many times that controller declares it\n const mounted = new Map<string, Map<string, number>>();\n\n const record = (signature: string, key: string, declarations: number): void => {\n const owners = mounted.get(signature) ?? new Map<string, number>();\n owners.set(key, Math.max(owners.get(key) ?? 0, declarations));\n mounted.set(signature, owners);\n };\n\n for (const binding of application.findByTag<AbstractRestController>({\n tag: BindingNamespaces.CONTROLLER,\n })) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n const metadata = target\n ? MetadataRegistry.getInstance().getControllerMetadata({ target })\n : undefined;\n\n if (!metadata?.path || metadata.transport === ControllerTransports.GRPC) {\n continue;\n }\n\n // A bound controller is a class; this narrows it for the `prototype` read below.\n if (!isClass(target)) {\n continue;\n }\n\n const instance = application.get<AbstractRestController>({\n key: binding.key,\n isOptional: true,\n });\n\n // Hono's `routes` has one entry PER HANDLER (a validator, an authenticate and the handler of one route are three\n // entries with the same method and path), so an entry is not a declaration: a controller counts once per signature.\n for (const route of instance?.getRouter().routes ?? []) {\n if (route.method === NON_ROUTE_METHOD) {\n continue;\n }\n\n record(`${route.method} ${normalizePath(`${metadata.path}/${route.path}`)}`, binding.key, 1);\n }\n\n // What the router cannot show: one controller declaring a method and path twice. Decorated routes are one\n // metadata entry per declaration, so those are counted there.\n const declared = new Map<string, number>();\n\n for (const route of MetadataRegistry.getInstance()\n .getRoutes({ target: target.prototype })\n ?.values() ?? []) {\n const signature = `${String(route.method).toUpperCase()} ${normalizePath(`${metadata.path}/${route.path}`)}`;\n declared.set(signature, (declared.get(signature) ?? 0) + 1);\n }\n\n for (const [signature, declarations] of declared) {\n record(signature, binding.key, declarations);\n }\n }\n\n const duplicates = [...mounted.entries()].filter(\n ([, owners]) =>\n owners.size > 1 || [...owners.values()].some((declarations) => declarations > 1),\n );\n\n if (duplicates.length === 0) {\n return;\n }\n\n const lines = duplicates.map(\n ([signature, owners]) =>\n `${signature} | controllers: ${[...owners]\n .map(([key, declarations]) =>\n declarations > 1 ? `${key} (declared ${declarations} times)` : key,\n )\n .join(', ')}`,\n );\n fail(\n `${duplicates.length} route(s) are mounted more than once, and only the first one answers | ${lines.join(' ; ')} | This is the helper's own check (IGNIS boot does not detect it); pass { routes: false } to turn it off`,\n );\n};\n\n/**\n * Proves an IGNIS application boots, without a datasource connection, a socket or a secrets provider:\n * it runs the application's own boot sequence (`init()` then `initialize()`) and never calls `start()`,\n * so no socket is opened and no post-start hook runs.\n *\n * Datasources are bound and resolved but not configured, unless named in `keepDataSources`; the\n * secrets steps are skipped; every other step and every component runs as in a real boot. A component\n * that opens Redis, Kafka or S3 in `binding()` therefore runs for real: name it in `skipComponents`.\n * `setupMiddlewares()` is not run: it is the application's own start-time step, user code that may open\n * connections, and the probe cannot know it is free of side effects. The framework's default stack (CORS, body\n * limit, request id) is a boot step of `initialize()`, so an invalid `configs.middlewares` value still fails here.\n * When the boot fails inside a component, one warning names it; the rejection is still the original error. When the\n * boot fails, the rejection is the original error. The application stays booted and is returned;\n * a failed boot leaves a half-booted instance, so build a new one rather than reuse it.\n *\n * It wraps `registerDynamicBindings` and `getBootSequence` on THIS instance only (an application's\n * own override of either still runs) and restores them whatever happens.\n *\n * It owns the process-wide `AuthorizationEnforcerRegistry` for the duration of the check: it resets it before it\n * boots, so a second boot in the same process (another probe, or a test boot after this one) does not fail with\n * `Enforcer already registered`. An application still running in the same process loses its enforcer registrations\n * and its authorize options, so its requests are then decided by the no-enforcer default (deny unless configured\n * otherwise): do not run the probe in a process that serves an application.\n *\n * @example\n * ```typescript\n * import { ApplicationBootAssertion } from '@venizia/ignis/testing';\n * import { test } from 'bun:test';\n * import { Application } from './application';\n *\n * test('the application boots offline', async () => {\n * await ApplicationBootAssertion.assert({\n * application: () => new Application({ scope: 'Application', config: { host: '127.0.0.1', port: 0, path: { base: '/', isStrict: true } } }),\n * options: { skipComponents: ['MailComponent'], allowNoControllers: true },\n * });\n * });\n * ```\n */\nexport class ApplicationBootAssertion {\n static async assert<Application extends BaseApplication>(opts: {\n application: Application | (() => Application | Promise<Application>);\n options?: IAssertApplicationBootsOptions;\n }): Promise<Application> {\n const { application, options = {} } = opts;\n const {\n keepDataSources = [],\n skipComponents = [],\n skipSteps = DEFAULT_SKIPPED_STEPS,\n verifyBindings = true,\n skipBindings = [],\n allowNoControllers = false,\n routes = true,\n } = options;\n\n for (const step of skipSteps) {\n if (!ServerBootSteps.isValid(step)) {\n fail(\n `Unknown boot step in skipSteps: '${String(step)}' | Expected one of: ${ServerBootSteps.values().join(', ')}`,\n );\n }\n }\n\n let target: Application;\n\n if (typeof application === 'function') {\n const built = await application();\n target = built;\n } else {\n target = application;\n }\n\n if (\n bootedApplications.has(target) ||\n Object.keys(target['registeredBindings'] ?? {}).length > 0\n ) {\n fail(\n `This application instance was already booted | A failed or finished boot leaves registrations behind, so build a new instance (pass a factory) for each call`,\n );\n }\n\n bootedApplications.add(target);\n\n for (const name of WRAPPED_METHODS) {\n if (typeof target[name] !== 'function') {\n fail(\n `The kernel method '${name}' is missing on this application | The helper cannot keep a boot offline without it, so it refuses to boot`,\n );\n }\n }\n\n const skippedSteps = new Set<string>(skipSteps);\n const patches: IPatch[] = [];\n let sweepsSeen = 0;\n // The components whose `configure()` is running, innermost last: when the boot rejects, the last one is where it failed.\n const configuringComponents: string[] = [];\n\n const neutralise = async (entry: {\n namespace: string;\n binding: Binding<IConfigurable>;\n }): Promise<void> => {\n const { namespace, binding } = entry;\n const isDataSource = namespace === BindingNamespaces.DATASOURCE;\n const isComponent = namespace === BindingNamespaces.COMPONENT;\n\n if (!isDataSource && !isComponent) {\n return;\n }\n\n const instance = target.get<IConfigurable>({ key: binding.key, isOptional: false });\n\n if (typeof instance?.configure !== 'function') {\n return;\n }\n\n const shouldRun = isDataSource\n ? matchesTarget({ targets: keepDataSources, binding, instance })\n : !matchesTarget({ targets: skipComponents, binding, instance });\n\n if (shouldRun) {\n return;\n }\n\n patches.push(patchProperty({ object: instance, name: 'configure', value: async () => {} }));\n };\n\n const originalRegisterDynamicBindings: (opts: IDynamicBindingsOptions) => Promise<void> =\n target['registerDynamicBindings'];\n const originalGetBootSequence: () => Array<{ name: string }> = target['getBootSequence'];\n\n const wrappedRegister = async (sweepOptions: IDynamicBindingsOptions): Promise<void> => {\n sweepsSeen += 1;\n const userBefore = sweepOptions.onBeforeConfigure;\n const userAfter = sweepOptions.onAfterConfigure;\n\n return originalRegisterDynamicBindings.call(target, {\n ...sweepOptions,\n onBeforeConfigure: async ({ binding }) => {\n await neutralise({ namespace: sweepOptions.namespace, binding });\n\n if (sweepOptions.namespace === BindingNamespaces.COMPONENT) {\n const instance = target.get<IConfigurable>({ key: binding.key, isOptional: true });\n configuringComponents.push(String(instance?.constructor?.name ?? binding.key));\n }\n\n await userBefore?.({ binding });\n },\n onAfterConfigure: async ({ binding, instance }) => {\n if (sweepOptions.namespace === BindingNamespaces.COMPONENT) {\n configuringComponents.pop();\n }\n\n await userAfter?.({ binding, instance });\n },\n });\n };\n\n patches.push(\n patchProperty({ object: target, name: 'registerDynamicBindings', value: wrappedRegister }),\n );\n patches.push(\n patchProperty({\n object: target,\n name: 'getBootSequence',\n value: () =>\n originalGetBootSequence.call(target).filter((step) => !skippedSteps.has(step.name)),\n }),\n );\n\n if (target['registerDynamicBindings'] !== wrappedRegister) {\n patches.forEach((patch) => patch.restore());\n fail(\n `The wrap of 'registerDynamicBindings' did not take effect | Refusing to boot against real infrastructure`,\n );\n }\n\n const configs = target['configs'];\n const originalBootChecks = configs.bootChecks;\n const originalBinding = originalBootChecks?.binding;\n configs.bootChecks = {\n ...originalBootChecks,\n binding: {\n allowManual: originalBinding?.allowManual ?? true,\n allowOverride: originalBinding?.allowOverride ?? true,\n doVerify: false,\n },\n };\n\n AuthorizationEnforcerRegistry.getInstance().reset();\n\n try {\n if (!target.isBound({ key: CoreBindings.APPLICATION_INSTANCE })) {\n target.init();\n }\n\n await target.initialize();\n\n const sweepsExpected = [\n ServerBootSteps.REGISTER_DATA_SOURCES,\n ServerBootSteps.REGISTER_COMPONENTS,\n ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n ].some((step) => !skippedSteps.has(step));\n\n if (sweepsExpected && sweepsSeen === 0) {\n fail(\n `The boot never went through 'registerDynamicBindings' | The wrap did not take effect, so datasources may have been configured`,\n );\n }\n\n if (verifyBindings) {\n BindingVerifier.assertResolve({\n container: target,\n namespaces: [BindingNamespaces.SERVICE, BindingNamespaces.REPOSITORY],\n skip: skipBindings,\n scope: 'verifyBindings',\n });\n }\n\n if (\n !allowNoControllers &&\n target.findByTag({ tag: BindingNamespaces.CONTROLLER }).length === 0\n ) {\n fail(\n `The application registered no controller | A boot that registers nothing proves nothing: check the artifact index (for example the AutoArtifacts plugin under 'bun test'), or pass { allowNoControllers: true }`,\n );\n }\n\n if (routes) {\n assertNoDuplicateRoutes({ application: target });\n }\n\n return target;\n } catch (error) {\n const failing = configuringComponents.at(-1);\n\n if (failing) {\n target.logger\n .for('ApplicationBootAssertion.assert')\n .warn(\n `The boot failed inside component ${failing} | If it needs infrastructure, skipComponents: ['${failing}'] skips it, and skipBindings lists the services that depend on it`,\n );\n }\n\n throw error;\n } finally {\n for (const patch of patches.reverse()) {\n patch.restore();\n }\n\n if (originalBootChecks === undefined) {\n delete configs.bootChecks;\n } else {\n configs.bootChecks = originalBootChecks;\n }\n }\n }\n}\n"]}
|
|
@@ -14,17 +14,17 @@
|
|
|
14
14
|
"dependencies": {
|
|
15
15
|
"@hono/zod-openapi": "^1.6.3",
|
|
16
16
|
"@scalar/hono-api-reference": "^0.12.13",
|
|
17
|
-
"@venizia/ignis": "0.5.0-
|
|
18
|
-
"@venizia/ignis-boot": "0.5.0-
|
|
19
|
-
"@venizia/ignis-helpers": "0.5.0-
|
|
17
|
+
"@venizia/ignis": "0.5.0-10",
|
|
18
|
+
"@venizia/ignis-boot": "0.5.0-6",
|
|
19
|
+
"@venizia/ignis-helpers": "0.5.0-6",
|
|
20
20
|
"hono": "^4.13.13",
|
|
21
21
|
"winston": "^3.19.0",
|
|
22
22
|
"winston-daily-rotate-file": "^5.0.0",
|
|
23
23
|
"winston-transport": "^4.9.0"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"@types/bun": "^1.4.
|
|
27
|
-
"@venizia/dev-configs": "0.5.0-
|
|
26
|
+
"@types/bun": "^1.4.5",
|
|
27
|
+
"@venizia/dev-configs": "0.5.0-6",
|
|
28
28
|
"eslint": "^10.13.0",
|
|
29
29
|
"oxlint": "1.89.0",
|
|
30
30
|
"oxlint-tsgolint": "7.0.2004",
|
|
@@ -3,16 +3,16 @@
|
|
|
3
3
|
"summary": "A library other IGNIS apps import: services backend apps bind (exports to src, #src imports).",
|
|
4
4
|
"dependencies": {},
|
|
5
5
|
"devDependencies": {
|
|
6
|
-
"@types/bun": "^1.4.
|
|
7
|
-
"@venizia/dev-configs": "0.5.0-
|
|
8
|
-
"@venizia/ignis": "0.5.0-
|
|
6
|
+
"@types/bun": "^1.4.5",
|
|
7
|
+
"@venizia/dev-configs": "0.5.0-6",
|
|
8
|
+
"@venizia/ignis": "0.5.0-10",
|
|
9
9
|
"eslint": "^10.13.0",
|
|
10
10
|
"oxlint": "1.89.0",
|
|
11
11
|
"oxlint-tsgolint": "7.0.2004",
|
|
12
12
|
"typescript": "^6.0.3"
|
|
13
13
|
},
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"@venizia/ignis": "0.5.0-
|
|
15
|
+
"@venizia/ignis": "0.5.0-10"
|
|
16
16
|
},
|
|
17
17
|
"scripts": {
|
|
18
18
|
"typecheck": "bun check",
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
"summary": "A package of plain code that backend and frontend apps both import; it depends on no framework.",
|
|
4
4
|
"dependencies": {},
|
|
5
5
|
"devDependencies": {
|
|
6
|
-
"@types/bun": "^1.4.
|
|
7
|
-
"@venizia/dev-configs": "0.5.0-
|
|
6
|
+
"@types/bun": "^1.4.5",
|
|
7
|
+
"@venizia/dev-configs": "0.5.0-6",
|
|
8
8
|
"eslint": "^10.13.0",
|
|
9
9
|
"oxlint": "1.89.0",
|
|
10
10
|
"oxlint-tsgolint": "7.0.2004",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@venizia/ignis",
|
|
3
|
-
"version": "0.5.0-
|
|
3
|
+
"version": "0.5.0-10",
|
|
4
4
|
"description": "TypeScript server framework with decorator-based DI, the repository pattern and a component system, on Hono. Features auto-generated OpenAPI docs, Drizzle ORM type-safe SQL, JWT/Basic authentication, Casbin authorization, convention-based bootstrapping, and pluggable components for health checks, Swagger UI, mail, Socket.IO, and static assets. Built for Bun.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"access-control",
|
|
@@ -134,11 +134,11 @@
|
|
|
134
134
|
"force-update": "sh ../../scripts/build/force-update.sh"
|
|
135
135
|
},
|
|
136
136
|
"dependencies": {
|
|
137
|
-
"@venizia/ignis-connectors": "0.5.0-
|
|
138
|
-
"@venizia/ignis-filter": "0.5.0-
|
|
139
|
-
"@venizia/ignis-helpers": "0.5.0-
|
|
140
|
-
"@venizia/ignis-inversion": "0.5.0-
|
|
141
|
-
"@venizia/ignis-kernel": "0.5.0-
|
|
137
|
+
"@venizia/ignis-connectors": "0.5.0-8",
|
|
138
|
+
"@venizia/ignis-filter": "0.5.0-3",
|
|
139
|
+
"@venizia/ignis-helpers": "0.5.0-6",
|
|
140
|
+
"@venizia/ignis-inversion": "0.5.0-3",
|
|
141
|
+
"@venizia/ignis-kernel": "0.5.0-7",
|
|
142
142
|
"reflect-metadata": "^0.2.2"
|
|
143
143
|
},
|
|
144
144
|
"devDependencies": {
|
|
@@ -148,11 +148,11 @@
|
|
|
148
148
|
"@hono/swagger-ui": "^0.6.1",
|
|
149
149
|
"@libsql/client": "^0.17.4",
|
|
150
150
|
"@socket.io/bun-engine": "^0.1.2",
|
|
151
|
-
"@types/bun": "^1.4.
|
|
151
|
+
"@types/bun": "^1.4.5",
|
|
152
152
|
"@types/nodemailer": "^8.0.2",
|
|
153
153
|
"@types/pg": "^8.23.1",
|
|
154
|
-
"@venizia/dev-configs": "0.5.0-
|
|
155
|
-
"@venizia/ignis-boot": "0.5.0-
|
|
154
|
+
"@venizia/dev-configs": "0.5.0-6",
|
|
155
|
+
"@venizia/ignis-boot": "0.5.0-6",
|
|
156
156
|
"casbin": "^5.51.1",
|
|
157
157
|
"eslint": "^10.13.0",
|
|
158
158
|
"meilisearch": "^0.62.0",
|