@venizia/ignis 0.4.8-13 → 0.4.8-15

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 (89) hide show
  1. package/dist/esm/components/mail/common/constants.d.ts +24 -14
  2. package/dist/esm/components/mail/common/constants.js +19 -32
  3. package/dist/esm/components/mail/common/constants.js.map +1 -1
  4. package/dist/esm/components/mail/common/errors.d.ts +10 -1
  5. package/dist/esm/components/mail/common/errors.js +7 -1
  6. package/dist/esm/components/mail/common/errors.js.map +1 -1
  7. package/dist/esm/components/mail/common/types/queue.d.ts +15 -8
  8. package/dist/esm/components/mail/common/types/queue.js.map +1 -1
  9. package/dist/esm/components/mail/common/types/template.d.ts +3 -2
  10. package/dist/esm/components/mail/common/types/template.js.map +1 -1
  11. package/dist/esm/components/mail/component.js +11 -2
  12. package/dist/esm/components/mail/component.js.map +1 -1
  13. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js +13 -12
  14. package/dist/esm/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
  15. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.d.ts +2 -0
  16. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js +17 -10
  17. package/dist/esm/components/mail/helpers/executors/internal-queue-executor.helper.js.map +1 -1
  18. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js +4 -4
  19. package/dist/esm/components/mail/helpers/transporters/amazon-ses-transporter.helper.js.map +1 -1
  20. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js +15 -6
  21. package/dist/esm/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
  22. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js +2 -2
  23. package/dist/esm/components/mail/helpers/transporters/nodemail-transporter.helper.js.map +1 -1
  24. package/dist/esm/components/mail/providers/mail-queue-executor.provider.d.ts +2 -2
  25. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js +7 -9
  26. package/dist/esm/components/mail/providers/mail-queue-executor.provider.js.map +1 -1
  27. package/dist/esm/components/mail/providers/mail-transporter.provider.js +7 -7
  28. package/dist/esm/components/mail/providers/mail-transporter.provider.js.map +1 -1
  29. package/dist/esm/components/mail/services/mail.service.js +21 -19
  30. package/dist/esm/components/mail/services/mail.service.js.map +1 -1
  31. package/dist/esm/components/mail/services/template.service.d.ts +4 -1
  32. package/dist/esm/components/mail/services/template.service.js +24 -16
  33. package/dist/esm/components/mail/services/template.service.js.map +1 -1
  34. package/dist/esm/components/mail/utilities/attachment.utility.js +8 -6
  35. package/dist/esm/components/mail/utilities/attachment.utility.js.map +1 -1
  36. package/dist/esm/components/mail/utilities/header.utility.d.ts +14 -0
  37. package/dist/esm/components/mail/utilities/header.utility.js +44 -0
  38. package/dist/esm/components/mail/utilities/header.utility.js.map +1 -0
  39. package/dist/esm/components/mail/utilities/index.d.ts +1 -0
  40. package/dist/esm/components/mail/utilities/index.js +1 -0
  41. package/dist/esm/components/mail/utilities/index.js.map +1 -1
  42. package/dist/esm/components/mail/utilities/mime.utility.d.ts +5 -1
  43. package/dist/esm/components/mail/utilities/mime.utility.js +9 -55
  44. package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
  45. package/dist/esm/components/static-asset/common/constants.d.ts +5 -4
  46. package/dist/esm/components/static-asset/common/constants.js +5 -9
  47. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  48. package/dist/esm/components/static-asset/common/errors.d.ts +18 -0
  49. package/dist/esm/components/static-asset/common/errors.js +18 -0
  50. package/dist/esm/components/static-asset/common/errors.js.map +1 -1
  51. package/dist/esm/components/static-asset/common/types.d.ts +47 -18
  52. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  53. package/dist/esm/components/static-asset/component.js +1 -1
  54. package/dist/esm/components/static-asset/component.js.map +1 -1
  55. package/dist/esm/components/static-asset/controller/factory.d.ts +2 -166
  56. package/dist/esm/components/static-asset/controller/factory.js +7 -20
  57. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  58. package/dist/esm/components/static-asset/controller/index.d.ts +1 -0
  59. package/dist/esm/components/static-asset/controller/index.js +1 -0
  60. package/dist/esm/components/static-asset/controller/index.js.map +1 -1
  61. package/dist/esm/components/static-asset/controller/routes/context.d.ts +1 -1
  62. package/dist/esm/components/static-asset/controller/routes/context.js.map +1 -1
  63. package/dist/esm/components/static-asset/controller/routes/definition.js +15 -6
  64. package/dist/esm/components/static-asset/controller/routes/definition.js.map +1 -1
  65. package/dist/esm/components/static-asset/controller/routes/direct-upload.js +24 -2
  66. package/dist/esm/components/static-asset/controller/routes/direct-upload.js.map +1 -1
  67. package/dist/esm/components/static-asset/controller/routes/serve.d.ts +14 -2
  68. package/dist/esm/components/static-asset/controller/routes/serve.js +40 -15
  69. package/dist/esm/components/static-asset/controller/routes/serve.js.map +1 -1
  70. package/dist/esm/components/static-asset/controller/routes/upload.js +11 -10
  71. package/dist/esm/components/static-asset/controller/routes/upload.js.map +1 -1
  72. package/dist/esm/components/static-asset/services/commitment.service.d.ts +35 -16
  73. package/dist/esm/components/static-asset/services/commitment.service.js +92 -30
  74. package/dist/esm/components/static-asset/services/commitment.service.js.map +1 -1
  75. package/dist/esm/components/static-asset/services/policy.service.d.ts +7 -3
  76. package/dist/esm/components/static-asset/services/policy.service.js +21 -2
  77. package/dist/esm/components/static-asset/services/policy.service.js.map +1 -1
  78. package/dist/esm/components/static-asset/utilities/commit-token.utility.d.ts +2 -1
  79. package/dist/esm/components/static-asset/utilities/commit-token.utility.js +14 -5
  80. package/dist/esm/components/static-asset/utilities/commit-token.utility.js.map +1 -1
  81. package/dist/esm/components/static-asset/utilities/entry.utility.js +9 -2
  82. package/dist/esm/components/static-asset/utilities/entry.utility.js.map +1 -1
  83. package/dist/esm/components/static-asset/utilities/route-options.utility.d.ts +6 -7
  84. package/dist/esm/components/static-asset/utilities/route-options.utility.js +9 -23
  85. package/dist/esm/components/static-asset/utilities/route-options.utility.js.map +1 -1
  86. package/dist/presets/app/preset.json +4 -4
  87. package/dist/presets/lib/preset.json +3 -3
  88. package/dist/presets/shared/preset.json +1 -1
  89. package/package.json +8 -8
@@ -1,7 +1,7 @@
1
1
  import { HTTP } from '@venizia/ignis-helpers/common';
2
2
  import { BaseProvider } from '@venizia/ignis-kernel';
3
3
  import { getError } from '@venizia/ignis-helpers/core';
4
- import { MailErrorCodes, MailProviders } from '../common/index.js';
4
+ import { MailErrors, MailProviders } from '../common/index.js';
5
5
  import { AmazonSesTransportHelper, MailgunTransportHelper, NodemailerTransportHelper, } from '../helpers/index.js';
6
6
  import { MailTypeUtility } from '../utilities/index.js';
7
7
  /** Provides the `TGetMailTransportFn` factory bound at `MailKeys.MAIL_TRANSPORT_PROVIDER`. */
@@ -30,7 +30,7 @@ export class MailTransportProvider extends BaseProvider {
30
30
  default: {
31
31
  throw getError({
32
32
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
33
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
33
+ error: MailErrors.INVALID_CONFIGURATION,
34
34
  message: `Unsupported mail provider: ${options.provider}`,
35
35
  });
36
36
  }
@@ -46,7 +46,7 @@ export class MailTransportProvider extends BaseProvider {
46
46
  }
47
47
  throw getError({
48
48
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
49
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
49
+ error: MailErrors.INVALID_CONFIGURATION,
50
50
  message: 'Invalid Nodemailer configuration',
51
51
  });
52
52
  }
@@ -57,7 +57,7 @@ export class MailTransportProvider extends BaseProvider {
57
57
  }
58
58
  throw getError({
59
59
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
60
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
60
+ error: MailErrors.INVALID_CONFIGURATION,
61
61
  message: 'Invalid Mailgun configuration',
62
62
  });
63
63
  }
@@ -68,7 +68,7 @@ export class MailTransportProvider extends BaseProvider {
68
68
  }
69
69
  throw getError({
70
70
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
71
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
71
+ error: MailErrors.INVALID_CONFIGURATION,
72
72
  message: 'Invalid Amazon SES configuration',
73
73
  });
74
74
  }
@@ -76,7 +76,7 @@ export class MailTransportProvider extends BaseProvider {
76
76
  if (!this.isCustomOptions(options)) {
77
77
  throw getError({
78
78
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
79
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
79
+ error: MailErrors.INVALID_CONFIGURATION,
80
80
  message: 'Invalid custom mail provider configuration',
81
81
  });
82
82
  }
@@ -91,7 +91,7 @@ export class MailTransportProvider extends BaseProvider {
91
91
  }
92
92
  throw getError({
93
93
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
94
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
94
+ error: MailErrors.INVALID_CONFIGURATION,
95
95
  message: `Custom mail provider must implement IMailTransport interface. Missing methods: ${missingMethods.join(', ')}`,
96
96
  });
97
97
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mail-transporter.provider.js","sourceRoot":"","sources":["../../../../../src/components/mail/providers/mail-transporter.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASvD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAK/C,8FAA8F;AAC9F,MAAM,OAAO,qBAAsB,SAAQ,YAAiC;IAC1E;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IA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AqB;QAC/C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,UAAU,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC9E,CAAC;IAEO,gBAAgB,CAAC,OAAqB;QAC5C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,OAAO,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC3E,CAAC;IAEO,kBAAkB,CAAC,OAAqB;QAC9C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,UAAU,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC9E,CAAC;IAEO,eAAe,CAAC,OAAqB;QAC3C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,MAAM,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseProvider } from '@venizia/ignis-kernel';\nimport type { Container } from '@/helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type {\n IAmazonSesMailOptions,\n ICustomMailOptions,\n IMailgunMailOptions,\n IMailTransport,\n INodemailerMailOptions,\n TMailOptions,\n} from '../common';\nimport { MailErrorCodes, MailProviders } from '../common';\nimport {\n AmazonSesTransportHelper,\n MailgunTransportHelper,\n NodemailerTransportHelper,\n} from '../helpers';\nimport { MailTypeUtility } from '../utilities';\n\n/** Builds the transport for the given mail options; throws on an unsupported provider. */\nexport type TGetMailTransportFn = (options: TMailOptions) => IMailTransport;\n\n/** Provides the `TGetMailTransportFn` factory bound at `MailKeys.MAIL_TRANSPORT_PROVIDER`. */\nexport class MailTransportProvider extends BaseProvider<TGetMailTransportFn> {\n constructor() {\n super({ scope: MailTransportProvider.name });\n }\n\n value(_container: Container): TGetMailTransportFn {\n return (options: TMailOptions) => {\n this.logger\n .for(this.value.name)\n .info('Creating mail transport for provider: %s', options.provider);\n\n switch (options.provider) {\n case MailProviders.NODEMAILER: {\n return this.createNodemailerTransport(options);\n }\n\n case MailProviders.MAILGUN: {\n return this.createMailgunTransport(options);\n }\n\n case MailProviders.AMAZON_SES: {\n return this.createAmazonSesTransport(options);\n }\n\n case MailProviders.CUSTOM: {\n return this.createCustomTransport(options);\n }\n\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: `Unsupported mail provider: ${options.provider}`,\n });\n }\n }\n };\n }\n\n private createNodemailerTransport(options: TMailOptions): NodemailerTransportHelper {\n if (this.isNodemailerOptions(options)) {\n this.logger\n .for(this.createNodemailerTransport.name)\n .info('Initializing Nodemailer transport');\n\n return new NodemailerTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: 'Invalid Nodemailer configuration',\n });\n }\n\n private createMailgunTransport(options: TMailOptions): MailgunTransportHelper {\n if (this.isMailgunOptions(options)) {\n this.logger.for(this.createMailgunTransport.name).info('Initializing Mailgun transport');\n\n return new MailgunTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: 'Invalid Mailgun configuration',\n });\n }\n\n private createAmazonSesTransport(options: TMailOptions): AmazonSesTransportHelper {\n if (this.isAmazonSesOptions(options)) {\n this.logger.for(this.createAmazonSesTransport.name).info('Initializing Amazon SES transport');\n\n return new AmazonSesTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: 'Invalid Amazon SES configuration',\n });\n }\n\n private createCustomTransport(options: TMailOptions): IMailTransport {\n if (!this.isCustomOptions(options)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: 'Invalid custom mail provider configuration',\n });\n }\n\n if (!MailTypeUtility.isTransport(options.config)) {\n const missingMethods: string[] = [];\n const config = options.config as Record<string, unknown>;\n\n if (typeof config.send !== 'function') {\n missingMethods.push('send');\n }\n\n if (typeof config.verify !== 'function') {\n missingMethods.push('verify');\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: `Custom mail provider must implement IMailTransport interface. Missing methods: ${missingMethods.join(', ')}`,\n });\n }\n\n this.logger.for(this.createCustomTransport.name).info('Using custom mail transport');\n\n return options.config;\n }\n\n private isNodemailerOptions(options: TMailOptions): options is INodemailerMailOptions {\n return options.provider === MailProviders.NODEMAILER && 'config' in options;\n }\n\n private isMailgunOptions(options: TMailOptions): options is IMailgunMailOptions {\n return options.provider === MailProviders.MAILGUN && 'config' in options;\n }\n\n private isAmazonSesOptions(options: TMailOptions): options is IAmazonSesMailOptions {\n return options.provider === MailProviders.AMAZON_SES && 'config' in options;\n }\n\n private isCustomOptions(options: TMailOptions): options is ICustomMailOptions {\n return options.provider === MailProviders.CUSTOM && 'config' in options;\n }\n}\n"]}
1
+ {"version":3,"file":"mail-transporter.provider.js","sourceRoot":"","sources":["../../../../../src/components/mail/providers/mail-transporter.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASvD,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACtD,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAK/C,8FAA8F;AAC9F,MAAM,OAAO,qBAAsB,SAAQ,YAAiC;IAC1E;QACE,KAAK,CAA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AC;QAErF,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC;IAEO,mBAAmB,CAAC,OAAqB;QAC/C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,UAAU,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC9E,CAAC;IAEO,gBAAgB,CAAC,OAAqB;QAC5C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,OAAO,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC3E,CAAC;IAEO,kBAAkB,CAAC,OAAqB;QAC9C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,UAAU,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC9E,CAAC;IAEO,eAAe,CAAC,OAAqB;QAC3C,OAAO,OAAO,CAAC,QAAQ,KAAK,aAAa,CAAC,MAAM,IAAI,QAAQ,IAAI,OAAO,CAAC;IAC1E,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseProvider } from '@venizia/ignis-kernel';\nimport type { Container } from '@/helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type {\n IAmazonSesMailOptions,\n ICustomMailOptions,\n IMailgunMailOptions,\n IMailTransport,\n INodemailerMailOptions,\n TMailOptions,\n} from '../common';\nimport { MailErrors, MailProviders } from '../common';\nimport {\n AmazonSesTransportHelper,\n MailgunTransportHelper,\n NodemailerTransportHelper,\n} from '../helpers';\nimport { MailTypeUtility } from '../utilities';\n\n/** Builds the transport for the given mail options; throws on an unsupported provider. */\nexport type TGetMailTransportFn = (options: TMailOptions) => IMailTransport;\n\n/** Provides the `TGetMailTransportFn` factory bound at `MailKeys.MAIL_TRANSPORT_PROVIDER`. */\nexport class MailTransportProvider extends BaseProvider<TGetMailTransportFn> {\n constructor() {\n super({ scope: MailTransportProvider.name });\n }\n\n value(_container: Container): TGetMailTransportFn {\n return (options: TMailOptions) => {\n this.logger\n .for(this.value.name)\n .info('Creating mail transport for provider: %s', options.provider);\n\n switch (options.provider) {\n case MailProviders.NODEMAILER: {\n return this.createNodemailerTransport(options);\n }\n\n case MailProviders.MAILGUN: {\n return this.createMailgunTransport(options);\n }\n\n case MailProviders.AMAZON_SES: {\n return this.createAmazonSesTransport(options);\n }\n\n case MailProviders.CUSTOM: {\n return this.createCustomTransport(options);\n }\n\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Unsupported mail provider: ${options.provider}`,\n });\n }\n }\n };\n }\n\n private createNodemailerTransport(options: TMailOptions): NodemailerTransportHelper {\n if (this.isNodemailerOptions(options)) {\n this.logger\n .for(this.createNodemailerTransport.name)\n .info('Initializing Nodemailer transport');\n\n return new NodemailerTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Invalid Nodemailer configuration',\n });\n }\n\n private createMailgunTransport(options: TMailOptions): MailgunTransportHelper {\n if (this.isMailgunOptions(options)) {\n this.logger.for(this.createMailgunTransport.name).info('Initializing Mailgun transport');\n\n return new MailgunTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Invalid Mailgun configuration',\n });\n }\n\n private createAmazonSesTransport(options: TMailOptions): AmazonSesTransportHelper {\n if (this.isAmazonSesOptions(options)) {\n this.logger.for(this.createAmazonSesTransport.name).info('Initializing Amazon SES transport');\n\n return new AmazonSesTransportHelper({ config: options.config, module: options.module });\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Invalid Amazon SES configuration',\n });\n }\n\n private createCustomTransport(options: TMailOptions): IMailTransport {\n if (!this.isCustomOptions(options)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Invalid custom mail provider configuration',\n });\n }\n\n if (!MailTypeUtility.isTransport(options.config)) {\n const missingMethods: string[] = [];\n const config = options.config as Record<string, unknown>;\n\n if (typeof config.send !== 'function') {\n missingMethods.push('send');\n }\n\n if (typeof config.verify !== 'function') {\n missingMethods.push('verify');\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Custom mail provider must implement IMailTransport interface. Missing methods: ${missingMethods.join(', ')}`,\n });\n }\n\n this.logger.for(this.createCustomTransport.name).info('Using custom mail transport');\n\n return options.config;\n }\n\n private isNodemailerOptions(options: TMailOptions): options is INodemailerMailOptions {\n return options.provider === MailProviders.NODEMAILER && 'config' in options;\n }\n\n private isMailgunOptions(options: TMailOptions): options is IMailgunMailOptions {\n return options.provider === MailProviders.MAILGUN && 'config' in options;\n }\n\n private isAmazonSesOptions(options: TMailOptions): options is IAmazonSesMailOptions {\n return options.provider === MailProviders.AMAZON_SES && 'config' in options;\n }\n\n private isCustomOptions(options: TMailOptions): options is ICustomMailOptions {\n return options.provider === MailProviders.CUSTOM && 'config' in options;\n }\n}\n"]}
@@ -13,12 +13,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  var MailService_1;
14
14
  import { HTTP } from '@venizia/ignis-helpers/common';
15
15
  import { BaseService } from '@venizia/ignis-kernel';
16
- import { MailDefaults, MailErrorCodes, MailErrors, MailKeys } from '../common/index.js';
16
+ import { MailDefaults, MailErrorCodes, MailErrors, MailKeys, MailTemplateFormats } from '../common/index.js';
17
17
  import { inject } from '../../../base/metadata/index.js';
18
18
  import { getError, isApplicationError } from '@venizia/ignis-helpers/core';
19
- import { PromiseUtility } from '@venizia/ignis-helpers';
19
+ import { ErrorUtility, PromiseUtility } from '@venizia/ignis-helpers';
20
20
  import { MailAttachmentUtility } from '../utilities/attachment.utility.js';
21
21
  import { MailBodyUtility } from '../utilities/body.utility.js';
22
+ import { MailHeaderUtility } from '../utilities/header.utility.js';
23
+ import { MailMimeUtility } from '../utilities/mime.utility.js';
22
24
  /** Sends mail through the bound transport. `send` validates the message, applies the attachment policy and defaults `from`; failures are thrown as application errors with a mail message code, except `sendBatch`, which reports each failure in its result. */
23
25
  let MailService = MailService_1 = class MailService extends BaseService {
24
26
  constructor(options, transport, templateEngine) {
@@ -88,7 +90,7 @@ let MailService = MailService_1 = class MailService extends BaseService {
88
90
  catch (error) {
89
91
  return {
90
92
  success: false,
91
- error: error instanceof Error ? error.message : 'Unknown error',
93
+ error: ErrorUtility.toError({ error }).message,
92
94
  };
93
95
  }
94
96
  });
@@ -118,29 +120,28 @@ let MailService = MailService_1 = class MailService extends BaseService {
118
120
  if (!this.templateEngine) {
119
121
  throw getError({
120
122
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
121
- messageCode: MailErrorCodes.INVALID_CONFIGURATION,
123
+ error: MailErrors.INVALID_CONFIGURATION,
122
124
  message: 'Template engine not configured',
123
125
  });
124
126
  }
127
+ // `rest` goes first below: the recipients, the subject and the body this call rendered are not the options' to replace, and `requireValidate` is a render switch, not a message field.
128
+ const { requireValidate, subject, ...rest } = options ?? {};
125
129
  this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);
126
- const html = this.templateEngine.render({
127
- templateName,
128
- data,
129
- requireValidate: options?.requireValidate,
130
- });
130
+ const html = this.templateEngine.render({ templateName, data, requireValidate });
131
131
  const templateData = this.templateEngine.getTemplate(templateName);
132
+ const renderedSubject = templateData?.subject === undefined
133
+ ? MailDefaults.SUBJECT
134
+ : this.templateEngine.render({
135
+ templateData: templateData.subject,
136
+ data,
137
+ requireValidate,
138
+ format: MailTemplateFormats.TEXT,
139
+ });
132
140
  const message = {
141
+ ...rest,
133
142
  to: recipients,
134
- subject: options?.subject ??
135
- (templateData?.subject !== undefined
136
- ? this.templateEngine.render({
137
- templateData: templateData.subject,
138
- data,
139
- requireValidate: options?.requireValidate,
140
- })
141
- : 'No Subject'),
143
+ subject: subject ?? renderedSubject,
142
144
  html,
143
- ...options,
144
145
  };
145
146
  const result = await this.send(message);
146
147
  return result;
@@ -187,6 +188,7 @@ let MailService = MailService_1 = class MailService extends BaseService {
187
188
  });
188
189
  }
189
190
  MailBodyUtility.assertIsText({ message });
191
+ MailHeaderUtility.assert({ message });
190
192
  }
191
193
  getDefaultFrom() {
192
194
  const { from, fromName } = this.options;
@@ -197,7 +199,7 @@ let MailService = MailService_1 = class MailService extends BaseService {
197
199
  if (!fromName) {
198
200
  return from;
199
201
  }
200
- return `"${fromName}" <${from}>`;
202
+ return `"${MailMimeUtility.escapeQuotedString({ value: fromName })}" <${from}>`;
201
203
  }
202
204
  };
203
205
  MailService = MailService_1 = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"mail.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/mail.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AASpD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC/E,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAE3E,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE5D,iQAAiQ;AACjQ,IAAa,WAAW,mBAAxB,MAAa,WAAY,SAAQ,WAAW;IAC1C,YAEY,OAAqB,EAErB,SAAyB,EAEzB,cAAoC;QAE9C,KAAK,CAAC,EAAE,KAAK,EAAE,aAAW,CAAC,IAAI,EAAE,CAAC,CAAC;QANzB,Y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BACb,KAAK,EAAE,UAAU,CAAC,qBAAqB;gBACvC,OAAO,EAAE,2BAA2B;aACrC,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;YACnC,MAAM,QAAQ,CAAC;gBACb,KAAK,EAAE,UAAU,CAAC,qBAAqB;gBACvC,OAAO,EAAE,6CAA6C;aACvD,CAAC,CAAC;QACL,CAAC;QAED,eAAe,CAAC,YAAY,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;IAC5C,CAAC;IAES,cAAc;QACtB,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QAExC,6FAA6F;QAC7F,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,YAAY,CAAC,aAAa,CAAC;QACpC,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,IAAI,QAAQ,MAAM,IAAI,GAAG,CAAC;IACnC,CAAC;CACF,CAAA;AA7NY,WAAW;IAEnB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAA;IAEtC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,oBAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;;GANxD,WAAW,CA6NvB","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport type {\n IMailMessage,\n IMailSendResult,\n IMailService,\n IMailTemplateEngine,\n IMailTransport,\n TMailOptions,\n} from '../common';\nimport { MailDefaults, MailErrorCodes, MailErrors, MailKeys } from '../common';\nimport { inject } from '@/base/metadata';\nimport { getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { type AnyType } from '@venizia/ignis-helpers/common';\nimport { PromiseUtility } from '@venizia/ignis-helpers';\nimport { MailAttachmentUtility } from '../utilities/attachment.utility';\nimport { MailBodyUtility } from '../utilities/body.utility';\n\n/** Sends mail through the bound transport. `send` validates the message, applies the attachment policy and defaults `from`; failures are thrown as application errors with a mail message code, except `sendBatch`, which reports each failure in its result. */\nexport class MailService extends BaseService implements IMailService {\n constructor(\n @inject({ key: MailKeys.MAIL_OPTIONS })\n protected options: TMailOptions,\n @inject({ key: MailKeys.MAIL_TRANSPORT_INSTANCE })\n protected transport: IMailTransport,\n @inject({ key: MailKeys.MAIL_TEMPLATE_ENGINE, isOptional: true })\n protected templateEngine?: IMailTemplateEngine,\n ) {\n super({ scope: MailService.name });\n this.logger\n .for(this.constructor.name)\n .info('Mail service initialized with provider: %s', this.options.provider);\n }\n\n async send(message: IMailMessage): Promise<IMailSendResult> {\n try {\n this.validateMessage(message);\n\n const emailMessage: IMailMessage = {\n ...message,\n from: message.from ?? this.getDefaultFrom(),\n };\n\n // The one place the attachment policy applies: every transport receives bytes, never a path.\n if (message.attachments) {\n const result2 = await MailAttachmentUtility.resolve({\n attachments: message.attachments,\n attachmentRoot: this.options.attachmentRoot,\n maxBytes: this.options.maxAttachmentBytes ?? MailDefaults.MAX_ATTACHMENT_BYTES,\n });\n emailMessage.attachments = result2;\n }\n\n this.logger.for(this.send.name).debug('Sending email to: %s', emailMessage.to);\n const result = await this.transport.send(emailMessage);\n\n if (result.success) {\n this.logger\n .for(this.send.name)\n .debug('Email sent successfully. MessageId: %s', result.messageId);\n } else {\n this.logger.for(this.send.name).debug('Email send failed: %s', result.error);\n }\n\n return result;\n } catch (error) {\n this.logger.for(this.send.name).error('Error sending email: %s', error);\n MailAttachmentUtility.release({ attachments: message.attachments });\n\n // An error the framework already shaped carries its own status and message code; re-wrapping as 500 would report a caller mistake as a server fault.\n if (isApplicationError(error)) {\n throw error;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.SEND_FAILED,\n // The raw text can carry a file path or a provider detail; it rides in `cause`, which only development responses show.\n message: 'Failed to send email',\n cause: error,\n });\n }\n }\n\n async sendBatch(\n messages: IMailMessage[],\n options?: { concurrency?: number },\n ): Promise<IMailSendResult[]> {\n try {\n const concurrency = options?.concurrency ?? MailDefaults.BATCH_CONCURRENCY;\n this.logger\n .for(this.sendBatch.name)\n .info('Sending batch of %d emails with concurrency: %d', messages.length, concurrency);\n\n const tasks = messages.map((message) => async () => {\n try {\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n });\n\n const results = await PromiseUtility.executeWithLimit<IMailSendResult>({\n tasks,\n limit: concurrency,\n });\n\n const successCount = results.filter((r) => r.success).length;\n this.logger\n .for(this.sendBatch.name)\n .info(\n 'Batch send completed. Success: %d, Failed: %d',\n successCount,\n results.length - successCount,\n );\n\n return results;\n } catch (error) {\n this.logger.for(this.sendBatch.name).error('Error sending batch emails: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.BATCH_SEND_FAILED,\n message: 'Failed to send batch emails',\n cause: error,\n });\n }\n }\n\n async sendTemplate(opts: {\n templateName: string;\n data: Record<string, AnyType>;\n recipients: string | string[];\n options?: Partial<IMailMessage>;\n }): Promise<IMailSendResult> {\n const { templateName, data, recipients, options } = opts;\n\n try {\n if (!this.templateEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.INVALID_CONFIGURATION,\n message: 'Template engine not configured',\n });\n }\n\n this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);\n const html = this.templateEngine.render({\n templateName,\n data,\n requireValidate: options?.requireValidate,\n });\n\n const templateData = this.templateEngine.getTemplate(templateName);\n\n const message: IMailMessage = {\n to: recipients,\n subject:\n options?.subject ??\n (templateData?.subject !== undefined\n ? this.templateEngine.render({\n templateData: templateData.subject,\n data,\n requireValidate: options?.requireValidate,\n })\n : 'No Subject'),\n html,\n ...options,\n };\n\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n this.logger.for(this.sendTemplate.name).error('Error sending template email: %s', error);\n throw error;\n }\n }\n\n async verify(): Promise<boolean> {\n try {\n this.logger.for(this.verify.name).debug('Verifying mail transport connection');\n const isValid = await this.transport.verify();\n this.logger.for(this.verify.name).debug('Verification result: %s', isValid);\n\n return isValid;\n } catch (error) {\n this.logger.for(this.verify.name).error('Verification failed: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.VERIFICATION_FAILED,\n message: 'Mail transport verification failed',\n cause: error,\n });\n }\n }\n\n protected validateMessage(message: IMailMessage): void {\n if (!message.to || (Array.isArray(message.to) && message.to.length === 0)) {\n throw getError({\n error: MailErrors.INVALID_RECIPIENT,\n message: 'Recipient email address is required',\n });\n }\n\n if (!message.subject) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email subject is required',\n });\n }\n\n if (!message.text && !message.html) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email must have either text or html content',\n });\n }\n\n MailBodyUtility.assertIsText({ message });\n }\n\n protected getDefaultFrom(): string {\n const { from, fromName } = this.options;\n\n // A display name is only renderable around an address: `\"Name\" <undefined>` is not a sender.\n if (!from) {\n return MailDefaults.FALLBACK_FROM;\n }\n\n if (!fromName) {\n return from;\n }\n\n return `\"${fromName}\" <${from}>`;\n }\n}\n"]}
1
+ {"version":3,"file":"mail.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/mail.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AASpD,OAAO,EAAE,YAAY,EAAE,cAAc,E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AAI,CAAC,OAAO,CAAC;QAExC,6FAA6F;QAC7F,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,YAAY,CAAC,aAAa,CAAC;QACpC,CAAC;QAED,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,IAAI,eAAe,CAAC,kBAAkB,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,MAAM,IAAI,GAAG,CAAC;IAClF,CAAC;CACF,CAAA;AA9NY,WAAW;IAEnB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAA;IAEtC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,uBAAuB,EAAE,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,QAAQ,CAAC,oBAAoB,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAA;;GANxD,WAAW,CA8NvB","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { BaseService } from '@venizia/ignis-kernel';\nimport type {\n IMailMessage,\n IMailSendResult,\n IMailService,\n IMailTemplateEngine,\n IMailTransport,\n TMailOptions,\n} from '../common';\nimport { MailDefaults, MailErrorCodes, MailErrors, MailKeys, MailTemplateFormats } from '../common';\nimport { inject } from '@/base/metadata';\nimport { getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { type AnyType } from '@venizia/ignis-helpers/common';\nimport { ErrorUtility, PromiseUtility } from '@venizia/ignis-helpers';\nimport { MailAttachmentUtility } from '../utilities/attachment.utility';\nimport { MailBodyUtility } from '../utilities/body.utility';\nimport { MailHeaderUtility } from '../utilities/header.utility';\nimport { MailMimeUtility } from '../utilities/mime.utility';\n\n/** Sends mail through the bound transport. `send` validates the message, applies the attachment policy and defaults `from`; failures are thrown as application errors with a mail message code, except `sendBatch`, which reports each failure in its result. */\nexport class MailService extends BaseService implements IMailService {\n constructor(\n @inject({ key: MailKeys.MAIL_OPTIONS })\n protected options: TMailOptions,\n @inject({ key: MailKeys.MAIL_TRANSPORT_INSTANCE })\n protected transport: IMailTransport,\n @inject({ key: MailKeys.MAIL_TEMPLATE_ENGINE, isOptional: true })\n protected templateEngine?: IMailTemplateEngine,\n ) {\n super({ scope: MailService.name });\n this.logger\n .for(this.constructor.name)\n .info('Mail service initialized with provider: %s', this.options.provider);\n }\n\n async send(message: IMailMessage): Promise<IMailSendResult> {\n try {\n this.validateMessage(message);\n\n const emailMessage: IMailMessage = {\n ...message,\n from: message.from ?? this.getDefaultFrom(),\n };\n\n // The one place the attachment policy applies: every transport receives bytes, never a path.\n if (message.attachments) {\n const result2 = await MailAttachmentUtility.resolve({\n attachments: message.attachments,\n attachmentRoot: this.options.attachmentRoot,\n maxBytes: this.options.maxAttachmentBytes ?? MailDefaults.MAX_ATTACHMENT_BYTES,\n });\n emailMessage.attachments = result2;\n }\n\n this.logger.for(this.send.name).debug('Sending email to: %s', emailMessage.to);\n const result = await this.transport.send(emailMessage);\n\n if (result.success) {\n this.logger\n .for(this.send.name)\n .debug('Email sent successfully. MessageId: %s', result.messageId);\n } else {\n this.logger.for(this.send.name).debug('Email send failed: %s', result.error);\n }\n\n return result;\n } catch (error) {\n this.logger.for(this.send.name).error('Error sending email: %s', error);\n MailAttachmentUtility.release({ attachments: message.attachments });\n\n // An error the framework already shaped carries its own status and message code; re-wrapping as 500 would report a caller mistake as a server fault.\n if (isApplicationError(error)) {\n throw error;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.SEND_FAILED,\n // The raw text can carry a file path or a provider detail; it rides in `cause`, which only development responses show.\n message: 'Failed to send email',\n cause: error,\n });\n }\n }\n\n async sendBatch(\n messages: IMailMessage[],\n options?: { concurrency?: number },\n ): Promise<IMailSendResult[]> {\n try {\n const concurrency = options?.concurrency ?? MailDefaults.BATCH_CONCURRENCY;\n this.logger\n .for(this.sendBatch.name)\n .info('Sending batch of %d emails with concurrency: %d', messages.length, concurrency);\n\n const tasks = messages.map((message) => async () => {\n try {\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n return {\n success: false,\n error: ErrorUtility.toError({ error }).message,\n };\n }\n });\n\n const results = await PromiseUtility.executeWithLimit<IMailSendResult>({\n tasks,\n limit: concurrency,\n });\n\n const successCount = results.filter((r) => r.success).length;\n this.logger\n .for(this.sendBatch.name)\n .info(\n 'Batch send completed. Success: %d, Failed: %d',\n successCount,\n results.length - successCount,\n );\n\n return results;\n } catch (error) {\n this.logger.for(this.sendBatch.name).error('Error sending batch emails: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.BATCH_SEND_FAILED,\n message: 'Failed to send batch emails',\n cause: error,\n });\n }\n }\n\n async sendTemplate(opts: {\n templateName: string;\n data: Record<string, AnyType>;\n recipients: string | string[];\n options?: Partial<IMailMessage>;\n }): Promise<IMailSendResult> {\n const { templateName, data, recipients, options } = opts;\n\n try {\n if (!this.templateEngine) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Template engine not configured',\n });\n }\n\n // `rest` goes first below: the recipients, the subject and the body this call rendered are not the options' to replace, and `requireValidate` is a render switch, not a message field.\n const { requireValidate, subject, ...rest } = options ?? {};\n\n this.logger.for(this.sendTemplate.name).debug('Rendering template: %s', templateName);\n const html = this.templateEngine.render({ templateName, data, requireValidate });\n\n const templateData = this.templateEngine.getTemplate(templateName);\n const renderedSubject =\n templateData?.subject === undefined\n ? MailDefaults.SUBJECT\n : this.templateEngine.render({\n templateData: templateData.subject,\n data,\n requireValidate,\n format: MailTemplateFormats.TEXT,\n });\n\n const message: IMailMessage = {\n ...rest,\n to: recipients,\n subject: subject ?? renderedSubject,\n html,\n };\n\n const result = await this.send(message);\n\n return result;\n } catch (error) {\n this.logger.for(this.sendTemplate.name).error('Error sending template email: %s', error);\n throw error;\n }\n }\n\n async verify(): Promise<boolean> {\n try {\n this.logger.for(this.verify.name).debug('Verifying mail transport connection');\n const isValid = await this.transport.verify();\n this.logger.for(this.verify.name).debug('Verification result: %s', isValid);\n\n return isValid;\n } catch (error) {\n this.logger.for(this.verify.name).error('Verification failed: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n messageCode: MailErrorCodes.VERIFICATION_FAILED,\n message: 'Mail transport verification failed',\n cause: error,\n });\n }\n }\n\n protected validateMessage(message: IMailMessage): void {\n if (!message.to || (Array.isArray(message.to) && message.to.length === 0)) {\n throw getError({\n error: MailErrors.INVALID_RECIPIENT,\n message: 'Recipient email address is required',\n });\n }\n\n if (!message.subject) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email subject is required',\n });\n }\n\n if (!message.text && !message.html) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: 'Email must have either text or html content',\n });\n }\n\n MailBodyUtility.assertIsText({ message });\n MailHeaderUtility.assert({ message });\n }\n\n protected getDefaultFrom(): string {\n const { from, fromName } = this.options;\n\n // A display name is only renderable around an address: `\"Name\" <undefined>` is not a sender.\n if (!from) {\n return MailDefaults.FALLBACK_FROM;\n }\n\n if (!fromName) {\n return from;\n }\n\n return `\"${MailMimeUtility.escapeQuotedString({ value: fromName })}\" <${from}>`;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { BaseService } from '@venizia/ignis-kernel';
2
- import type { IMailTemplateEngine, ITemplate } from '../common/index.js';
2
+ import type { IMailTemplateEngine, ITemplate, TMailTemplateFormat } from '../common/index.js';
3
3
  import type { AnyType } from '@venizia/ignis-helpers/common';
4
4
  /** In-memory template store and renderer. Templates registered here are lost on restart. */
5
5
  export declare class TemplateEngineService extends BaseService implements IMailTemplateEngine {
@@ -15,6 +15,7 @@ export declare class TemplateEngineService extends BaseService implements IMailT
15
15
  templateName?: string;
16
16
  data: Record<string, AnyType>;
17
17
  requireValidate?: boolean;
18
+ format?: TMailTemplateFormat;
18
19
  }): string;
19
20
  getTemplate(name: string): ITemplate | undefined;
20
21
  listTemplates(): ITemplate[];
@@ -31,7 +32,9 @@ export declare class TemplateEngineService extends BaseService implements IMailT
31
32
  };
32
33
  renderSimpleTemplate(template: string, data: Record<string, AnyType>, opts?: {
33
34
  requireValidate?: boolean;
35
+ format?: TMailTemplateFormat;
34
36
  }): string;
37
+ /** Reads own properties only: `{{constructor}}` or `{{__proto__.x}}` must not reach the prototype chain. */
35
38
  private getNestedValue;
36
39
  }
37
40
  //# sourceMappingURL=template.service.d.ts.map
@@ -1,6 +1,8 @@
1
1
  import { BaseService } from '@venizia/ignis-kernel';
2
- import { MailErrors } from '../common/index.js';
2
+ import { MailErrors, MailTemplateFormats } from '../common/index.js';
3
3
  import { getError } from '@venizia/ignis-helpers/core';
4
+ /** `{{{key}}}` (group 1, raw) or `{{key}}` (group 2). The raw form comes first: `{{key}}` also matches inside it. */
5
+ const PLACEHOLDER = /\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*([\w.]+)\s*\}\}/g;
4
6
  /** In-memory template store and renderer. Templates registered here are lost on restart. */
5
7
  export class TemplateEngineService extends BaseService {
6
8
  constructor() {
@@ -20,7 +22,7 @@ export class TemplateEngineService extends BaseService {
20
22
  this.templates.set(name, template);
21
23
  }
22
24
  render(opts) {
23
- const { templateData, templateName, data, requireValidate } = opts;
25
+ const { templateData, templateName, data, requireValidate, format } = opts;
24
26
  if (!templateData && !templateName) {
25
27
  throw getError({ message: 'Either templateName or templateData must be provided' });
26
28
  }
@@ -36,8 +38,13 @@ export class TemplateEngineService extends BaseService {
36
38
  this.logger.for(this.render.name).debug('Rendering template: %s', templateName);
37
39
  content = template.content;
38
40
  }
39
- // TODO: check content! later
40
- return this.renderSimpleTemplate(content, data, { requireValidate });
41
+ if (content === undefined) {
42
+ throw getError({
43
+ error: MailErrors.INVALID_CONFIGURATION,
44
+ message: `Template has no content: ${templateName}`,
45
+ });
46
+ }
47
+ return this.renderSimpleTemplate(content, data, { requireValidate, format });
41
48
  }
42
49
  getTemplate(name) {
43
50
  return this.templates.get(name);
@@ -58,12 +65,10 @@ export class TemplateEngineService extends BaseService {
58
65
  }
59
66
  validateTemplateData(opts) {
60
67
  const { template, data } = opts;
61
- const placeholderRegex = /\{\{(\s*[\w.]+\s*)\}\}/g;
62
68
  const allKeys = [];
63
69
  const missingKeys = [];
64
- let match;
65
- while ((match = placeholderRegex.exec(template)) !== null) {
66
- const key = match[1].trim();
70
+ for (const match of template.matchAll(PLACEHOLDER)) {
71
+ const key = match[1] ?? match[2];
67
72
  if (allKeys.includes(key)) {
68
73
  continue;
69
74
  }
@@ -91,21 +96,24 @@ export class TemplateEngineService extends BaseService {
91
96
  });
92
97
  }
93
98
  }
94
- return template.replace(/\{\{(\s*[\w.]+\s*)\}\}/g, (match, key) => {
95
- const trimmedKey = key.trim();
96
- const value = this.getNestedValue(data, trimmedKey);
99
+ const isHtml = (opts?.format ?? MailTemplateFormats.HTML) === MailTemplateFormats.HTML;
100
+ return template.replace(PLACEHOLDER, (match, tripleKey, doubleKey) => {
101
+ const key = tripleKey ?? doubleKey ?? '';
102
+ const value = this.getNestedValue(data, key);
97
103
  if (value === undefined || value === null) {
98
- this.logger
99
- .for(this.renderSimpleTemplate.name)
100
- .warn('Missing value for key: %s', trimmedKey);
104
+ this.logger.for(this.renderSimpleTemplate.name).warn('Missing value for key: %s', key);
101
105
  return match;
102
106
  }
103
- return String(value);
107
+ // `{{{key}}}` inserts as it is; `{{key}}` is escaped for HTML.
108
+ return isHtml && tripleKey === undefined ? Bun.escapeHTML(String(value)) : String(value);
104
109
  });
105
110
  }
111
+ /** Reads own properties only: `{{constructor}}` or `{{__proto__.x}}` must not reach the prototype chain. */
106
112
  getNestedValue(obj, path) {
107
113
  return path.split('.').reduce((current, key) => {
108
- return current?.[key];
114
+ return current !== null && typeof current === 'object' && Object.hasOwn(current, key)
115
+ ? current[key]
116
+ : undefined;
109
117
  }, obj);
110
118
  }
111
119
  }
@@ -1 +1 @@
1
- {"version":3,"file":"template.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/template.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,4FAA4F;AAC5F,MAAM,OAAO,qBAAsB,SAAQ,WAAW;IAGpD;QACE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;QAHvC,cAAS,GAA2B,IAAI,GAAG,EAAE,CAAC;QAIpD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC;IAC7E,CAAC;IAED,gBAAgB,CAAC,IAAqE;QACpF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACxC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,0BAA0B,EAAE,IAAI,CAAC,CAAC;QAEnF,MAAM,QAAQ,GAAc;YAC1B,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,OAAO,EAAE,OAAO;YACzB,WAAW,EAAE,OAAO,EAAE,WAAW;SAClC,CAAC;QAEF,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACrC,CAAC;IAED,MAAM,CAAC,IAKN;QACC,MAAM,EAAE,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,eAAe,EAAE,GAAG,IAAI,CAAC;QAEnE,IAAI,CAAC,YAAY,IAAI,CAAC,YAAY,EAAE,CAAC;YACnC,MAAM,QAAQ,CAAC,EAAE,OAAO,EAA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AC;IACV,CAAC;CACF","sourcesContent":["import { BaseService } from '@venizia/ignis-kernel';\nimport type { IMailTemplateEngine, ITemplate } from '../common';\nimport { MailErrors } from '../common';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** In-memory template store and renderer. Templates registered here are lost on restart. */\nexport class TemplateEngineService extends BaseService implements IMailTemplateEngine {\n private templates: Map<string, ITemplate> = new Map();\n\n constructor() {\n super({ scope: TemplateEngineService.name });\n this.logger.for(this.constructor.name).info('Template engine initialized');\n }\n\n registerTemplate(opts: { name: string; content: string; options?: Partial<ITemplate> }): void {\n const { name, content, options } = opts;\n this.logger.for(this.registerTemplate.name).info('Registering template: %s', name);\n\n const template: ITemplate = {\n name,\n content,\n subject: options?.subject,\n description: options?.description,\n };\n\n this.templates.set(name, template);\n }\n\n render(opts: {\n templateData?: string;\n templateName?: string;\n data: Record<string, AnyType>;\n requireValidate?: boolean;\n }): string {\n const { templateData, templateName, data, requireValidate } = opts;\n\n if (!templateData && !templateName) {\n throw getError({ message: 'Either templateName or templateData must be provided' });\n }\n\n let content = templateData;\n\n if (!content && templateName) {\n const template = this.templates.get(templateName);\n\n if (!template) {\n throw getError({\n error: MailErrors.TEMPLATE_NOT_FOUND,\n message: `Template not found: ${templateName}`,\n });\n }\n\n this.logger.for(this.render.name).debug('Rendering template: %s', templateName);\n\n content = template.content;\n }\n\n // TODO: check content! later\n return this.renderSimpleTemplate(content!, data, { requireValidate });\n }\n\n getTemplate(name: string): ITemplate | undefined {\n return this.templates.get(name);\n }\n\n listTemplates(): ITemplate[] {\n return Array.from(this.templates.values());\n }\n\n hasTemplate(name: string): boolean {\n return this.templates.has(name);\n }\n\n removeTemplate(name: string): boolean {\n this.logger.for(this.removeTemplate.name).info('Removing template: %s', name);\n\n return this.templates.delete(name);\n }\n\n clearTemplates(): void {\n this.logger.for(this.clearTemplates.name).info('Clearing all templates');\n this.templates.clear();\n }\n\n validateTemplateData(opts: { template: string; data: Record<string, AnyType> }): {\n isValid: boolean;\n missingKeys: string[];\n allKeys: string[];\n } {\n const { template, data } = opts;\n const placeholderRegex = /\\{\\{(\\s*[\\w.]+\\s*)\\}\\}/g;\n const allKeys: string[] = [];\n const missingKeys: string[] = [];\n\n let match: RegExpExecArray | null;\n\n while ((match = placeholderRegex.exec(template)) !== null) {\n const key = match[1].trim();\n\n if (allKeys.includes(key)) {\n continue;\n }\n\n allKeys.push(key);\n\n const value = this.getNestedValue(data, key);\n\n if (value === undefined || value === null) {\n missingKeys.push(key);\n }\n }\n\n const isValid = missingKeys.length === 0;\n\n if (!isValid) {\n this.logger\n .for(this.validateTemplateData.name)\n .warn('Template validation failed | Missing keys: %s', missingKeys.join(', '));\n }\n\n return { isValid, missingKeys, allKeys };\n }\n\n renderSimpleTemplate(\n template: string,\n data: Record<string, AnyType>,\n opts?: { requireValidate?: boolean },\n ): string {\n if (opts?.requireValidate) {\n const validation = this.validateTemplateData({ template, data });\n\n if (!validation.isValid) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Missing template data for keys: ${validation.missingKeys.join(', ')}`,\n });\n }\n }\n\n return template.replace(/\\{\\{(\\s*[\\w.]+\\s*)\\}\\}/g, (match, key) => {\n const trimmedKey = key.trim();\n const value = this.getNestedValue(data, trimmedKey);\n\n if (value === undefined || value === null) {\n this.logger\n .for(this.renderSimpleTemplate.name)\n .warn('Missing value for key: %s', trimmedKey);\n\n return match;\n }\n\n return String(value);\n });\n }\n\n private getNestedValue(obj: AnyType, path: string) {\n return path.split('.').reduce((current, key) => {\n return current?.[key];\n }, obj);\n }\n}\n"]}
1
+ {"version":3,"file":"template.service.js","sourceRoot":"","sources":["../../../../../src/components/mail/services/template.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,EAAE,QAAQ,EAAE,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AE,IAAY;QAC/C,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE;YAC7C,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC;gBACnF,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;gBACd,CAAC,CAAC,SAAS,CAAC;QAChB,CAAC,EAAE,GAAG,CAAC,CAAC;IACV,CAAC;CACF","sourcesContent":["import { BaseService } from '@venizia/ignis-kernel';\nimport type { IMailTemplateEngine, ITemplate, TMailTemplateFormat } from '../common';\nimport { MailErrors, MailTemplateFormats } from '../common';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** `{{{key}}}` (group 1, raw) or `{{key}}` (group 2). The raw form comes first: `{{key}}` also matches inside it. */\nconst PLACEHOLDER = /\\{\\{\\{\\s*([\\w.]+)\\s*\\}\\}\\}|\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g;\n\n/** In-memory template store and renderer. Templates registered here are lost on restart. */\nexport class TemplateEngineService extends BaseService implements IMailTemplateEngine {\n private templates: Map<string, ITemplate> = new Map();\n\n constructor() {\n super({ scope: TemplateEngineService.name });\n this.logger.for(this.constructor.name).info('Template engine initialized');\n }\n\n registerTemplate(opts: { name: string; content: string; options?: Partial<ITemplate> }): void {\n const { name, content, options } = opts;\n this.logger.for(this.registerTemplate.name).info('Registering template: %s', name);\n\n const template: ITemplate = {\n name,\n content,\n subject: options?.subject,\n description: options?.description,\n };\n\n this.templates.set(name, template);\n }\n\n render(opts: {\n templateData?: string;\n templateName?: string;\n data: Record<string, AnyType>;\n requireValidate?: boolean;\n format?: TMailTemplateFormat;\n }): string {\n const { templateData, templateName, data, requireValidate, format } = opts;\n\n if (!templateData && !templateName) {\n throw getError({ message: 'Either templateName or templateData must be provided' });\n }\n\n let content = templateData;\n\n if (!content && templateName) {\n const template = this.templates.get(templateName);\n\n if (!template) {\n throw getError({\n error: MailErrors.TEMPLATE_NOT_FOUND,\n message: `Template not found: ${templateName}`,\n });\n }\n\n this.logger.for(this.render.name).debug('Rendering template: %s', templateName);\n\n content = template.content;\n }\n\n if (content === undefined) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Template has no content: ${templateName}`,\n });\n }\n\n return this.renderSimpleTemplate(content, data, { requireValidate, format });\n }\n\n getTemplate(name: string): ITemplate | undefined {\n return this.templates.get(name);\n }\n\n listTemplates(): ITemplate[] {\n return Array.from(this.templates.values());\n }\n\n hasTemplate(name: string): boolean {\n return this.templates.has(name);\n }\n\n removeTemplate(name: string): boolean {\n this.logger.for(this.removeTemplate.name).info('Removing template: %s', name);\n\n return this.templates.delete(name);\n }\n\n clearTemplates(): void {\n this.logger.for(this.clearTemplates.name).info('Clearing all templates');\n this.templates.clear();\n }\n\n validateTemplateData(opts: { template: string; data: Record<string, AnyType> }): {\n isValid: boolean;\n missingKeys: string[];\n allKeys: string[];\n } {\n const { template, data } = opts;\n const allKeys: string[] = [];\n const missingKeys: string[] = [];\n\n for (const match of template.matchAll(PLACEHOLDER)) {\n const key = match[1] ?? match[2];\n\n if (allKeys.includes(key)) {\n continue;\n }\n\n allKeys.push(key);\n\n const value = this.getNestedValue(data, key);\n\n if (value === undefined || value === null) {\n missingKeys.push(key);\n }\n }\n\n const isValid = missingKeys.length === 0;\n\n if (!isValid) {\n this.logger\n .for(this.validateTemplateData.name)\n .warn('Template validation failed | Missing keys: %s', missingKeys.join(', '));\n }\n\n return { isValid, missingKeys, allKeys };\n }\n\n renderSimpleTemplate(\n template: string,\n data: Record<string, AnyType>,\n opts?: { requireValidate?: boolean; format?: TMailTemplateFormat },\n ): string {\n if (opts?.requireValidate) {\n const validation = this.validateTemplateData({ template, data });\n\n if (!validation.isValid) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message: `Missing template data for keys: ${validation.missingKeys.join(', ')}`,\n });\n }\n }\n\n const isHtml = (opts?.format ?? MailTemplateFormats.HTML) === MailTemplateFormats.HTML;\n\n return template.replace(PLACEHOLDER, (match, tripleKey?: string, doubleKey?: string) => {\n const key = tripleKey ?? doubleKey ?? '';\n const value = this.getNestedValue(data, key);\n\n if (value === undefined || value === null) {\n this.logger.for(this.renderSimpleTemplate.name).warn('Missing value for key: %s', key);\n\n return match;\n }\n\n // `{{{key}}}` inserts as it is; `{{key}}` is escaped for HTML.\n return isHtml && tripleKey === undefined ? Bun.escapeHTML(String(value)) : String(value);\n });\n }\n\n /** Reads own properties only: `{{constructor}}` or `{{__proto__.x}}` must not reach the prototype chain. */\n private getNestedValue(obj: AnyType, path: string) {\n return path.split('.').reduce((current, key) => {\n return current !== null && typeof current === 'object' && Object.hasOwn(current, key)\n ? current[key]\n : undefined;\n }, obj);\n }\n}\n"]}
@@ -185,12 +185,14 @@ export class MailAttachmentUtility {
185
185
  const filename = rest.filename ?? (isReadFromPath ? basename(path) : undefined);
186
186
  const contentType = rest.contentType ??
187
187
  (isReadFromPath && filename ? ContentTypeTable.resolve({ filename }) : undefined);
188
- resolved.push({
189
- ...rest,
190
- ...(filename === undefined ? {} : { filename }),
191
- ...(contentType === undefined ? {} : { contentType }),
192
- content: bytes,
193
- });
188
+ const item = { ...rest, content: bytes };
189
+ if (filename !== undefined) {
190
+ item.filename = filename;
191
+ }
192
+ if (contentType !== undefined) {
193
+ item.contentType = contentType;
194
+ }
195
+ resolved.push(item);
194
196
  }
195
197
  return resolved;
196
198
  }
@@ -1 +1 @@
1
- {"version":3,"file":"attachment.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/attachment.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,UAAU,EA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 'node:fs';\nimport { open, realpath, type FileHandle } from 'node:fs/promises';\nimport { basename, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { ContentTypeTable } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { LoggerFactory } from '@venizia/ignis-helpers';\nimport { MailErrors, type IMailAttachment } from '../common';\n\nconst logger = LoggerFactory.getLogger(['MailAttachments']);\n\n// O_NONBLOCK: opening a FIFO must not wait for a writer; the fstat check then refuses it.\n// Windows has neither flag; there the realpath containment check stands alone.\nconst OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// One reason for missing, directory, unreadable and escaping paths: no existence oracle.\nconst PATH_OUTSIDE_REASON =\n 'attachment.path must name a readable file inside attachmentRoot | pass the bytes as content instead';\n\ntype TAttachmentStream = AsyncIterable<Uint8Array | string>;\n\nconst buildPathRefusedError = (opts: { reason: string; cause?: unknown }) => {\n return getError({\n error: MailErrors.ATTACHMENT_PATH_REFUSED,\n message: `Mail attachment path refused | ${opts.reason}`,\n cause: opts.cause,\n });\n};\n\nconst buildTooLargeError = (opts: { maxBytes: number }) => {\n return getError({\n error: MailErrors.ATTACHMENT_TOO_LARGE,\n message: `Mail attachments are over maxAttachmentBytes (${opts.maxBytes} bytes per message) | raise maxAttachmentBytes on the mail options, or send smaller attachments`,\n });\n};\n\nconst assertWithinLimit = (opts: { byteLength: number; usedBytes: number; maxBytes?: number }) => {\n const { byteLength, usedBytes, maxBytes } = opts;\n\n if (maxBytes === undefined || usedBytes + byteLength <= maxBytes) {\n return;\n }\n\n throw buildTooLargeError({ maxBytes });\n};\n\nconst isAttachmentStream = (value: unknown): value is TAttachmentStream => {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value;\n};\n\nconst toBuffer = (chunk: Uint8Array | string): Buffer => {\n if (typeof chunk === 'string') {\n return Buffer.from(chunk);\n }\n\n return Buffer.isBuffer(chunk)\n ? chunk\n : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n};\n\n/** Throwing out of `for await` destroys a Node Readable and cancels a web ReadableStream. */\nconst drainStream = async (opts: {\n stream: TAttachmentStream;\n usedBytes: number;\n maxBytes?: number;\n}): Promise<Buffer> => {\n const { stream, usedBytes, maxBytes } = opts;\n const chunks: Buffer[] = [];\n let streamBytes = 0;\n\n for await (const chunk of stream) {\n const buffer = toBuffer(chunk);\n streamBytes += buffer.byteLength;\n\n // Per chunk: a stream has no length up front, and the rest must never be buffered.\n assertWithinLimit({ byteLength: streamBytes, usedBytes, maxBytes });\n chunks.push(buffer);\n }\n\n return Buffer.concat(chunks, streamBytes);\n};\n\n/**\n * Both sides go through realpath, so neither `..` nor a symlink can leave the root. Not closed: a\n * directory inside the root swapped for a symlink between this check and `open` - that takes write\n * access inside the root, so keep the root writable only by what the application trusts.\n */\nconst resolveConfinedPath = async (opts: {\n path: string;\n attachmentRoot: string;\n}): Promise<string> => {\n const { path, attachmentRoot } = opts;\n\n let rootPath: string;\n let filePath: string;\n\n // `resolve` throws synchronously on a non-string `path` from an untyped caller; it lands here too.\n try {\n const resolved = await Promise.all([\n realpath(attachmentRoot),\n realpath(resolve(attachmentRoot, path)),\n ]);\n [rootPath, filePath] = resolved;\n } catch (error) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON, cause: error });\n }\n\n const relation = relative(rootPath, filePath);\n const isOutside =\n relation === '' || relation === '..' || relation.startsWith(`..${sep}`) || isAbsolute(relation);\n\n if (isOutside) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON });\n }\n\n return filePath;\n};\n\nconst readConfinedFile = async (opts: {\n path: string;\n usedBytes: number;\n attachmentRoot?: string;\n maxBytes?: number;\n}): Promise<Buffer> => {\n const { path, usedBytes, attachmentRoot, maxBytes } = opts;\n\n if (!attachmentRoot) {\n throw buildPathRefusedError({\n reason:\n 'attachment.path is read only under attachmentRoot, which is not set | set attachmentRoot on the mail options, or pass the bytes as content',\n });\n }\n\n const filePath = await resolveConfinedPath({ path, attachmentRoot });\n let handle: FileHandle;\n\n try {\n const opened = await open(filePath, OPEN_FLAGS);\n handle = opened;\n } catch (error) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON, cause: error });\n }\n\n try {\n const stats = await handle.stat();\n\n if (!stats.isFile()) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON });\n }\n\n // Sized before reading, so a file known to be oversized is never opened for reading.\n assertWithinLimit({ byteLength: stats.size, usedBytes, maxBytes });\n\n // Counted while read, and read no further than one byte past the budget: the file may have\n // grown since fstat.\n const stream = handle.createReadStream({\n autoClose: false,\n end: maxBytes === undefined ? Infinity : maxBytes - usedBytes,\n });\n\n const result = await drainStream({ stream, usedBytes, maxBytes });\n\n return result;\n } finally {\n await handle.close();\n }\n};\n\nexport class MailAttachmentUtility {\n /**\n * Reads one attachment's bytes. A string `content` is raw text unless `encoding` says otherwise\n * (nodemailer's convention); `null` counts as absent. A `path` is read only inside\n * `attachmentRoot` and refused without one. `maxBytes` caps the whole message; `usedBytes` is what\n * earlier attachments already took.\n */\n static async readContent(opts: {\n attachment: IMailAttachment;\n attachmentRoot?: string;\n maxBytes?: number;\n usedBytes?: number;\n }): Promise<Buffer> {\n const { attachment, attachmentRoot, maxBytes, usedBytes = 0 } = opts;\n const { content } = attachment;\n\n if (content !== undefined && content !== null) {\n if (typeof content === 'string') {\n const encoding = attachment.encoding ?? 'utf-8';\n assertWithinLimit({\n byteLength: Buffer.byteLength(content, encoding),\n usedBytes,\n maxBytes,\n });\n\n return Buffer.from(content, encoding);\n }\n\n if (content instanceof Uint8Array) {\n assertWithinLimit({ byteLength: content.byteLength, usedBytes, maxBytes });\n\n return toBuffer(content);\n }\n\n if (!isAttachmentStream(content)) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message:\n 'Invalid mail attachment | attachment.content must be a Buffer, a Uint8Array, a string or a stream',\n });\n }\n\n return drainStream({ stream: content, usedBytes, maxBytes });\n }\n\n if (attachment.path !== undefined && attachment.path !== null) {\n return readConfinedFile({ path: attachment.path, usedBytes, attachmentRoot, maxBytes });\n }\n\n return Buffer.alloc(0);\n }\n\n /**\n * Turns every attachment into `content` bytes and drops `path`, so no transport is ever handed a\n * file or URL to read on its own. `maxBytes` is shared by all attachments of the message. An\n * attachment read from `path` keeps the file's name and, when none is given, its content type.\n */\n static async resolve(opts: {\n attachments: IMailAttachment[];\n attachmentRoot?: string;\n maxBytes?: number;\n }): Promise<IMailAttachment[]> {\n const { attachments, attachmentRoot, maxBytes } = opts;\n const resolved: IMailAttachment[] = [];\n let usedBytes = 0;\n\n // Sequential on purpose: each read spends the budget the previous ones left.\n for (const attachment of attachments) {\n const { path, href, raw, content, encoding, ...rest } = attachment;\n\n // nodemailer reads both on its own - `href` fetches a URL, `raw` can carry a `path`.\n if ((href !== undefined && href !== null) || (raw !== undefined && raw !== null)) {\n throw buildPathRefusedError({\n reason:\n 'attachment.href and attachment.raw are not supported | pass the bytes as content',\n });\n }\n\n const bytes = await MailAttachmentUtility.readContent({\n attachment: { content, encoding, path },\n attachmentRoot,\n maxBytes,\n usedBytes,\n });\n\n usedBytes += bytes.byteLength;\n\n const isReadFromPath =\n (content === undefined || content === null) && typeof path === 'string';\n const filename = rest.filename ?? (isReadFromPath ? basename(path) : undefined);\n const contentType =\n rest.contentType ??\n (isReadFromPath && filename ? ContentTypeTable.resolve({ filename }) : undefined);\n\n resolved.push({\n ...rest,\n ...(filename === undefined ? {} : { filename }),\n ...(contentType === undefined ? {} : { contentType }),\n content: bytes,\n });\n }\n\n return resolved;\n }\n\n /**\n * Releases every attachment stream of a refused send, read or not, so none keeps a descriptor\n * open. A drained stream is already closed; releasing it again is harmless.\n */\n static release(opts: { attachments?: IMailAttachment[] }): void {\n for (const attachment of opts.attachments ?? []) {\n const { content } = attachment;\n\n if (content instanceof ReadableStream) {\n if (!content.locked) {\n content.cancel().catch((error) => {\n logger.warn(\n '[MailAttachmentUtility.release] Cancelling a web stream failed | error: %s',\n error,\n );\n });\n }\n\n continue;\n }\n\n if (\n typeof content === 'object' &&\n content !== null &&\n 'destroy' in content &&\n typeof content.destroy === 'function'\n ) {\n content.destroy();\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"attachment.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/attachment.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAwB,MAAM,WAAW,CAAC;AAE7D,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC;AAE5D,0FAA0F;AAC1F,+EAA+E;AAC/E,MAAM,UAAU,GAAG,SAAS,CAAC,QAAQ,GAAG,CAAC,SAAS,CAAC,UAAU,IAAI,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC;AAElG,yFAAyF;AACzF,MAAM,mBAAmB,GACvB,qGAAqG,CAAC;AAIxG,MAAM,qBAAqB,GAAG,CAAC,IAAyC,EAAE,EAAE;IAC1E,OAAO,QAAQ,CAAC;QACd,KAAK,EAAE,UAAU,CAAC,uBAAuB;QACzC,OAAO,EAAE,kCAAkC,IAAI,CAAC,MAAM,EAAE;QACxD,KAAK,EAAE,IAAI,CAAC,KAAK;KAClB,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,kBAAkB,GAAG,CAAC,IA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AM,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;wBAC/B,MAAM,CAAC,IAAI,CACT,4EAA4E,EAC5E,KAAK,CACN,CAAC;oBACJ,CAAC,CAAC,CAAC;gBACL,CAAC;gBAED,SAAS;YACX,CAAC;YAED,IACE,OAAO,OAAO,KAAK,QAAQ;gBAC3B,OAAO,KAAK,IAAI;gBAChB,SAAS,IAAI,OAAO;gBACpB,OAAO,OAAO,CAAC,OAAO,KAAK,UAAU,EACrC,CAAC;gBACD,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { constants } from 'node:fs';\nimport { open, realpath, type FileHandle } from 'node:fs/promises';\nimport { basename, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { ContentTypeTable } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { LoggerFactory } from '@venizia/ignis-helpers';\nimport { MailErrors, type IMailAttachment } from '../common';\n\nconst logger = LoggerFactory.getLogger(['MailAttachments']);\n\n// O_NONBLOCK: opening a FIFO must not wait for a writer; the fstat check then refuses it.\n// Windows has neither flag; there the realpath containment check stands alone.\nconst OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// One reason for missing, directory, unreadable and escaping paths: no existence oracle.\nconst PATH_OUTSIDE_REASON =\n 'attachment.path must name a readable file inside attachmentRoot | pass the bytes as content instead';\n\ntype TAttachmentStream = AsyncIterable<Uint8Array | string>;\n\nconst buildPathRefusedError = (opts: { reason: string; cause?: unknown }) => {\n return getError({\n error: MailErrors.ATTACHMENT_PATH_REFUSED,\n message: `Mail attachment path refused | ${opts.reason}`,\n cause: opts.cause,\n });\n};\n\nconst buildTooLargeError = (opts: { maxBytes: number }) => {\n return getError({\n error: MailErrors.ATTACHMENT_TOO_LARGE,\n message: `Mail attachments are over maxAttachmentBytes (${opts.maxBytes} bytes per message) | raise maxAttachmentBytes on the mail options, or send smaller attachments`,\n });\n};\n\nconst assertWithinLimit = (opts: { byteLength: number; usedBytes: number; maxBytes?: number }) => {\n const { byteLength, usedBytes, maxBytes } = opts;\n\n if (maxBytes === undefined || usedBytes + byteLength <= maxBytes) {\n return;\n }\n\n throw buildTooLargeError({ maxBytes });\n};\n\nconst isAttachmentStream = (value: unknown): value is TAttachmentStream => {\n return typeof value === 'object' && value !== null && Symbol.asyncIterator in value;\n};\n\nconst toBuffer = (chunk: Uint8Array | string): Buffer => {\n if (typeof chunk === 'string') {\n return Buffer.from(chunk);\n }\n\n return Buffer.isBuffer(chunk)\n ? chunk\n : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);\n};\n\n/** Throwing out of `for await` destroys a Node Readable and cancels a web ReadableStream. */\nconst drainStream = async (opts: {\n stream: TAttachmentStream;\n usedBytes: number;\n maxBytes?: number;\n}): Promise<Buffer> => {\n const { stream, usedBytes, maxBytes } = opts;\n const chunks: Buffer[] = [];\n let streamBytes = 0;\n\n for await (const chunk of stream) {\n const buffer = toBuffer(chunk);\n streamBytes += buffer.byteLength;\n\n // Per chunk: a stream has no length up front, and the rest must never be buffered.\n assertWithinLimit({ byteLength: streamBytes, usedBytes, maxBytes });\n chunks.push(buffer);\n }\n\n return Buffer.concat(chunks, streamBytes);\n};\n\n/**\n * Both sides go through realpath, so neither `..` nor a symlink can leave the root. Not closed: a\n * directory inside the root swapped for a symlink between this check and `open` - that takes write\n * access inside the root, so keep the root writable only by what the application trusts.\n */\nconst resolveConfinedPath = async (opts: {\n path: string;\n attachmentRoot: string;\n}): Promise<string> => {\n const { path, attachmentRoot } = opts;\n\n let rootPath: string;\n let filePath: string;\n\n // `resolve` throws synchronously on a non-string `path` from an untyped caller; it lands here too.\n try {\n const resolved = await Promise.all([\n realpath(attachmentRoot),\n realpath(resolve(attachmentRoot, path)),\n ]);\n [rootPath, filePath] = resolved;\n } catch (error) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON, cause: error });\n }\n\n const relation = relative(rootPath, filePath);\n const isOutside =\n relation === '' || relation === '..' || relation.startsWith(`..${sep}`) || isAbsolute(relation);\n\n if (isOutside) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON });\n }\n\n return filePath;\n};\n\nconst readConfinedFile = async (opts: {\n path: string;\n usedBytes: number;\n attachmentRoot?: string;\n maxBytes?: number;\n}): Promise<Buffer> => {\n const { path, usedBytes, attachmentRoot, maxBytes } = opts;\n\n if (!attachmentRoot) {\n throw buildPathRefusedError({\n reason:\n 'attachment.path is read only under attachmentRoot, which is not set | set attachmentRoot on the mail options, or pass the bytes as content',\n });\n }\n\n const filePath = await resolveConfinedPath({ path, attachmentRoot });\n let handle: FileHandle;\n\n try {\n const opened = await open(filePath, OPEN_FLAGS);\n handle = opened;\n } catch (error) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON, cause: error });\n }\n\n try {\n const stats = await handle.stat();\n\n if (!stats.isFile()) {\n throw buildPathRefusedError({ reason: PATH_OUTSIDE_REASON });\n }\n\n // Sized before reading, so a file known to be oversized is never opened for reading.\n assertWithinLimit({ byteLength: stats.size, usedBytes, maxBytes });\n\n // Counted while read, and read no further than one byte past the budget: the file may have\n // grown since fstat.\n const stream = handle.createReadStream({\n autoClose: false,\n end: maxBytes === undefined ? Infinity : maxBytes - usedBytes,\n });\n\n const result = await drainStream({ stream, usedBytes, maxBytes });\n\n return result;\n } finally {\n await handle.close();\n }\n};\n\nexport class MailAttachmentUtility {\n /**\n * Reads one attachment's bytes. A string `content` is raw text unless `encoding` says otherwise\n * (nodemailer's convention); `null` counts as absent. A `path` is read only inside\n * `attachmentRoot` and refused without one. `maxBytes` caps the whole message; `usedBytes` is what\n * earlier attachments already took.\n */\n static async readContent(opts: {\n attachment: IMailAttachment;\n attachmentRoot?: string;\n maxBytes?: number;\n usedBytes?: number;\n }): Promise<Buffer> {\n const { attachment, attachmentRoot, maxBytes, usedBytes = 0 } = opts;\n const { content } = attachment;\n\n if (content !== undefined && content !== null) {\n if (typeof content === 'string') {\n const encoding = attachment.encoding ?? 'utf-8';\n assertWithinLimit({\n byteLength: Buffer.byteLength(content, encoding),\n usedBytes,\n maxBytes,\n });\n\n return Buffer.from(content, encoding);\n }\n\n if (content instanceof Uint8Array) {\n assertWithinLimit({ byteLength: content.byteLength, usedBytes, maxBytes });\n\n return toBuffer(content);\n }\n\n if (!isAttachmentStream(content)) {\n throw getError({\n error: MailErrors.INVALID_CONFIGURATION,\n message:\n 'Invalid mail attachment | attachment.content must be a Buffer, a Uint8Array, a string or a stream',\n });\n }\n\n return drainStream({ stream: content, usedBytes, maxBytes });\n }\n\n if (attachment.path !== undefined && attachment.path !== null) {\n return readConfinedFile({ path: attachment.path, usedBytes, attachmentRoot, maxBytes });\n }\n\n return Buffer.alloc(0);\n }\n\n /**\n * Turns every attachment into `content` bytes and drops `path`, so no transport is ever handed a\n * file or URL to read on its own. `maxBytes` is shared by all attachments of the message. An\n * attachment read from `path` keeps the file's name and, when none is given, its content type.\n */\n static async resolve(opts: {\n attachments: IMailAttachment[];\n attachmentRoot?: string;\n maxBytes?: number;\n }): Promise<IMailAttachment[]> {\n const { attachments, attachmentRoot, maxBytes } = opts;\n const resolved: IMailAttachment[] = [];\n let usedBytes = 0;\n\n // Sequential on purpose: each read spends the budget the previous ones left.\n for (const attachment of attachments) {\n const { path, href, raw, content, encoding, ...rest } = attachment;\n\n // nodemailer reads both on its own - `href` fetches a URL, `raw` can carry a `path`.\n if ((href !== undefined && href !== null) || (raw !== undefined && raw !== null)) {\n throw buildPathRefusedError({\n reason:\n 'attachment.href and attachment.raw are not supported | pass the bytes as content',\n });\n }\n\n const bytes = await MailAttachmentUtility.readContent({\n attachment: { content, encoding, path },\n attachmentRoot,\n maxBytes,\n usedBytes,\n });\n\n usedBytes += bytes.byteLength;\n\n const isReadFromPath =\n (content === undefined || content === null) && typeof path === 'string';\n const filename = rest.filename ?? (isReadFromPath ? basename(path) : undefined);\n const contentType =\n rest.contentType ??\n (isReadFromPath && filename ? ContentTypeTable.resolve({ filename }) : undefined);\n\n const item: IMailAttachment = { ...rest, content: bytes };\n\n if (filename !== undefined) {\n item.filename = filename;\n }\n\n if (contentType !== undefined) {\n item.contentType = contentType;\n }\n\n resolved.push(item);\n }\n\n return resolved;\n }\n\n /**\n * Releases every attachment stream of a refused send, read or not, so none keeps a descriptor\n * open. A drained stream is already closed; releasing it again is harmless.\n */\n static release(opts: { attachments?: IMailAttachment[] }): void {\n for (const attachment of opts.attachments ?? []) {\n const { content } = attachment;\n\n if (content instanceof ReadableStream) {\n if (!content.locked) {\n content.cancel().catch((error) => {\n logger.warn(\n '[MailAttachmentUtility.release] Cancelling a web stream failed | error: %s',\n error,\n );\n });\n }\n\n continue;\n }\n\n if (\n typeof content === 'object' &&\n content !== null &&\n 'destroy' in content &&\n typeof content.destroy === 'function'\n ) {\n content.destroy();\n }\n }\n }\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { type IMailMessage } from '../common/index.js';
2
+ /** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */
3
+ export declare class MailHeaderUtility {
4
+ /** `value` is `unknown`: the message types end in `[key: string]: any`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */
5
+ static assertValue(opts: {
6
+ field: string;
7
+ value: unknown;
8
+ }): void;
9
+ /** Every address field, the subject and the custom headers, names included. */
10
+ static assert(opts: {
11
+ message: IMailMessage;
12
+ }): void;
13
+ }
14
+ //# sourceMappingURL=header.utility.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { getError } from '@venizia/ignis-helpers/core';
2
+ import { MailErrors } from '../common/index.js';
3
+ /** Printable ASCII without the colon: what RFC 5322 allows in a header field name. */
4
+ const HEADER_NAME_PATTERN = /^[\x21-\x39\x3b-\x7e]+$/;
5
+ /** A value spliced into a header line cannot hold a line break or NUL: it would break out of its line and forge headers or smuggle body content. */
6
+ const HEADER_VALUE_FORBIDDEN = /[\r\n\0]/;
7
+ /** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */
8
+ export class MailHeaderUtility {
9
+ /** `value` is `unknown`: the message types end in `[key: string]: any`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */
10
+ static assertValue(opts) {
11
+ const { field, value } = opts;
12
+ if (typeof value === 'string' && !HEADER_VALUE_FORBIDDEN.test(value)) {
13
+ return;
14
+ }
15
+ throw getError({
16
+ error: MailErrors.INVALID_HEADER,
17
+ message: `Invalid mail header | ${field} must be a string without line breaks or control characters`,
18
+ });
19
+ }
20
+ /** Every address field, the subject and the custom headers, names included. */
21
+ static assert(opts) {
22
+ const { from, to, cc, bcc, replyTo, subject, headers } = opts.message;
23
+ const addresses = { from, to, cc, bcc, replyTo };
24
+ for (const [field, value] of Object.entries(addresses)) {
25
+ if (value === undefined || value === null) {
26
+ continue;
27
+ }
28
+ for (const item of Array.isArray(value) ? value : [value]) {
29
+ MailHeaderUtility.assertValue({ field, value: item });
30
+ }
31
+ }
32
+ MailHeaderUtility.assertValue({ field: 'subject', value: subject });
33
+ for (const [name, value] of Object.entries(headers ?? {})) {
34
+ if (!HEADER_NAME_PATTERN.test(name)) {
35
+ throw getError({
36
+ error: MailErrors.INVALID_HEADER,
37
+ message: 'Invalid mail header | a header name must be printable ASCII without a colon',
38
+ });
39
+ }
40
+ MailHeaderUtility.assertValue({ field: `headers.${name}`, value });
41
+ }
42
+ }
43
+ }
44
+ //# sourceMappingURL=header.utility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"header.utility.js","sourceRoot":"","sources":["../../../../../src/components/mail/utilities/header.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,UAAU,EAAqB,MAAM,WAAW,CAAC;AAE1D,sFAAsF;AACtF,MAAM,mBAAmB,GAAG,yBAAyB,CAAC;AAEtD,oJAAoJ;AACpJ,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAE1C,mIAAmI;AACnI,MAA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AAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,EAAE,CAAC;YAC1D,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;gBACpC,MAAM,QAAQ,CAAC;oBACb,KAAK,EAAE,UAAU,CAAC,cAAc;oBAChC,OAAO,EAAE,6EAA6E;iBACvF,CAAC,CAAC;YACL,CAAC;YAED,iBAAiB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,WAAW,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport { MailErrors, type IMailMessage } from '../common';\n\n/** Printable ASCII without the colon: what RFC 5322 allows in a header field name. */\nconst HEADER_NAME_PATTERN = /^[\\x21-\\x39\\x3b-\\x7e]+$/;\n\n/** A value spliced into a header line cannot hold a line break or NUL: it would break out of its line and forge headers or smuggle body content. */\nconst HEADER_VALUE_FORBIDDEN = /[\\r\\n\\0]/;\n\n/** The one place a message is checked for header injection, before any transport sees it. A transport called directly skips it. */\nexport class MailHeaderUtility {\n /** `value` is `unknown`: the message types end in `[key: string]: any`, so nothing stops a controller forwarding a request body from putting an array where a string is declared. */\n static assertValue(opts: { field: string; value: unknown }): void {\n const { field, value } = opts;\n\n if (typeof value === 'string' && !HEADER_VALUE_FORBIDDEN.test(value)) {\n return;\n }\n\n throw getError({\n error: MailErrors.INVALID_HEADER,\n message: `Invalid mail header | ${field} must be a string without line breaks or control characters`,\n });\n }\n\n /** Every address field, the subject and the custom headers, names included. */\n static assert(opts: { message: IMailMessage }): void {\n const { from, to, cc, bcc, replyTo, subject, headers } = opts.message;\n const addresses = { from, to, cc, bcc, replyTo };\n\n for (const [field, value] of Object.entries(addresses)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n for (const item of Array.isArray(value) ? value : [value]) {\n MailHeaderUtility.assertValue({ field, value: item });\n }\n }\n\n MailHeaderUtility.assertValue({ field: 'subject', value: subject });\n\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (!HEADER_NAME_PATTERN.test(name)) {\n throw getError({\n error: MailErrors.INVALID_HEADER,\n message: 'Invalid mail header | a header name must be printable ASCII without a colon',\n });\n }\n\n MailHeaderUtility.assertValue({ field: `headers.${name}`, value });\n }\n }\n}\n"]}