@venizia/ignis 0.4.8-10 → 0.4.8-12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/esm/components/auth/authenticate/component.js +1 -1
  2. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  3. package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +1 -1
  4. package/dist/esm/components/auth/authenticate/controllers/factory.js +1 -1
  5. package/dist/esm/components/auth/authenticate/controllers/factory.js.map +1 -1
  6. package/dist/esm/components/mail/common/types/queue.d.ts +8 -4
  7. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  8. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.d.ts +1 -1
  9. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +2 -16
  10. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  11. package/dist/esm/components/static-asset/common/constants.d.ts +43 -24
  12. package/dist/esm/components/static-asset/common/constants.js +74 -47
  13. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  14. package/dist/esm/components/static-asset/common/errors.d.ts +11 -43
  15. package/dist/esm/components/static-asset/common/errors.js +11 -40
  16. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  17. package/dist/esm/components/static-asset/common/index.d.ts +1 -1
  18. package/dist/esm/components/static-asset/common/index.js +1 -1
  19. package/dist/esm/components/static-asset/common/index.js.map +1 -1
  20. package/dist/esm/components/static-asset/common/keys.d.ts +10 -2
  21. package/dist/esm/components/static-asset/common/keys.js +10 -2
  22. package/dist/esm/components/static-asset/common/keys.js.map +1 -1
  23. package/dist/esm/components/static-asset/common/types.d.ts +196 -141
  24. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  25. package/dist/esm/components/static-asset/common/validation.d.ts +10 -0
  26. package/dist/esm/components/static-asset/common/validation.js +8 -0
  27. package/dist/esm/components/static-asset/common/validation.js.map +1 -0
  28. package/dist/esm/components/static-asset/component.d.ts +4 -2
  29. package/dist/esm/components/static-asset/component.js +26 -31
  30. package/dist/esm/components/static-asset/component.js.map +1 -1
  31. package/dist/esm/components/static-asset/controller/factory.d.ts +188 -66
  32. package/dist/esm/components/static-asset/controller/factory.js +34 -912
  33. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  34. package/dist/esm/components/static-asset/controller/routes/context.d.ts +61 -0
  35. package/dist/esm/components/static-asset/controller/routes/context.js +45 -0
  36. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -0
  37. package/dist/esm/components/static-asset/controller/routes/definition.d.ts +40 -0
  38. package/dist/esm/components/static-asset/controller/routes/definition.js +74 -0
  39. package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -0
  40. package/dist/esm/components/static-asset/controller/routes/direct-upload.d.ts +3 -0
  41. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +125 -0
  42. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -0
  43. package/dist/esm/components/static-asset/controller/routes/labels.d.ts +16 -0
  44. package/dist/esm/components/static-asset/controller/routes/labels.js +19 -0
  45. package/dist/esm/components/static-asset/controller/routes/labels.js.map +1 -0
  46. package/dist/esm/components/static-asset/controller/routes/objects.d.ts +7 -0
  47. package/dist/esm/components/static-asset/controller/routes/objects.js +193 -0
  48. package/dist/esm/components/static-asset/controller/routes/objects.js.map +1 -0
  49. package/dist/esm/components/static-asset/controller/routes/serve.d.ts +17 -0
  50. package/dist/esm/components/static-asset/controller/routes/serve.js +127 -0
  51. package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -0
  52. package/dist/esm/components/static-asset/controller/routes/table.d.ts +12 -0
  53. package/dist/esm/components/static-asset/controller/routes/table.js +52 -0
  54. package/dist/esm/components/static-asset/controller/routes/table.js.map +1 -0
  55. package/dist/esm/components/static-asset/controller/routes/upload.d.ts +10 -0
  56. package/dist/esm/components/static-asset/controller/routes/upload.js +174 -0
  57. package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -0
  58. package/dist/esm/components/static-asset/index.d.ts +2 -1
  59. package/dist/esm/components/static-asset/index.js +2 -1
  60. package/dist/esm/components/static-asset/index.js.map +1 -1
  61. package/dist/esm/components/static-asset/models/base.model.d.ts +4 -4
  62. package/dist/esm/components/static-asset/models/base.model.js.map +1 -1
  63. package/dist/esm/components/static-asset/services/commitment.service.d.ts +73 -0
  64. package/dist/esm/components/static-asset/services/commitment.service.js +141 -0
  65. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -0
  66. package/dist/esm/components/static-asset/services/index.d.ts +3 -0
  67. package/dist/esm/components/static-asset/services/index.js +3 -0
  68. package/dist/esm/components/static-asset/services/index.js.map +1 -0
  69. package/dist/esm/components/static-asset/services/policy.service.d.ts +41 -0
  70. package/dist/esm/components/static-asset/services/policy.service.js +84 -0
  71. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -0
  72. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +26 -0
  73. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +78 -0
  74. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -0
  75. package/dist/esm/components/static-asset/utilities/entry.utility.d.ts +69 -0
  76. package/dist/esm/components/static-asset/utilities/entry.utility.js +153 -0
  77. package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -0
  78. package/dist/esm/components/static-asset/utilities/index.d.ts +5 -0
  79. package/dist/esm/components/static-asset/utilities/index.js +5 -0
  80. package/dist/esm/components/static-asset/utilities/index.js.map +1 -0
  81. package/dist/esm/components/static-asset/{ingest.d.ts → utilities/ingest.utility.d.ts} +5 -5
  82. package/dist/esm/components/static-asset/{ingest.js → utilities/ingest.utility.js} +12 -10
  83. package/dist/esm/components/static-asset/utilities/ingest.utility.js.map +1 -0
  84. package/dist/esm/components/static-asset/{controller/key-scope.d.ts → utilities/key-scope.utility.d.ts} +21 -2
  85. package/dist/esm/components/static-asset/utilities/key-scope.utility.js +74 -0
  86. package/dist/esm/components/static-asset/utilities/key-scope.utility.js.map +1 -0
  87. package/dist/esm/components/static-asset/{controller/meta-link.d.ts → utilities/meta-link.utility.d.ts} +4 -4
  88. package/dist/esm/components/static-asset/{controller/meta-link.js → utilities/meta-link.utility.js} +10 -10
  89. package/dist/esm/components/static-asset/utilities/meta-link.utility.js.map +1 -0
  90. package/dist/esm/components/static-asset/utilities/object-link.utility.d.ts +16 -0
  91. package/dist/esm/components/static-asset/utilities/object-link.utility.js +20 -0
  92. package/dist/esm/components/static-asset/utilities/object-link.utility.js.map +1 -0
  93. package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +44 -0
  94. package/dist/esm/components/static-asset/utilities/route-options.utility.js +85 -0
  95. package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -0
  96. package/dist/esm/components/static-asset/utilities/toggle.utility.d.ts +13 -0
  97. package/dist/esm/components/static-asset/utilities/toggle.utility.js +16 -0
  98. package/dist/esm/components/static-asset/utilities/toggle.utility.js.map +1 -0
  99. package/dist/presets/app/preset.json +4 -4
  100. package/dist/presets/lib/preset.json +3 -3
  101. package/dist/presets/shared/preset.json +1 -1
  102. package/package.json +6 -6
  103. package/dist/esm/components/static-asset/common/commit-token.d.ts +0 -28
  104. package/dist/esm/components/static-asset/common/commit-token.js +0 -48
  105. package/dist/esm/components/static-asset/common/commit-token.js.map +0 -1
  106. package/dist/esm/components/static-asset/controller/base.definition.d.ts +0 -30
  107. package/dist/esm/components/static-asset/controller/base.definition.js +0 -307
  108. package/dist/esm/components/static-asset/controller/base.definition.js.map +0 -1
  109. package/dist/esm/components/static-asset/controller/key-scope.js +0 -41
  110. package/dist/esm/components/static-asset/controller/key-scope.js.map +0 -1
  111. package/dist/esm/components/static-asset/controller/meta-link.js.map +0 -1
  112. package/dist/esm/components/static-asset/controller/route-options.d.ts +0 -29
  113. package/dist/esm/components/static-asset/controller/route-options.js +0 -47
  114. package/dist/esm/components/static-asset/controller/route-options.js.map +0 -1
  115. package/dist/esm/components/static-asset/ingest.js.map +0 -1
@@ -292,7 +292,7 @@ let AuthenticateComponent = AuthenticateComponent_1 = class AuthenticateComponen
292
292
  message: '[defineControllers] Auth controller requires jwtOptions to be configured',
293
293
  });
294
294
  }
295
- const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);
295
+ const AuthController = AuthControllerFactory.build(restOptions.controllerOpts);
296
296
  this.application.controller(AuthController);
297
297
  this.logger.for(this.defineControllers.name).info('Auth controller registered');
298
298
  }
@@ -1 +1 @@
1
- {"version":3,"file":"component.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/component.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,8BAA8B,EAC9B,aAAa,EACb,UAAU,EACV,YAAY,EAKZ,MAAM,EAEN,aAAa,EACb,cAAc,EACd,SAAS,EACT,gBAAgB,GAKjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EAAE,sBAAsB,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,CAAC;AAE9E,MAAM,cAAc,GAAG,gBAAgB,CAAC;AAExC,6LAA6L;AAC7L,IAAa,qBAAqB,6BAAlC,MAAa,qBA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UAAU,EAAE,CAAC;YAChB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,0EAA0E;aACpF,CAAC,CAAC;QACL,CAAC;QAED,MAAM,cAAc,GAAG,qBAAqB,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC;QAChF,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE5C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AA7VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA6VjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n AbstractBearerTokenService,\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { JWKSUrlPolicy } from './services/jwks-url-policy';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: issuerOpts,\n pinnedAlgorithms: [issuerOpts.algorithm],\n });\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: verifierOpts,\n });\n\n JWKSUrlPolicy.assertUrl({\n scope: 'defineJWKSAuth',\n label: 'jwksUrl',\n url: verifierOpts.jwksUrl,\n hosts: verifierOpts.jwks?.hosts?.http,\n });\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n // A caller's key set decides who may call: https, loopback, or a host listed in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveHttpHosts({\n scope: 'defineServiceAuth',\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n\n for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {\n JWKSUrlPolicy.assertUrl({\n scope: 'defineServiceAuth',\n label: `callers[${JSON.stringify(caller)}].jwksUrl`,\n url: typeof entry === 'string' ? entry : entry.jwksUrl,\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.define(restOptions.controllerOpts);\n this.application.controller(AuthController);\n\n this.logger.for(this.defineControllers.name).info('Auth controller registered');\n }\n\n defineOAuth2() {\n // TODO Implement OAuth2\n }\n}\n"]}
1
+ {"version":3,"file":"component.js","sourceRoot":"","sources":["../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C,IAAI,CAAC,4BAA4B,CAAC,CAAC;IAClF,CAAC;IAED,YAAY;QACV,wBAAwB;IAC1B,CAAC;CACF,CAAA;AA7VY,qBAAqB;IAE7B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,oBAAoB,EAAE,CAAC,CAAA;;GAF1C,qBAAqB,CA6VjC","sourcesContent":["import type { BaseApplication } from '@/base/applications/base';\nimport { type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { Binding } from '@venizia/ignis-inversion';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationStrategyRegistry,\n BaseComponent,\n controller,\n CoreBindings,\n type IAuthenticateOptions,\n type IJWKSIssuerOptions,\n type IJWKSVerifierOptions,\n type IJWSTokenServiceOptions,\n inject,\n type IServiceAuthOptions,\n JOSEStandards,\n JWKSKeyFormats,\n JWKSModes,\n ServiceAssertion,\n type TAuthenticationRestOptions,\n type TBasicTokenServiceOptions,\n type TJWKSTokenServiceOptions,\n type TJWTTokenServiceOptions,\n} from '@venizia/ignis-kernel';\nimport { AuthControllerFactory, JWKSController } from './controllers';\nimport { ServiceCertsController } from './controllers/service-certs';\nimport {\n AbstractBearerTokenService,\n BasicTokenService,\n JWKSIssuerTokenService,\n JWKSVerifierTokenService,\n JWSTokenService,\n} from './services';\nimport { JoseLoader } from './services/jose-loader';\nimport { JWKSUrlPolicy } from './services/jwks-url-policy';\nimport { ServiceAssertionSignerService } from './services/service/signer.service';\nimport { ServiceAssertionVerifierService } from './services/service/verifier.service';\nimport { ServiceAuthenticationStrategy } from './strategies/service.strategy';\n\nconst DEFAULT_SECRET = 'unknown_secret';\n\n/** Registers the authentication services and strategies from the options bound under `AuthenticateBindingKeys`. Throws at binding time unless JWT, basic or service options are provided. */\nexport class AuthenticateComponent extends BaseComponent {\n constructor(\n @inject({ key: CoreBindings.APPLICATION_INSTANCE }) private application: BaseApplication,\n ) {\n super({\n scope: AuthenticateComponent.name,\n initDefault: { enable: true, container: application },\n bindings: {\n [AuthenticateBindingKeys.REST_OPTIONS]: Binding.bind<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n }).toValue({ useAuthController: false }),\n },\n });\n }\n\n override binding(): ValueOrPromise<void> {\n const jwtOptions = this.application.get<TJWTTokenServiceOptions>({\n key: AuthenticateBindingKeys.JWT_OPTIONS,\n isOptional: true,\n });\n const basicOptions = this.application.get<TBasicTokenServiceOptions>({\n key: AuthenticateBindingKeys.BASIC_OPTIONS,\n isOptional: true,\n });\n const restOptions = this.application.get<TAuthenticationRestOptions>({\n key: AuthenticateBindingKeys.REST_OPTIONS,\n isOptional: true,\n });\n const serviceOptions = this.application.get<IServiceAuthOptions>({\n key: AuthenticateBindingKeys.SERVICE_OPTIONS,\n isOptional: true,\n });\n\n // A service that only VERIFIES assertions needs neither jwt nor basic - and that application,\n // an IGNIS app consuming no user tokens at all, is exactly what the service strategy is for.\n if (!jwtOptions && !basicOptions && !serviceOptions) {\n throw getError({\n message:\n '[AuthenticateComponent] At least one of jwtOptions, basicOptions or serviceOptions must be provided',\n });\n }\n\n const options: IAuthenticateOptions = { restOptions, jwtOptions, basicOptions, serviceOptions };\n\n if (jwtOptions) {\n switch (jwtOptions.standard) {\n case JOSEStandards.JWS: {\n this.defineJWSAuth({ options: jwtOptions.options });\n break;\n }\n case JOSEStandards.JWKS: {\n this.defineJWKSAuth({ options: jwtOptions.options });\n break;\n }\n default: {\n throw getError({\n message: `[AuthenticateComponent] Unknown JOSE standard: ${(jwtOptions as any).standard}`,\n });\n }\n }\n }\n\n this.defineBasicAuth({ basicOptions });\n this.defineServiceAuth({ serviceOptions });\n\n this.defineControllers({ options });\n\n this.defineOAuth2();\n\n return this.preloadJose({ options });\n }\n\n /**\n * Loads `jose` at boot when a configured service signs or verifies with it, so a missing or broken\n * install fails the boot instead of answering every token check with a 401.\n */\n private async preloadJose(opts: { options: IAuthenticateOptions }): Promise<void> {\n const { jwtOptions, serviceOptions } = opts.options;\n\n if (!jwtOptions && !serviceOptions) {\n return;\n }\n\n try {\n await JoseLoader.load();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n this.logger.for(this.preloadJose.name).error(\"Failed to load 'jose' | Error: %s\", reason);\n\n throw getError({\n message: `[AuthenticateComponent] Cannot load 'jose', which JWT and service authentication need. Please install it | Error: ${reason}`,\n cause: error,\n });\n }\n }\n\n private defineJWSAuth(opts: { options: IJWSTokenServiceOptions }): void {\n const { options: jwsOptions } = opts;\n\n const { jwtSecret, getTokenExpiresFn } = jwsOptions;\n\n if (!jwtSecret || jwtSecret === DEFAULT_SECRET) {\n throw getError({\n message: `[defineJWSAuth] Invalid jwtSecret | Provided: ${jwtSecret}`,\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n message: '[defineJWSAuth] getTokenExpiresFn is required',\n });\n }\n\n // The boot refuses a configuration without claims, and a service refuses the same when built.\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWSAuth',\n options: jwsOptions,\n pinnedAlgorithms: [jwsOptions.headerAlgorithm ?? 'HS256'],\n });\n\n JWSTokenService.assertSecretStrength({ scope: 'defineJWSAuth', secret: jwtSecret });\n\n this.application\n .bind<IJWSTokenServiceOptions>({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n .toValue(jwsOptions);\n this.application.service(JWSTokenService);\n\n this.logger.for(this.defineJWSAuth.name).info('JWS authentication configured');\n }\n\n private defineJWKSAuth(opts: { options: TJWKSTokenServiceOptions }): void {\n const { options: jwksOptions } = opts;\n\n switch (jwksOptions.mode) {\n case JWKSModes.ISSUER: {\n const issuerOpts = jwksOptions;\n\n if (!issuerOpts.keys?.private || !issuerOpts.keys?.public) {\n throw getError({\n message: '[defineJWKSAuth] keys.private and keys.public are required for issuer mode',\n });\n }\n\n if (!issuerOpts.keys?.format || !JWKSKeyFormats.isValid(issuerOpts.keys.format)) {\n throw getError({\n message: `[defineJWKSAuth] keys.format is required and must be one of: ${[...JWKSKeyFormats.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (!issuerOpts.kid) {\n throw getError({ message: '[defineJWKSAuth] kid is required for issuer mode' });\n }\n\n if (!issuerOpts.getTokenExpiresFn) {\n throw getError({\n message: '[defineJWKSAuth] getTokenExpiresFn is required for issuer mode',\n });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: issuerOpts,\n pinnedAlgorithms: [issuerOpts.algorithm],\n });\n\n this.application\n .bind<IJWKSIssuerOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(issuerOpts);\n this.application.service(JWKSIssuerTokenService);\n\n // Path depends on a runtime option, so @controller can't be applied statically — decorate here instead.\n Reflect.decorate(\n [controller({ path: issuerOpts?.rest?.path ?? '/certs' })],\n JWKSController,\n );\n this.application.controller(JWKSController);\n\n this.logger\n .for(this.defineJWKSAuth.name)\n .info('JWKS issuer configured with /certs endpoint');\n break;\n }\n\n case JWKSModes.VERIFIER: {\n const verifierOpts = jwksOptions;\n\n if (!verifierOpts.jwksUrl) {\n throw getError({ message: '[defineJWKSAuth] jwksUrl is required for verifier mode' });\n }\n\n AbstractBearerTokenService.resolveClaimsConfig({\n scope: 'defineJWKSAuth',\n options: verifierOpts,\n });\n\n JWKSUrlPolicy.assertUrl({\n scope: 'defineJWKSAuth',\n label: 'jwksUrl',\n url: verifierOpts.jwksUrl,\n hosts: verifierOpts.jwks?.hosts?.http,\n });\n\n this.application\n .bind<IJWKSVerifierOptions>({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n .toValue(verifierOpts);\n this.application.service(JWKSVerifierTokenService);\n\n this.logger.for(this.defineJWKSAuth.name).info('JWKS verifier configured');\n break;\n }\n\n default: {\n // Same exhaustive-switch-narrows-to-never situation as the JOSE standard default above.\n throw getError({\n message: `[defineJWKSAuth] Invalid JWKS mode: ${(jwksOptions as { mode?: unknown }).mode}`,\n });\n }\n }\n }\n\n /**\n * Service-to-service authentication. Absent options mean no strategy is registered and no route is\n * mounted, so an application that never sets them is byte-identical to today.\n *\n * The certs route is mounted only when SIGNING keys are present. Most services are called and\n * never call; publishing a key set for a service that signs nothing advertises a capability it\n * does not have.\n */\n private defineServiceAuth(opts: { serviceOptions?: IServiceAuthOptions }): void {\n const { serviceOptions } = opts;\n\n if (!serviceOptions) {\n this.logger\n .for(this.defineServiceAuth.name)\n .debug('serviceOptions not provided, skipping service authentication');\n\n return;\n }\n\n if (!serviceOptions.name) {\n throw getError({\n message:\n '[defineServiceAuth] name is required | it is the issuer this service stamps and the audience it demands',\n });\n }\n\n if (!serviceOptions.resolvePrincipal) {\n throw getError({\n message:\n '[defineServiceAuth] resolvePrincipal is required | the framework proves WHICH SERVICE called, the application decides who that acts as',\n });\n }\n\n // A caller's key set decides who may call: https, loopback, or a host listed in jwks.hosts.http. Checked at boot, so a bad URL never waits for its first request.\n JWKSUrlPolicy.resolveHttpHosts({\n scope: 'defineServiceAuth',\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n\n for (const [caller, entry] of Object.entries(serviceOptions.callers ?? {})) {\n JWKSUrlPolicy.assertUrl({\n scope: 'defineServiceAuth',\n label: `callers[${JSON.stringify(caller)}].jwksUrl`,\n url: typeof entry === 'string' ? entry : entry.jwksUrl,\n hosts: serviceOptions.jwks?.hosts?.http,\n });\n }\n\n this.application.service(ServiceAssertionVerifierService);\n\n if (serviceOptions.keys) {\n this.application.service(ServiceAssertionSignerService);\n\n const restPath = serviceOptions.rest?.path ?? ServiceAssertion.DEFAULT_REST_PATH;\n this.application\n .bind<string>({ key: AuthenticateBindingKeys.SERVICE_CERTS_PATH })\n .toValue(restPath);\n\n // Path depends on a runtime option, so @controller cannot be applied statically.\n Reflect.decorate([controller({ path: restPath })], ServiceCertsController);\n this.application.controller(ServiceCertsController);\n }\n\n AuthenticationStrategyRegistry.getInstance().register({\n container: this.application,\n strategies: [\n { name: Authentication.STRATEGY_SERVICE, strategy: ServiceAuthenticationStrategy },\n ],\n });\n\n this.logger\n .for(this.defineServiceAuth.name)\n .info(\n 'Service authentication configured | name: %s | signs: %s | callers: %s',\n serviceOptions.name,\n Boolean(serviceOptions.keys),\n Object.keys(serviceOptions.callers ?? {}).join(', ') || 'none',\n );\n }\n\n private defineBasicAuth(opts: { basicOptions?: TBasicTokenServiceOptions }): void {\n const { basicOptions } = opts;\n\n if (!basicOptions) {\n this.logger\n .for(this.defineBasicAuth.name)\n .debug('basicOptions not provided, skipping Basic configuration');\n\n return;\n }\n\n if (!basicOptions.verifyCredentials) {\n throw getError({\n message: '[defineBasicAuth] verifyCredentials function is required',\n });\n }\n\n this.application\n .bind<TBasicTokenServiceOptions>({ key: AuthenticateBindingKeys.BASIC_OPTIONS })\n .toValue(basicOptions);\n this.application.service(BasicTokenService);\n\n this.logger.for(this.defineBasicAuth.name).info('Basic authentication configured');\n }\n\n private defineControllers(opts: { options: IAuthenticateOptions }): void {\n const { restOptions, jwtOptions } = opts.options;\n\n if (!restOptions?.useAuthController) {\n this.logger.for(this.defineControllers.name).debug('Auth controller disabled');\n\n return;\n }\n\n if (!jwtOptions) {\n throw getError({\n message: '[defineControllers] Auth controller requires jwtOptions to be configured',\n });\n }\n\n const AuthController = AuthControllerFactory.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"]}
@@ -15,7 +15,7 @@ export declare const JWTTokenPayloadSchema: z.ZodObject<{
15
15
  }, z.core.$strip>;
16
16
  /** Builds the decorated REST controller of the authentication routes (sign-in, sign-up, change-password, who-am-i). */
17
17
  export declare class AuthControllerFactory {
18
- static define(opts: TDefineAuthControllerOpts): {
18
+ static build(opts: TDefineAuthControllerOpts): {
19
19
  new (authService: IAuthService): {
20
20
  service: IAuthService;
21
21
  binding(): ValueOrPromise<void>;
@@ -33,7 +33,7 @@ export const JWTTokenPayloadSchema = z.object({
33
33
  });
34
34
  /** Builds the decorated REST controller of the authentication routes (sign-in, sign-up, change-password, who-am-i). */
35
35
  export class AuthControllerFactory {
36
- static define(opts) {
36
+ static build(opts) {
37
37
  const { restPath = '/auth', serviceKey, requireAuthenticatedSignUp = false, payload = {}, } = opts;
38
38
  let AuthController = AuthController_1 = class AuthController extends BaseRestController {
39
39
  constructor(authService) {
@@ -1 +1 @@
1
- {"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/controllers/factory.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,cAAc,GAGf,MAAM,uBAAuB,CAAC;AAE/B,+IAA+I;AAC/I,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IACjC,KAAK,EAAE,CAAC,CAAC,KAAK,CACZ,CAAC,CAAC,MAAM,CAAC;QACP,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,CA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AC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;oBACpD,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;SACF,CAAA;QAjNK,cAAc;YADnB,UAAU,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;;WACzB,cAAc,CAiNnB;QAED,MAAM,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;QAE1D,OAAO,cAAc,CAAC;IACxB,CAAC;CACF","sourcesContent":["import { BaseRestController } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { controller } from '@venizia/ignis-kernel';\nimport { OpenApiResponses } from '@venizia/ignis-kernel';\nimport { NotSupportedUtility } from '@venizia/ignis-kernel';\nimport { AnyObjectSchema } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n ChangePasswordRequestSchema,\n SignInRequestSchema,\n SignUpRequestSchema,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n type IAuthService,\n type TDefineAuthControllerOpts,\n} from '@venizia/ignis-kernel';\n\n/** Zod schema of the JWT payload: `userId`, the `roles` (id, identifier, integer priority) and optional `clientId`, `provider` and `email`. */\nexport const JWTTokenPayloadSchema = z.object({\n userId: z.string().or(z.number()),\n roles: z.array(\n z.object({\n id: z.string().or(z.number()),\n identifier: z.string(),\n priority: z.number().int(),\n }),\n ),\n clientId: z.string().optional(),\n provider: z.string().optional(),\n email: z.email().optional(),\n});\n\n/** Builds the decorated REST controller of the authentication routes (sign-in, sign-up, change-password, who-am-i). */\nexport class AuthControllerFactory {\n static define(opts: TDefineAuthControllerOpts) {\n const {\n restPath = '/auth',\n serviceKey,\n requireAuthenticatedSignUp = false,\n payload = {},\n } = opts;\n\n @controller({ path: restPath })\n class AuthController extends BaseRestController {\n service: IAuthService;\n\n constructor(authService: IAuthService) {\n super({\n scope: AuthController.name,\n path: restPath,\n isStrict: true,\n });\n\n if (!authService) {\n throw getError({\n message:\n '[AuthController] Failed to init auth controller | Invalid injectable authentication service!',\n });\n }\n\n this.service = authService;\n }\n\n override binding(): ValueOrPromise<void> {\n this.defineRoute({\n configs: {\n description: 'Sign In',\n path: '/sign-in',\n method: HTTP.Methods.POST,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Sign-in request body',\n required: true,\n schema: payload?.signIn?.request?.schema ?? SignInRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.signIn?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signIn(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Sign Up',\n path: '/sign-up',\n method: HTTP.Methods.POST,\n authenticate: {\n strategies: !requireAuthenticatedSignUp ? [] : [Authentication.STRATEGY_JWT],\n },\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Sign-up request body',\n required: true,\n schema: payload?.signUp?.request?.schema ?? SignUpRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.signUp?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signUp(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Change password',\n path: '/change-password',\n method: HTTP.Methods.POST,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Change password request body',\n required: true,\n schema: payload?.changePassword?.request?.schema ?? ChangePasswordRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.changePassword?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.changePassword(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n // Re-issues an access token using the caller's currently valid JWT — no separate refresh token. Implementers must enforce their own rotation/revocation policy if needed.\n this.defineRoute({\n configs: {\n description: 'Refresh access token',\n path: '/token/refresh',\n method: HTTP.Methods.POST,\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.refreshToken?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.refreshToken) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'refreshToken',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.refreshToken(context);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n path: '/who-am-i',\n method: HTTP.Methods.GET,\n request: {\n query: z.object({\n withUserInformation: z\n .enum(['true', 'false', '1', '0'])\n .transform((value) => value === 'true' || value === '1')\n .optional()\n .openapi({\n description: 'Whether to attach user information to currentUser',\n }),\n }),\n },\n responses: {\n [HTTP.ResultCodes.RS_2.Ok]: OpenApiResponses.jsonContent({\n description: 'Success Response',\n schema: JWTTokenPayloadSchema.extend({\n userInformation: (\n payload?.getUserInformation?.response?.schema ?? AnyObjectSchema\n )\n .optional()\n .openapi({\n description: 'Attached when withUserInformation is truthy',\n }),\n }),\n }),\n },\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const { withUserInformation = false } = context.req.valid<{\n withUserInformation?: boolean;\n }>('query');\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n let rs = currentUser;\n\n if (withUserInformation) {\n if (!this.service.getUserInformation) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const userInformation = await this.service.getUserInformation(context, {});\n rs = Object.assign({}, currentUser, { userInformation });\n }\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Get current user information',\n path: '/me',\n method: HTTP.Methods.GET,\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.getUserInformation?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.getUserInformation) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.getUserInformation(context, {});\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n }\n }\n\n inject({ key: serviceKey })(AuthController, undefined, 0);\n\n return AuthController;\n }\n}\n"]}
1
+ {"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/controllers/factory.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,cAAc,GAGf,MAAM,uBAAuB,CAAC;AAE/B,+IA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,iBAAiB,CAAC;gCAC3C,KAAK,EAAE,gBAAc,CAAC,IAAI;gCAC1B,OAAO,EAAE,oBAAoB;gCAC7B,MAAM,EAAE,IAAI,CAAC,MAAM;6BACpB,CAAC,CAAC;wBACL,CAAC;wBAED,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;wBAE9D,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;oBACpD,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;SACF,CAAA;QAjNK,cAAc;YADnB,UAAU,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;;WACzB,cAAc,CAiNnB;QAED,MAAM,CAAC,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;QAE1D,OAAO,cAAc,CAAC;IACxB,CAAC;CACF","sourcesContent":["import { BaseRestController } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { controller } from '@venizia/ignis-kernel';\nimport { OpenApiResponses } from '@venizia/ignis-kernel';\nimport { NotSupportedUtility } from '@venizia/ignis-kernel';\nimport { AnyObjectSchema } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n ChangePasswordRequestSchema,\n SignInRequestSchema,\n SignUpRequestSchema,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n type IAuthService,\n type TDefineAuthControllerOpts,\n} from '@venizia/ignis-kernel';\n\n/** Zod schema of the JWT payload: `userId`, the `roles` (id, identifier, integer priority) and optional `clientId`, `provider` and `email`. */\nexport const JWTTokenPayloadSchema = z.object({\n userId: z.string().or(z.number()),\n roles: z.array(\n z.object({\n id: z.string().or(z.number()),\n identifier: z.string(),\n priority: z.number().int(),\n }),\n ),\n clientId: z.string().optional(),\n provider: z.string().optional(),\n email: z.email().optional(),\n});\n\n/** Builds the decorated REST controller of the authentication routes (sign-in, sign-up, change-password, who-am-i). */\nexport class AuthControllerFactory {\n static build(opts: TDefineAuthControllerOpts) {\n const {\n restPath = '/auth',\n serviceKey,\n requireAuthenticatedSignUp = false,\n payload = {},\n } = opts;\n\n @controller({ path: restPath })\n class AuthController extends BaseRestController {\n service: IAuthService;\n\n constructor(authService: IAuthService) {\n super({\n scope: AuthController.name,\n path: restPath,\n isStrict: true,\n });\n\n if (!authService) {\n throw getError({\n message:\n '[AuthController] Failed to init auth controller | Invalid injectable authentication service!',\n });\n }\n\n this.service = authService;\n }\n\n override binding(): ValueOrPromise<void> {\n this.defineRoute({\n configs: {\n description: 'Sign In',\n path: '/sign-in',\n method: HTTP.Methods.POST,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Sign-in request body',\n required: true,\n schema: payload?.signIn?.request?.schema ?? SignInRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.signIn?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signIn(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Sign Up',\n path: '/sign-up',\n method: HTTP.Methods.POST,\n authenticate: {\n strategies: !requireAuthenticatedSignUp ? [] : [Authentication.STRATEGY_JWT],\n },\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Sign-up request body',\n required: true,\n schema: payload?.signUp?.request?.schema ?? SignUpRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.signUp?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signUp(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Change password',\n path: '/change-password',\n method: HTTP.Methods.POST,\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Change password request body',\n required: true,\n schema: payload?.changePassword?.request?.schema ?? ChangePasswordRequestSchema,\n }),\n },\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.changePassword?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.changePassword(context, body);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n // Re-issues an access token using the caller's currently valid JWT — no separate refresh token. Implementers must enforce their own rotation/revocation policy if needed.\n this.defineRoute({\n configs: {\n description: 'Refresh access token',\n path: '/token/refresh',\n method: HTTP.Methods.POST,\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.refreshToken?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.refreshToken) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'refreshToken',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.refreshToken(context);\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n path: '/who-am-i',\n method: HTTP.Methods.GET,\n request: {\n query: z.object({\n withUserInformation: z\n .enum(['true', 'false', '1', '0'])\n .transform((value) => value === 'true' || value === '1')\n .optional()\n .openapi({\n description: 'Whether to attach user information to currentUser',\n }),\n }),\n },\n responses: {\n [HTTP.ResultCodes.RS_2.Ok]: OpenApiResponses.jsonContent({\n description: 'Success Response',\n schema: JWTTokenPayloadSchema.extend({\n userInformation: (\n payload?.getUserInformation?.response?.schema ?? AnyObjectSchema\n )\n .optional()\n .openapi({\n description: 'Attached when withUserInformation is truthy',\n }),\n }),\n }),\n },\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const { withUserInformation = false } = context.req.valid<{\n withUserInformation?: boolean;\n }>('query');\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n let rs = currentUser;\n\n if (withUserInformation) {\n if (!this.service.getUserInformation) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const userInformation = await this.service.getUserInformation(context, {});\n rs = Object.assign({}, currentUser, { userInformation });\n }\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Get current user information',\n path: '/me',\n method: HTTP.Methods.GET,\n responses: OpenApiResponses.jsonResponse({\n schema: payload?.getUserInformation?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.getUserInformation) {\n return NotSupportedUtility.throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.getUserInformation(context, {});\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n }\n }\n\n inject({ key: serviceKey })(AuthController, undefined, 0);\n\n return AuthController;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { TMailBackoffType } from '../constants.js';
2
2
  import type { TConstValue } from '@venizia/ignis-helpers/common';
3
- import type { IRedisSingleHelperOptions } from '@venizia/ignis-helpers';
3
+ import type { IRedisHelper } from '@venizia/ignis-helpers';
4
4
  import type { BullMQExecutorModes, MailQueueExecutorTypes } from '../constants.js';
5
5
  /** Per-job options for a queued verification mail. `delay` and `backoff.delay` are milliseconds; `attempts` is the total number of tries, first included. */
6
6
  export interface IMailQueueOptions {
@@ -43,10 +43,14 @@ export interface IQueueJobPayload {
43
43
  export interface IInternalQueueMailExecutorOpts {
44
44
  identifier: string;
45
45
  }
46
- /** Options of the BullMQ mail executor: the Redis connection, the queue `identifier` and BullMQ `name`, and which of queue and workers this process runs. */
46
+ /** Options of the BullMQ mail executor: the Redis helper, the queue `identifier` and BullMQ `name`, and which of queue and workers this process runs. */
47
47
  export interface IBullMQMailExecutorOpts {
48
- /** `redis.module` passes `ioredis` itself - see `module` below for why. */
49
- redis: IRedisSingleHelperOptions;
48
+ /**
49
+ * A ready single, cluster or sentinel helper. The queue and each worker duplicate its client, and the
50
+ * application closes it: the executor never disconnects a connection it did not create. On a cluster
51
+ * the queue name is wrapped in a `{hash tag}` so its keys share one slot.
52
+ */
53
+ redis: IRedisHelper;
50
54
  queue: {
51
55
  identifier: string;
52
56
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"queue.js","sourceRoot":"","sources":["../../../../../../src/components/mail/common/types/queue.ts"],"names":[],"mappings":"","sourcesContent":["import type { TMailBackoffType } from '../constants';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type { IRedisSingleHelperOptions } from '@venizia/ignis-helpers';\nimport type { BullMQExecutorModes, MailQueueExecutorTypes } from '../constants';\n\n/** Per-job options for a queued verification mail. `delay` and `backoff.delay` are milliseconds; `attempts` is the total number of tries, first included. */\nexport interface IMailQueueOptions {\n priority?: number;\n delay?: number;\n attempts?: number;\n backoff?: {\n type: TMailBackoffType;\n delay: number;\n };\n}\n\n/** Result a queue processor returns for one verification mail; returning `success: false` marks the job failed so it is retried. */\nexport interface IMailProcessorResult {\n success: boolean;\n message: string;\n expiresInMinutes: number;\n nextResendAt?: string;\n}\n\n/** Result of enqueueing a verification mail; `queued` is `false` and `result` is set when the executor ran the mail inline. */\nexport interface IMailQueueResult {\n jobId?: string;\n queued: boolean;\n message: string;\n result?: IMailProcessorResult;\n}\n\n/** Queues verification mails and runs them through the processor registered with `setProcessor`. */\nexport interface IMailQueueExecutor {\n enqueueVerificationEmail(email: string, options?: IMailQueueOptions): Promise<IMailQueueResult>;\n setProcessor(processor: (email: string) => Promise<IMailProcessorResult>): void;\n}\n\n/** Envelope every queue-backed executor stores for one pending verification email. */\nexport interface IQueueJobPayload {\n id: string;\n email: string;\n options?: IMailQueueOptions;\n attempts: number;\n scheduledAt: number;\n}\n\n/** Options of the in-process queue executor; `identifier` names its queue. */\nexport interface IInternalQueueMailExecutorOpts {\n identifier: string;\n}\n\n/** Options of the BullMQ mail executor: the Redis connection, the queue `identifier` and BullMQ `name`, and which of queue and workers this process runs. */\nexport interface IBullMQMailExecutorOpts {\n /** `redis.module` passes `ioredis` itself - see `module` below for why. */\n redis: IRedisSingleHelperOptions;\n queue: { identifier: string; name: string };\n mode: TConstValue<typeof BullMQExecutorModes>;\n /** `bullmq` itself, for a `bun build --compile` binary that has no `node_modules` to load it from. */\n module?: typeof import('bullmq');\n}\n\n/** Selects and configures the mail queue executor; the field matching `type` (`internalQueue` or `bullmq`) is required for that type. */\nexport interface IMailQueueExecutorConfig {\n type: TConstValue<typeof MailQueueExecutorTypes>;\n internalQueue?: IInternalQueueMailExecutorOpts;\n bullmq?: IBullMQMailExecutorOpts;\n}\n"]}
1
+ {"version":3,"file":"queue.js","sourceRoot":"","sources":["../../../../../../src/components/mail/common/types/queue.ts"],"names":[],"mappings":"","sourcesContent":["import type { TMailBackoffType } from '../constants';\nimport type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type { IRedisHelper } from '@venizia/ignis-helpers';\nimport type { BullMQExecutorModes, MailQueueExecutorTypes } from '../constants';\n\n/** Per-job options for a queued verification mail. `delay` and `backoff.delay` are milliseconds; `attempts` is the total number of tries, first included. */\nexport interface IMailQueueOptions {\n priority?: number;\n delay?: number;\n attempts?: number;\n backoff?: {\n type: TMailBackoffType;\n delay: number;\n };\n}\n\n/** Result a queue processor returns for one verification mail; returning `success: false` marks the job failed so it is retried. */\nexport interface IMailProcessorResult {\n success: boolean;\n message: string;\n expiresInMinutes: number;\n nextResendAt?: string;\n}\n\n/** Result of enqueueing a verification mail; `queued` is `false` and `result` is set when the executor ran the mail inline. */\nexport interface IMailQueueResult {\n jobId?: string;\n queued: boolean;\n message: string;\n result?: IMailProcessorResult;\n}\n\n/** Queues verification mails and runs them through the processor registered with `setProcessor`. */\nexport interface IMailQueueExecutor {\n enqueueVerificationEmail(email: string, options?: IMailQueueOptions): Promise<IMailQueueResult>;\n setProcessor(processor: (email: string) => Promise<IMailProcessorResult>): void;\n}\n\n/** Envelope every queue-backed executor stores for one pending verification email. */\nexport interface IQueueJobPayload {\n id: string;\n email: string;\n options?: IMailQueueOptions;\n attempts: number;\n scheduledAt: number;\n}\n\n/** Options of the in-process queue executor; `identifier` names its queue. */\nexport interface IInternalQueueMailExecutorOpts {\n identifier: string;\n}\n\n/** Options of the BullMQ mail executor: the Redis helper, the queue `identifier` and BullMQ `name`, and which of queue and workers this process runs. */\nexport interface IBullMQMailExecutorOpts {\n /**\n * A ready single, cluster or sentinel helper. The queue and each worker duplicate its client, and the\n * application closes it: the executor never disconnects a connection it did not create. On a cluster\n * the queue name is wrapped in a `{hash tag}` so its keys share one slot.\n */\n redis: IRedisHelper;\n queue: { identifier: string; name: string };\n mode: TConstValue<typeof BullMQExecutorModes>;\n /** `bullmq` itself, for a `bun build --compile` binary that has no `node_modules` to load it from. */\n module?: typeof import('bullmq');\n}\n\n/** Selects and configures the mail queue executor; the field matching `type` (`internalQueue` or `bullmq`) is required for that type. */\nexport interface IMailQueueExecutorConfig {\n type: TConstValue<typeof MailQueueExecutorTypes>;\n internalQueue?: IInternalQueueMailExecutorOpts;\n bullmq?: IBullMQMailExecutorOpts;\n}\n"]}
@@ -32,7 +32,7 @@ export declare class BullMQMailExecutorHelper extends BaseHelper implements IMai
32
32
  /** Closes every worker without stopping at the first failure, always empties the list, and returns failures instead of throwing so teardown can continue. */
33
33
  private closeWorkers;
34
34
  clearWorkers(): Promise<void>;
35
- /** Full teardown: workers -> queue -> Redis. Every step runs even if an earlier one failed (skipping leaks a queue client + Redis socket); failures are reported once, at the end. */
35
+ /** Closes the workers, then the queue. Every step runs even if an earlier one failed; failures are reported once, at the end. The Redis helper is the application's, so it stays open. */
36
36
  close(): Promise<void>;
37
37
  getWorkerCount(): number;
38
38
  getMode(): TConstValue<typeof BullMQExecutorModes>;
@@ -1,5 +1,4 @@
1
1
  import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
2
- import { RedisSingleHelper } from '@venizia/ignis-helpers';
3
2
  import { BullMQHelper } from '@venizia/ignis-helpers/bullmq';
4
3
  import { BullMQExecutorModes, MailBackoffTypes, MailErrorCodes, MailExecutorErrors, } from '../../common/index.js';
5
4
  /** Mail queue executor backed by BullMQ. The `mode` option decides whether this process holds the queue, the workers, or both; a processor returning `success: false` fails the job so BullMQ retries it. */
@@ -9,10 +8,7 @@ export class BullMQMailExecutorHelper extends BaseHelper {
9
8
  this.workerHelpers = [];
10
9
  this.jobIdCounter = 0;
11
10
  this.mode = opts.mode;
12
- this.redisConnection = new RedisSingleHelper({
13
- ...opts.redis,
14
- maxRetry: undefined,
15
- });
11
+ this.redisConnection = opts.redis;
16
12
  this.bullmqModule = opts.module;
17
13
  this.queueIdentifier = opts.queue.identifier;
18
14
  this.queueName = opts.queue.name;
@@ -162,7 +158,7 @@ export class BullMQMailExecutorHelper extends BaseHelper {
162
158
  await this.closeWorkers();
163
159
  this.logger.for(this.clearWorkers.name).info('All workers cleared | Count: %d', count);
164
160
  }
165
- /** Full teardown: workers -> queue -> Redis. Every step runs even if an earlier one failed (skipping leaks a queue client + Redis socket); failures are reported once, at the end. */
161
+ /** Closes the workers, then the queue. Every step runs even if an earlier one failed; failures are reported once, at the end. The Redis helper is the application's, so it stays open. */
166
162
  async close() {
167
163
  const result = await this.closeWorkers();
168
164
  const failures = [...result];
@@ -176,16 +172,6 @@ export class BullMQMailExecutorHelper extends BaseHelper {
176
172
  this.logger.for(this.close.name).error('Failed to close queue | error: %s', closeError);
177
173
  }
178
174
  }
179
- try {
180
- await this.redisConnection.disconnect();
181
- }
182
- catch (error) {
183
- const disconnectError = error instanceof Error ? error : getError({ message: String(error) });
184
- failures.push(disconnectError);
185
- this.logger
186
- .for(this.close.name)
187
- .error('Failed to disconnect redis | error: %s', disconnectError);
188
- }
189
175
  if (failures.length > 0) {
190
176
  throw getError({
191
177
  message: `[close] Incomplete BullMQ mail executor teardown | failures: ${failures
@@ -1 +1 @@
1
- {"version":3,"file":"bull-mq-executor.helper.js","sourceRoot":"","sources":["../../../../../../src/components/mail/helpers/executors/bull-mq-executor.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAS7D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,kBAAkB,GACnB,MAAM,cAAc,CAAC;AAGtB,6MAA6M;AAC7M,MAAM,OAAO,wBAAyB,SAAQ,UAAU;IAatD,YAAY,IAA6B;QACvC,KAAK,CAAC,EAAE,KAAK,EAAE,wBAAwB,CAAC,IAAI,EAAE,CAAC,CAAC;QAR1C,kBAAa,GAA2D,EAAE,CAAC;QAG3E,iBAAY,GAAG,CAAC,CAAC;QAOvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QAEtB,IAAI,CAAC,eAAe,GAAG,IAAI,iBAAiB,CAAC;YAC3C,GAAG,IAAI,CAAC,KAAK;YACb,QAAQ,EAAE,SAAS;SACpB,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;QAC7C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;QAEjC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IAED,SAAS,CAAC,KAA2C;QACnD,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KAAK;YACT,KAAK;YACL,OAAO;YACP,QAAQ,EAAE,CAAC;YACX,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,CAAC,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC;aACvC,IAAI,CACH,kEAAkE,EAClE,KAAK,EACL,KAAK,EACL,IAAI,CAAC,IAAI,CACV,CAAC;QAEJ,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,yBAAyB,EAAE,GAAG,EAAE;YAC/E,QAAQ,EAAE,OAAO,EAAE,QAAQ;YAC3B,KAAK,EAAE,OAAO,EAAE,KAAK;YACrB,QAAQ,EAAE,OAAO,EAAE,QAAQ,IAAI,CAAC;YAChC,OAAO,EAAE;gBACP,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,gBAAgB,CAAC,WAAW;gBAC5D,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;aACvC;YACD,gBAAgB,EAAE,IAAI;YACtB,YAAY,EAAE,KAAK;SACpB,CAAC,CAAC;QAEH,OAAO;YACL,KAAK,EAAE,OAAO,CAAC,EAAE,IAAI,KAAK;YAC1B,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,0CAA0C;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { RedisSingleHelper } from '@venizia/ignis-helpers';\nimport type { TConstValue } from '@/helpers';\nimport { BullMQHelper } from '@venizia/ignis-helpers/bullmq';\nimport type {\n IBullMQMailExecutorOpts,\n IMailProcessorResult,\n IMailQueueExecutor,\n IMailQueueOptions,\n IMailQueueResult,\n IQueueJobPayload,\n} from '../../common';\nimport {\n BullMQExecutorModes,\n MailBackoffTypes,\n MailErrorCodes,\n MailExecutorErrors,\n} from '../../common';\nimport type { Job } from 'bullmq';\n\n/** Mail queue executor backed by BullMQ. The `mode` option decides whether this process holds the queue, the workers, or both; a processor returning `success: false` fails the job so BullMQ retries it. */\nexport class BullMQMailExecutorHelper extends BaseHelper implements IMailQueueExecutor {\n private queueIdentifier: string;\n private queueName: string;\n private mode: TConstValue<typeof BullMQExecutorModes>;\n\n private queueHelper?: BullMQHelper<IQueueJobPayload, IMailQueueResult>;\n private workerHelpers: BullMQHelper<IQueueJobPayload, IMailProcessorResult>[] = [];\n private redisConnection: RedisSingleHelper;\n private readonly bullmqModule?: typeof import('bullmq');\n private jobIdCounter = 0;\n\n private processor?: (email: string) => Promise<IMailProcessorResult>;\n\n constructor(opts: IBullMQMailExecutorOpts) {\n super({ scope: BullMQMailExecutorHelper.name });\n\n this.mode = opts.mode;\n\n this.redisConnection = new RedisSingleHelper({\n ...opts.redis,\n maxRetry: undefined,\n });\n\n this.bullmqModule = opts.module;\n this.queueIdentifier = opts.queue.identifier;\n this.queueName = opts.queue.name;\n\n this.initQueue(opts.queue);\n }\n\n initQueue(queue: { identifier: string; name: string }) {\n switch (this.mode) {\n case BullMQExecutorModes.QUEUE_ONLY:\n case BullMQExecutorModes.BOTH: {\n this.queueHelper = new BullMQHelper<IQueueJobPayload, IMailQueueResult>({\n identifier: queue.identifier,\n queueName: queue.name,\n redisConnection: this.redisConnection,\n role: 'queue',\n module: this.bullmqModule,\n });\n\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (queue enabled) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n break;\n }\n default: {\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (worker-only mode) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n\n break;\n }\n }\n }\n\n async setProcessor(\n processor: (email: string) => Promise<IMailProcessorResult>,\n opts?: {\n numberOfWorkers?: number;\n concurrencyPerWorker?: number;\n lockDuration?: number;\n },\n ): Promise<void> {\n this.processor = processor;\n\n if (this.mode === BullMQExecutorModes.QUEUE_ONLY) {\n this.logger\n .for(this.setProcessor.name)\n .warn('Skipping worker creation in queue-only mode. Workers will not be started.');\n\n return;\n }\n\n const numberOfWorkers = opts?.numberOfWorkers ?? 1;\n const concurrencyPerWorker = opts?.concurrencyPerWorker ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n await this.clearWorkers();\n\n for (let i = 0; i < numberOfWorkers; i++) {\n this.addWorker({\n workerIdentifier: `${this.queueIdentifier}-worker-${i}`,\n concurrency: concurrencyPerWorker,\n lockDuration,\n });\n }\n\n this.logger\n .for(this.setProcessor.name)\n .info(\n 'Processor registered | Mode: %s | Workers: %d | Concurrency per worker: %d',\n this.mode,\n numberOfWorkers,\n concurrencyPerWorker,\n );\n }\n\n addWorker(opts: { workerIdentifier: string; concurrency?: number; lockDuration?: number }): void {\n if (!this.processor) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const workerIdentifier = opts.workerIdentifier;\n const concurrency = opts?.concurrency ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n const workerHelper = new BullMQHelper<IQueueJobPayload, IMailProcessorResult>({\n identifier: workerIdentifier,\n queueName: this.queueName,\n redisConnection: this.redisConnection,\n role: 'worker',\n module: this.bullmqModule,\n numberOfWorker: concurrency,\n lockDuration,\n onWorkerData: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n const maxAttempts = job.data.options?.attempts ?? 3;\n\n this.logger\n .for('onWorkerData')\n .info(\n 'Processing job | Worker: %s | jobId: %s | email: %s | attempt: %d/%d',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade + 1,\n maxAttempts,\n );\n\n if (!this.processor) {\n // Returning undefined would let BullMQ mark the job COMPLETED and (with removeOnComplete) delete it - mail silently dropped.\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] ${MailExecutorErrors.PROCESSOR_NOT_SET} | jobId: ${job.data.id}`,\n });\n }\n\n const result = await this.processor(job.data.email);\n\n // A processor reports SMTP rejection by RETURNING `{ success: false }`; BullMQ only treats a REJECTION as failure, so resolving completes the job - no retry, no DLQ.\n if (result?.success === false) {\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] Processor reported failure | jobId: ${job.data.id} | reason: ${result.message}`,\n });\n }\n\n return result;\n },\n onWorkerDataCompleted: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n this.logger\n .for('onWorkerDataCompleted')\n .info(\n 'Job completed | Worker: %s | jobId: %s | email: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n );\n },\n onWorkerDataFail: async (\n job: Job<IQueueJobPayload, IMailProcessorResult> | undefined,\n error: Error,\n ) => {\n if (job) {\n const maxAttempts = job.data.options?.attempts ?? 3;\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Job failed | Worker: %s | jobId: %s | email: %s | attempt: %d/%d | error: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade,\n maxAttempts,\n error.message,\n );\n } else {\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Worker error (no job) | Worker: %s | error: %s',\n workerIdentifier,\n error.message,\n );\n }\n },\n });\n\n this.workerHelpers.push(workerHelper);\n\n this.logger\n .for(this.addWorker.name)\n .info(\n 'Worker added | Identifier: %s | Concurrency: %d | Total workers: %d',\n workerIdentifier,\n concurrency,\n this.workerHelpers.length,\n );\n }\n\n async removeWorker(index: number): Promise<boolean> {\n if (index < 0 || index >= this.workerHelpers.length) {\n this.logger.for(this.removeWorker.name).warn('Invalid worker index: %d', index);\n\n return false;\n }\n\n // Dropped from the list BEFORE the close is awaited: a rejecting close must not leave a half-closed worker still counted and still handed jobs.\n const [workerHelper] = this.workerHelpers.splice(index, 1);\n await workerHelper.worker.close();\n\n this.logger\n .for(this.removeWorker.name)\n .info('Worker removed | Index: %d | Remaining workers: %d', index, this.workerHelpers.length);\n\n return true;\n }\n\n /** Closes every worker without stopping at the first failure, always empties the list, and returns failures instead of throwing so teardown can continue. */\n private async closeWorkers(): Promise<Error[]> {\n const workerHelpers = this.workerHelpers;\n this.workerHelpers = [];\n\n const results = await Promise.allSettled(\n workerHelpers.map((workerHelper) => workerHelper.worker.close()),\n );\n\n const failures: Error[] = [];\n\n for (const result of results) {\n if (result.status !== 'rejected') {\n continue;\n }\n\n const error =\n result.reason instanceof Error\n ? result.reason\n : getError({ message: `Worker close failed | reason: ${String(result.reason)}` });\n\n failures.push(error);\n this.logger.for('closeWorkers').error('Failed to close worker | error: %s', error.message);\n }\n\n return failures;\n }\n\n async clearWorkers(): Promise<void> {\n const count = this.workerHelpers.length;\n await this.closeWorkers();\n\n this.logger.for(this.clearWorkers.name).info('All workers cleared | Count: %d', count);\n }\n\n /** Full teardown: workers -> queue -> Redis. Every step runs even if an earlier one failed (skipping leaks a queue client + Redis socket); failures are reported once, at the end. */\n async close(): Promise<void> {\n const result = await this.closeWorkers();\n const failures: Error[] = [...result];\n\n if (this.queueHelper) {\n try {\n await this.queueHelper.queue.close();\n } catch (error) {\n const closeError = error instanceof Error ? error : getError({ message: String(error) });\n failures.push(closeError);\n this.logger.for(this.close.name).error('Failed to close queue | error: %s', closeError);\n }\n }\n\n try {\n await this.redisConnection.disconnect();\n } catch (error) {\n const disconnectError = error instanceof Error ? error : getError({ message: String(error) });\n failures.push(disconnectError);\n this.logger\n .for(this.close.name)\n .error('Failed to disconnect redis | error: %s', disconnectError);\n }\n\n if (failures.length > 0) {\n throw getError({\n message: `[close] Incomplete BullMQ mail executor teardown | failures: ${failures\n .map((failure) => failure.message)\n .join(' | ')}`,\n });\n }\n\n this.logger.for(this.close.name).info('BullMQ mail executor closed | Mode: %s', this.mode);\n }\n\n getWorkerCount(): number {\n return this.workerHelpers.length;\n }\n\n getMode(): TConstValue<typeof BullMQExecutorModes> {\n return this.mode;\n }\n\n async enqueueVerificationEmail(\n email: string,\n options?: IMailQueueOptions,\n ): Promise<IMailQueueResult> {\n if (this.mode === BullMQExecutorModes.WORKER_ONLY) {\n throw getError({\n message: 'Cannot enqueue jobs in worker-only mode. Set mode to \"queue-only\" or \"both\".',\n });\n }\n\n if (!this.queueHelper) {\n throw getError({\n message: 'Queue helper not initialized. This should not happen in queue-enabled mode.',\n });\n }\n\n if (!this.processor && this.mode !== BullMQExecutorModes.QUEUE_ONLY) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const jobId = `job_${++this.jobIdCounter}_${Date.now()}`;\n const job: IQueueJobPayload = {\n id: jobId,\n email,\n options,\n attempts: 0,\n scheduledAt: Date.now() + (options?.delay ?? 0),\n };\n\n this.logger\n .for(this.enqueueVerificationEmail.name)\n .info(\n 'Queuing email to BullMQ/Redis | jobId: %s | email: %s | mode: %s',\n jobId,\n email,\n this.mode,\n );\n\n const bullJob = await this.queueHelper.queue.add('send-verification-email', job, {\n priority: options?.priority,\n delay: options?.delay,\n attempts: options?.attempts ?? 3,\n backoff: {\n type: options?.backoff?.type ?? MailBackoffTypes.EXPONENTIAL,\n delay: options?.backoff?.delay ?? 1000,\n },\n removeOnComplete: true,\n removeOnFail: false,\n });\n\n return {\n jobId: bullJob.id ?? jobId,\n queued: true,\n message: 'Email queued successfully (BullMQ/Redis)',\n };\n }\n}\n"]}
1
+ {"version":3,"file":"bull-mq-executor.helper.js","sourceRoot":"","sources":["../../../../../../src/components/mail/helpers/executors/bull-mq-executor.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGnE,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAS7D,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,kBAAkB,GACnB,MAAM,cAAc,CAAC;AAGtB,6MAA6M;AAC7M,MAAM,OAAO,wBAAyB,SAAQ,UAAU;IAatD,YAAY,IAA6B;QACvC,KAAK,CAAC,EAAE,KAAK,EAAE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C;QACzD,MAAM,GAAG,GAAqB;YAC5B,EAAE,EAAE,KAAK;YACT,KAAK;YACL,OAAO;YACP,QAAQ,EAAE,CAAC;YACX,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,EAAE,KAAK,IAAI,CAAC,CAAC;SAChD,CAAC;QAEF,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC;aACvC,IAAI,CACH,kEAAkE,EAClE,KAAK,EACL,KAAK,EACL,IAAI,CAAC,IAAI,CACV,CAAC;QAEJ,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,yBAAyB,EAAE,GAAG,EAAE;YAC/E,QAAQ,EAAE,OAAO,EAAE,QAAQ;YAC3B,KAAK,EAAE,OAAO,EAAE,KAAK;YACrB,QAAQ,EAAE,OAAO,EAAE,QAAQ,IAAI,CAAC;YAChC,OAAO,EAAE;gBACP,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,gBAAgB,CAAC,WAAW;gBAC5D,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,IAAI;aACvC;YACD,gBAAgB,EAAE,IAAI;YACtB,YAAY,EAAE,KAAK;SACpB,CAAC,CAAC;QAEH,OAAO;YACL,KAAK,EAAE,OAAO,CAAC,EAAE,IAAI,KAAK;YAC1B,MAAM,EAAE,IAAI;YACZ,OAAO,EAAE,0CAA0C;SACpD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { IRedisHelper } from '@venizia/ignis-helpers';\nimport type { TConstValue } from '@/helpers';\nimport { BullMQHelper } from '@venizia/ignis-helpers/bullmq';\nimport type {\n IBullMQMailExecutorOpts,\n IMailProcessorResult,\n IMailQueueExecutor,\n IMailQueueOptions,\n IMailQueueResult,\n IQueueJobPayload,\n} from '../../common';\nimport {\n BullMQExecutorModes,\n MailBackoffTypes,\n MailErrorCodes,\n MailExecutorErrors,\n} from '../../common';\nimport type { Job } from 'bullmq';\n\n/** Mail queue executor backed by BullMQ. The `mode` option decides whether this process holds the queue, the workers, or both; a processor returning `success: false` fails the job so BullMQ retries it. */\nexport class BullMQMailExecutorHelper extends BaseHelper implements IMailQueueExecutor {\n private queueIdentifier: string;\n private queueName: string;\n private mode: TConstValue<typeof BullMQExecutorModes>;\n\n private queueHelper?: BullMQHelper<IQueueJobPayload, IMailQueueResult>;\n private workerHelpers: BullMQHelper<IQueueJobPayload, IMailProcessorResult>[] = [];\n private redisConnection: IRedisHelper;\n private readonly bullmqModule?: typeof import('bullmq');\n private jobIdCounter = 0;\n\n private processor?: (email: string) => Promise<IMailProcessorResult>;\n\n constructor(opts: IBullMQMailExecutorOpts) {\n super({ scope: BullMQMailExecutorHelper.name });\n\n this.mode = opts.mode;\n\n this.redisConnection = opts.redis;\n\n this.bullmqModule = opts.module;\n this.queueIdentifier = opts.queue.identifier;\n this.queueName = opts.queue.name;\n\n this.initQueue(opts.queue);\n }\n\n initQueue(queue: { identifier: string; name: string }) {\n switch (this.mode) {\n case BullMQExecutorModes.QUEUE_ONLY:\n case BullMQExecutorModes.BOTH: {\n this.queueHelper = new BullMQHelper<IQueueJobPayload, IMailQueueResult>({\n identifier: queue.identifier,\n queueName: queue.name,\n redisConnection: this.redisConnection,\n role: 'queue',\n module: this.bullmqModule,\n });\n\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (queue enabled) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n break;\n }\n default: {\n this.logger\n .for(this.constructor.name)\n .info(\n 'BullMQ queue executor initialized (worker-only mode) | Identifier: %s | Mode: %s',\n this.queueIdentifier,\n this.mode,\n );\n\n break;\n }\n }\n }\n\n async setProcessor(\n processor: (email: string) => Promise<IMailProcessorResult>,\n opts?: {\n numberOfWorkers?: number;\n concurrencyPerWorker?: number;\n lockDuration?: number;\n },\n ): Promise<void> {\n this.processor = processor;\n\n if (this.mode === BullMQExecutorModes.QUEUE_ONLY) {\n this.logger\n .for(this.setProcessor.name)\n .warn('Skipping worker creation in queue-only mode. Workers will not be started.');\n\n return;\n }\n\n const numberOfWorkers = opts?.numberOfWorkers ?? 1;\n const concurrencyPerWorker = opts?.concurrencyPerWorker ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n await this.clearWorkers();\n\n for (let i = 0; i < numberOfWorkers; i++) {\n this.addWorker({\n workerIdentifier: `${this.queueIdentifier}-worker-${i}`,\n concurrency: concurrencyPerWorker,\n lockDuration,\n });\n }\n\n this.logger\n .for(this.setProcessor.name)\n .info(\n 'Processor registered | Mode: %s | Workers: %d | Concurrency per worker: %d',\n this.mode,\n numberOfWorkers,\n concurrencyPerWorker,\n );\n }\n\n addWorker(opts: { workerIdentifier: string; concurrency?: number; lockDuration?: number }): void {\n if (!this.processor) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const workerIdentifier = opts.workerIdentifier;\n const concurrency = opts?.concurrency ?? 5;\n const lockDuration = opts?.lockDuration ?? 30000;\n\n const workerHelper = new BullMQHelper<IQueueJobPayload, IMailProcessorResult>({\n identifier: workerIdentifier,\n queueName: this.queueName,\n redisConnection: this.redisConnection,\n role: 'worker',\n module: this.bullmqModule,\n numberOfWorker: concurrency,\n lockDuration,\n onWorkerData: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n const maxAttempts = job.data.options?.attempts ?? 3;\n\n this.logger\n .for('onWorkerData')\n .info(\n 'Processing job | Worker: %s | jobId: %s | email: %s | attempt: %d/%d',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade + 1,\n maxAttempts,\n );\n\n if (!this.processor) {\n // Returning undefined would let BullMQ mark the job COMPLETED and (with removeOnComplete) delete it - mail silently dropped.\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] ${MailExecutorErrors.PROCESSOR_NOT_SET} | jobId: ${job.data.id}`,\n });\n }\n\n const result = await this.processor(job.data.email);\n\n // A processor reports SMTP rejection by RETURNING `{ success: false }`; BullMQ only treats a REJECTION as failure, so resolving completes the job - no retry, no DLQ.\n if (result?.success === false) {\n throw getError({\n messageCode: MailErrorCodes.SEND_FAILED,\n message: `[onWorkerData] Processor reported failure | jobId: ${job.data.id} | reason: ${result.message}`,\n });\n }\n\n return result;\n },\n onWorkerDataCompleted: async (job: Job<IQueueJobPayload, IMailProcessorResult>) => {\n this.logger\n .for('onWorkerDataCompleted')\n .info(\n 'Job completed | Worker: %s | jobId: %s | email: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n );\n },\n onWorkerDataFail: async (\n job: Job<IQueueJobPayload, IMailProcessorResult> | undefined,\n error: Error,\n ) => {\n if (job) {\n const maxAttempts = job.data.options?.attempts ?? 3;\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Job failed | Worker: %s | jobId: %s | email: %s | attempt: %d/%d | error: %s',\n workerIdentifier,\n job.data.id,\n job.data.email,\n job.attemptsMade,\n maxAttempts,\n error.message,\n );\n } else {\n this.logger\n .for('onWorkerDataFail')\n .error(\n 'Worker error (no job) | Worker: %s | error: %s',\n workerIdentifier,\n error.message,\n );\n }\n },\n });\n\n this.workerHelpers.push(workerHelper);\n\n this.logger\n .for(this.addWorker.name)\n .info(\n 'Worker added | Identifier: %s | Concurrency: %d | Total workers: %d',\n workerIdentifier,\n concurrency,\n this.workerHelpers.length,\n );\n }\n\n async removeWorker(index: number): Promise<boolean> {\n if (index < 0 || index >= this.workerHelpers.length) {\n this.logger.for(this.removeWorker.name).warn('Invalid worker index: %d', index);\n\n return false;\n }\n\n // Dropped from the list BEFORE the close is awaited: a rejecting close must not leave a half-closed worker still counted and still handed jobs.\n const [workerHelper] = this.workerHelpers.splice(index, 1);\n await workerHelper.worker.close();\n\n this.logger\n .for(this.removeWorker.name)\n .info('Worker removed | Index: %d | Remaining workers: %d', index, this.workerHelpers.length);\n\n return true;\n }\n\n /** Closes every worker without stopping at the first failure, always empties the list, and returns failures instead of throwing so teardown can continue. */\n private async closeWorkers(): Promise<Error[]> {\n const workerHelpers = this.workerHelpers;\n this.workerHelpers = [];\n\n const results = await Promise.allSettled(\n workerHelpers.map((workerHelper) => workerHelper.worker.close()),\n );\n\n const failures: Error[] = [];\n\n for (const result of results) {\n if (result.status !== 'rejected') {\n continue;\n }\n\n const error =\n result.reason instanceof Error\n ? result.reason\n : getError({ message: `Worker close failed | reason: ${String(result.reason)}` });\n\n failures.push(error);\n this.logger.for('closeWorkers').error('Failed to close worker | error: %s', error.message);\n }\n\n return failures;\n }\n\n async clearWorkers(): Promise<void> {\n const count = this.workerHelpers.length;\n await this.closeWorkers();\n\n this.logger.for(this.clearWorkers.name).info('All workers cleared | Count: %d', count);\n }\n\n /** Closes the workers, then the queue. Every step runs even if an earlier one failed; failures are reported once, at the end. The Redis helper is the application's, so it stays open. */\n async close(): Promise<void> {\n const result = await this.closeWorkers();\n const failures: Error[] = [...result];\n\n if (this.queueHelper) {\n try {\n await this.queueHelper.queue.close();\n } catch (error) {\n const closeError = error instanceof Error ? error : getError({ message: String(error) });\n failures.push(closeError);\n this.logger.for(this.close.name).error('Failed to close queue | error: %s', closeError);\n }\n }\n\n if (failures.length > 0) {\n throw getError({\n message: `[close] Incomplete BullMQ mail executor teardown | failures: ${failures\n .map((failure) => failure.message)\n .join(' | ')}`,\n });\n }\n\n this.logger.for(this.close.name).info('BullMQ mail executor closed | Mode: %s', this.mode);\n }\n\n getWorkerCount(): number {\n return this.workerHelpers.length;\n }\n\n getMode(): TConstValue<typeof BullMQExecutorModes> {\n return this.mode;\n }\n\n async enqueueVerificationEmail(\n email: string,\n options?: IMailQueueOptions,\n ): Promise<IMailQueueResult> {\n if (this.mode === BullMQExecutorModes.WORKER_ONLY) {\n throw getError({\n message: 'Cannot enqueue jobs in worker-only mode. Set mode to \"queue-only\" or \"both\".',\n });\n }\n\n if (!this.queueHelper) {\n throw getError({\n message: 'Queue helper not initialized. This should not happen in queue-enabled mode.',\n });\n }\n\n if (!this.processor && this.mode !== BullMQExecutorModes.QUEUE_ONLY) {\n throw getError({ message: MailExecutorErrors.PROCESSOR_NOT_SET });\n }\n\n const jobId = `job_${++this.jobIdCounter}_${Date.now()}`;\n const job: IQueueJobPayload = {\n id: jobId,\n email,\n options,\n attempts: 0,\n scheduledAt: Date.now() + (options?.delay ?? 0),\n };\n\n this.logger\n .for(this.enqueueVerificationEmail.name)\n .info(\n 'Queuing email to BullMQ/Redis | jobId: %s | email: %s | mode: %s',\n jobId,\n email,\n this.mode,\n );\n\n const bullJob = await this.queueHelper.queue.add('send-verification-email', job, {\n priority: options?.priority,\n delay: options?.delay,\n attempts: options?.attempts ?? 3,\n backoff: {\n type: options?.backoff?.type ?? MailBackoffTypes.EXPONENTIAL,\n delay: options?.backoff?.delay ?? 1000,\n },\n removeOnComplete: true,\n removeOnFail: false,\n });\n\n return {\n jobId: bullJob.id ?? jobId,\n queued: true,\n message: 'Email queued successfully (BullMQ/Redis)',\n };\n }\n}\n"]}
@@ -1,34 +1,53 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
- /** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */
3
- export declare const WHITELIST_HEADERS: readonly ["content-encoding", "cache-control", "etag", "last-modified"];
4
- /**
5
- * Types the controller will let a browser render, keyed off the object name. Anything absent here is
6
- * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`
7
- * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.
8
- */
9
- export declare const RENDERABLE_CONTENT_TYPES: Set<string>;
10
- /** Storage backends a static asset controller can serve from. `isValid` checks a string against them. */
11
- export declare class StaticAssetStorageTypes {
12
- static readonly DISK = "disk";
13
- static readonly BUN_S3 = "bun-s3";
14
- static readonly SCHEME_SET: Set<string>;
15
- static isValid(orgType: string): boolean;
2
+ /** The response headers a controller echoes from the backend's metadata. */
3
+ export declare class StaticAssetHeaders {
4
+ /** `content-type` is absent on purpose: it is decided from the object name, never from the backend. */
5
+ static readonly ALLOWED: readonly ["content-encoding", "cache-control", "etag", "last-modified"];
6
+ /** Of what a controller sends with every object. */
7
+ static readonly NOSNIFF = "nosniff";
8
+ static readonly CSP_SANDBOX = "sandbox";
9
+ static readonly RANGE_UNIT = "bytes";
10
+ }
11
+ /** Content types the controller serves. */
12
+ export declare class StaticAssetContentTypes {
13
+ /**
14
+ * Types the controller will let a browser render, keyed off the object name. Anything absent here is
15
+ * served as an attachment, because a renderable upload on the API origin is stored XSS - and `nosniff`
16
+ * cannot stop a type we declared ourselves. `image/svg+xml` is deliberately excluded: SVG carries script.
17
+ */
18
+ static readonly RENDERABLE: Set<string>;
19
+ }
20
+ /** The built-in routes of a generated controller, the keys of `routes`. */
21
+ export declare class StaticAssetRouteKeys {
22
+ static readonly UPLOAD = "upload";
23
+ static readonly LIST_OBJECTS = "listObjects";
24
+ static readonly DELETE_OBJECT = "deleteObject";
25
+ static readonly GET_OBJECT_BY_NAME = "getObjectByName";
26
+ static readonly DOWNLOAD_OBJECT_BY_NAME = "downloadObjectByName";
27
+ static readonly UPLOAD_POLICY = "uploadPolicy";
28
+ static readonly UPLOAD_COMMIT = "uploadCommit";
29
+ static readonly UPLOAD_VALIDATE = "uploadValidate";
30
+ static readonly RECREATE_META_LINK = "recreateMetaLink";
31
+ /** Every key, in registration order. */
32
+ static readonly ALL: readonly ["getObjectByName", "downloadObjectByName", "upload", "deleteObject", "listObjects", "uploadPolicy", "uploadCommit", "uploadValidate", "recreateMetaLink"];
16
33
  }
17
- /** One of the `StaticAssetStorageTypes` values. */
18
- export type TStaticAssetStorageType = TConstValue<typeof StaticAssetStorageTypes>;
19
34
  /** What `recreate-metalink` did: refreshed the rows of an object, or created its first one. */
20
35
  export declare class MetaLinkRecreateActions {
21
36
  static readonly CREATED = "created";
22
37
  static readonly REFRESHED = "refreshed";
23
- static readonly SCHEME_SET: Set<string>;
24
- static isValid(value: string): boolean;
25
38
  }
26
39
  /** One of the `MetaLinkRecreateActions` values. */
27
40
  export type TMetaLinkRecreateAction = TConstValue<typeof MetaLinkRecreateActions>;
28
- /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
29
- export declare const DEFAULT_PENDING_PREFIX = "pending/";
30
- /** The most file parts one upload request may carry unless `parseMultipartBody.maxFiles` says otherwise. */
31
- export declare const DEFAULT_MAX_UPLOAD_FILES = 20;
32
- /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */
33
- export declare const META_LINK_CREATE_FAILED = "META_LINK_CREATE_FAILED";
41
+ /** Defaults of the static asset component. */
42
+ export declare class StaticAssetDefaults {
43
+ /** Where a signed policy may write. The final key is never inside it, so content cannot be replaced after the commit. */
44
+ static readonly PENDING_PREFIX = "pending/";
45
+ /** The most file parts one upload request may carry unless `serverUpload.maxFiles` says otherwise. */
46
+ static readonly MAX_UPLOAD_FILES = 20;
47
+ }
48
+ /** Codes the component reports in a body instead of throwing. */
49
+ export declare class StaticAssetMetaLinkCodes {
50
+ /** Reported in the body, never thrown: the bytes are stored, only the row is not. A CODE, because a 200 bypasses the middleware that strips the driver's `detail`/`table`/`constraint`. */
51
+ static readonly CREATE_FAILED = "META_LINK_CREATE_FAILED";
52
+ }
34
53
  //# sourceMappingURL=constants.d.ts.map