@bymax-one/nest-notification 1.0.6 → 1.1.1

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.
@@ -1726,6 +1726,378 @@ _options = new WeakMap();
1726
1726
  ResendEmailProvider = __decorateClass([
1727
1727
  Injectable()
1728
1728
  ], ResendEmailProvider);
1729
+ var DEFAULT_PORT = 587;
1730
+ var IMPLICIT_TLS_PORT = 465;
1731
+ var DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
1732
+ var DEFAULT_GREETING_TIMEOUT_MS = 1e4;
1733
+ var DEFAULT_SOCKET_TIMEOUT_MS = 2e4;
1734
+ var REDACTED = "[redacted]";
1735
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1736
+ function areCredentialsComplete(credentials) {
1737
+ return Boolean(credentials.user) && Boolean(credentials.pass);
1738
+ }
1739
+ var NODEMAILER_MODULE = "nodemailer";
1740
+ var _transportPromise, _options2;
1741
+ var SmtpEmailProvider = class {
1742
+ /**
1743
+ * @param options - Adapter options; `host` is required to actually send, and
1744
+ * `credentials` must be complete whenever supplied at all.
1745
+ */
1746
+ constructor(options = {}) {
1747
+ this.name = "smtp";
1748
+ this.logger = new Logger(SmtpEmailProvider.name);
1749
+ /**
1750
+ * Cached in-flight (or resolved) transport initialization. `null` until the first
1751
+ * `send()` and after a failed init. Caching the PROMISE (not just the transport)
1752
+ * collapses concurrent first sends onto a single dynamic `import()` + creation;
1753
+ * a failed init resets this back to `null` so a transient error can be retried.
1754
+ */
1755
+ __privateAdd(this, _transportPromise, null);
1756
+ /**
1757
+ * The adapter options, which carry the SMTP password.
1758
+ *
1759
+ * An ECMAScript private field rather than a TypeScript `private` one: the latter
1760
+ * is erased at runtime, leaving an enumerable own property that `JSON.stringify`,
1761
+ * object spread and `util.inspect` all walk into. This provider is registered in
1762
+ * the container, so anything that renders it incidentally — a structured logger
1763
+ * formatting its arguments, an error reporter capturing the scope of a throw —
1764
+ * would emit the password in plaintext.
1765
+ */
1766
+ __privateAdd(this, _options2);
1767
+ __privateSet(this, _options2, options);
1768
+ }
1769
+ /**
1770
+ * Whether the relay is fully described. Does not open a connection nor load
1771
+ * Nodemailer.
1772
+ *
1773
+ * A host is always required. Credentials are required only when the consumer
1774
+ * supplied a `credentials` object at all — which is how a deployment declares that
1775
+ * it logs in. That makes an open capture server configured, while a production
1776
+ * relay whose `SMTP_PASS` variable failed to load is *not*, instead of silently
1777
+ * attempting an anonymous send.
1778
+ *
1779
+ * @returns `true` when the provider can attempt a send.
1780
+ */
1781
+ isConfigured() {
1782
+ if (!__privateGet(this, _options2).host) {
1783
+ return false;
1784
+ }
1785
+ const credentials = __privateGet(this, _options2).credentials;
1786
+ if (credentials === void 0) {
1787
+ return true;
1788
+ }
1789
+ return areCredentialsComplete(credentials);
1790
+ }
1791
+ /**
1792
+ * Sends one transactional email over SMTP.
1793
+ *
1794
+ * @param options - The message envelope and body.
1795
+ * @returns The RFC-5322 `Message-ID` assigned to the message, angle brackets
1796
+ * included — the value that also appears in the delivered message's headers,
1797
+ * so an audit entry correlates with what the recipient received.
1798
+ * @throws Error When an address or custom header carries a line break, the
1799
+ * configuration is incomplete, no sender address is available, the `nodemailer`
1800
+ * package is not installed, the transport rejects the message, or no message id
1801
+ * comes back. `EmailService` maps any thrown `Error` to `EMAIL_SEND_FAILED`.
1802
+ */
1803
+ async send(options) {
1804
+ this.guardHeaderInjection(options);
1805
+ const from2 = this.buildSender(options.from, options.fromName);
1806
+ const transport = await this.getTransport();
1807
+ const info = await this.dispatch(transport, {
1808
+ from: from2,
1809
+ to: options.to,
1810
+ subject: options.subject,
1811
+ html: options.html,
1812
+ text: options.text,
1813
+ replyTo: options.replyTo,
1814
+ cc: options.cc,
1815
+ bcc: options.bcc,
1816
+ headers: options.headers,
1817
+ attachments: this.mapAttachments(options.attachments)
1818
+ });
1819
+ if (!info.messageId) {
1820
+ throw new Error("SMTP transport returned no message ID");
1821
+ }
1822
+ return { messageId: info.messageId };
1823
+ }
1824
+ /**
1825
+ * Hands the payload to the transport, converting a transport failure into a plain
1826
+ * `Error` whose message has the SMTP password scrubbed out. The email body is
1827
+ * never part of what is logged.
1828
+ *
1829
+ * @param transport - The initialized transport.
1830
+ * @param payload - The message to send.
1831
+ * @returns The transport's send info.
1832
+ * @throws Error When the transport rejects the message.
1833
+ */
1834
+ async dispatch(transport, payload) {
1835
+ try {
1836
+ return await transport.sendMail(payload);
1837
+ } catch (error) {
1838
+ const reason = this.redact(error instanceof Error ? error.message : String(error));
1839
+ this.logger.warn(`[SMTP_SEND_FAILED] ${reason}`);
1840
+ throw new Error(`SMTP send failed: ${reason}`);
1841
+ }
1842
+ }
1843
+ /**
1844
+ * Replaces every occurrence of either configured credential with a placeholder.
1845
+ *
1846
+ * A relay can echo the failing command back in its response, and a socket error
1847
+ * can carry the connection options — either would otherwise put the credential
1848
+ * into a log line and into the audit entry `EmailService` writes from the thrown
1849
+ * message.
1850
+ *
1851
+ * The **user** is scrubbed alongside the password because it is not always a
1852
+ * public login: an SES SMTP username, for one, is itself generated secret
1853
+ * material. Matching is literal and unconditional, so a short credential
1854
+ * over-redacts a message rather than risking a miss — the safe direction for a
1855
+ * control whose other failure mode is persisting a secret.
1856
+ *
1857
+ * @param message - The raw error message.
1858
+ * @returns The message with both credentials removed, unchanged when none is set.
1859
+ */
1860
+ redact(message) {
1861
+ const credentials = __privateGet(this, _options2).credentials;
1862
+ const secrets = [credentials?.user, credentials?.pass].filter((secret) => Boolean(secret)).sort((a, b) => b.length - a.length);
1863
+ let redacted = message;
1864
+ for (const secret of secrets) {
1865
+ redacted = redacted.split(secret).join(REDACTED);
1866
+ }
1867
+ return redacted;
1868
+ }
1869
+ /**
1870
+ * Rejects a line break in any caller-supplied value that becomes a message header.
1871
+ *
1872
+ * Nodemailer's MIME layer already strips `CR`/`LF` from header names and values and
1873
+ * derives the envelope from parsed address objects rather than raw strings, so this
1874
+ * is defence in depth rather than the only barrier — but header injection is the
1875
+ * one place where trusting a peer dependency's current behaviour would be the whole
1876
+ * security boundary. The subject is left out on purpose: a stray trailing newline
1877
+ * from a template is plausible there, and Nodemailer's strip handles it without a
1878
+ * hard failure.
1879
+ *
1880
+ * @param options - The message envelope.
1881
+ * @throws Error When a line break appears in an address or a custom header.
1882
+ */
1883
+ guardHeaderInjection(options) {
1884
+ this.rejectLineBreak("from", options.from);
1885
+ this.rejectLineBreak("fromName", options.fromName);
1886
+ this.rejectLineBreak("replyTo", options.replyTo);
1887
+ for (const recipient of [options.to, options.cc, options.bcc].flat()) {
1888
+ this.rejectLineBreak("recipient", recipient);
1889
+ }
1890
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
1891
+ this.rejectLineBreak("header name", name);
1892
+ this.rejectLineBreak(`header ${name}`, value);
1893
+ }
1894
+ }
1895
+ /**
1896
+ * Throws when a value carries a `CR` or `LF`.
1897
+ *
1898
+ * @param field - The field name, for the error message.
1899
+ * @param value - The value to check; `undefined` passes.
1900
+ * @throws Error When the value contains a line break.
1901
+ */
1902
+ rejectLineBreak(field, value) {
1903
+ if (value !== void 0 && /[\r\n]/.test(value)) {
1904
+ throw new Error(`SmtpEmailProvider: ${field} contains a line break \u2014 refusing to send`);
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Builds the sender in Nodemailer's structured address form.
1909
+ *
1910
+ * Never concatenates the display name into `"Name <address>"` — see
1911
+ * {@link SmtpSender} for why that hands the sender away to whoever controls the
1912
+ * name.
1913
+ *
1914
+ * @param from - The sender address, if any.
1915
+ * @param fromName - The sender display name, if any.
1916
+ * @returns The sender; `name` is `''` when no display name was supplied.
1917
+ * @throws Error When no sender address is available — SMTP needs an envelope
1918
+ * sender, so an absent `from` and `defaultFrom` is a configuration bug worth
1919
+ * reporting plainly rather than a cryptic transport rejection.
1920
+ */
1921
+ buildSender(from2, fromName) {
1922
+ if (!from2) {
1923
+ throw new Error(
1924
+ "SmtpEmailProvider: no sender address \u2014 set `email.defaultFrom` or pass `from`"
1925
+ );
1926
+ }
1927
+ return { name: fromName ?? "", address: from2 };
1928
+ }
1929
+ /**
1930
+ * Maps the library's attachments onto Nodemailer's shape.
1931
+ *
1932
+ * `EmailAttachment.content` is documented as a `Buffer` **or a base64 string**, so
1933
+ * a string is tagged `encoding: 'base64'` — left untagged, Nodemailer would treat
1934
+ * the base64 text as the literal body and deliver a corrupt file.
1935
+ *
1936
+ * @param attachments - The attachments to map, if any.
1937
+ * @returns The mapped attachments, or `undefined` when there are none.
1938
+ */
1939
+ mapAttachments(attachments) {
1940
+ return attachments?.map((attachment) => ({
1941
+ filename: attachment.filename,
1942
+ content: attachment.content,
1943
+ contentType: attachment.contentType,
1944
+ encoding: typeof attachment.content === "string" ? "base64" : void 0
1945
+ }));
1946
+ }
1947
+ /**
1948
+ * Returns the cached transport, lazily importing `nodemailer` on first use.
1949
+ * Concurrent first calls share one in-flight initialization promise so the dynamic
1950
+ * import and creation run exactly once; a failed init is dropped from the cache so
1951
+ * a later call can retry instead of being permanently bricked.
1952
+ *
1953
+ * @returns The initialized transport.
1954
+ * @throws Error When the configuration is incomplete or `nodemailer` is missing.
1955
+ */
1956
+ getTransport() {
1957
+ __privateGet(this, _transportPromise) ?? __privateSet(this, _transportPromise, this.createTransport());
1958
+ return __privateGet(this, _transportPromise);
1959
+ }
1960
+ /**
1961
+ * Builds a fresh transport, resetting the cached promise on any failure so the
1962
+ * provider is not permanently bricked by a transient init error.
1963
+ *
1964
+ * @returns The initialized transport.
1965
+ * @throws Error When the configuration is incomplete or `nodemailer` is missing.
1966
+ */
1967
+ async createTransport() {
1968
+ try {
1969
+ const config = this.buildTransportConfig();
1970
+ const nodemailer = await this.loadNodemailer();
1971
+ return this.instantiate(nodemailer, config);
1972
+ } catch (error) {
1973
+ __privateSet(this, _transportPromise, null);
1974
+ throw error;
1975
+ }
1976
+ }
1977
+ /**
1978
+ * Calls into Nodemailer to build the transport, scrubbing the password out of a
1979
+ * failure.
1980
+ *
1981
+ * Redaction is applied here and in {@link SmtpEmailProvider.dispatch} rather than
1982
+ * around the whole initialization, because those two are the only calls that cross
1983
+ * into foreign code. This adapter's own errors — a missing host, incomplete
1984
+ * credentials — never contain the password, and running them through a substring
1985
+ * scrub would corrupt them: a one-character password rewrites every occurrence of
1986
+ * that character in the sentence.
1987
+ *
1988
+ * @param nodemailer - The loaded module surface.
1989
+ * @param config - The resolved transport configuration.
1990
+ * @returns The initialized transport.
1991
+ * @throws Error When the transport rejects its configuration.
1992
+ */
1993
+ instantiate(nodemailer, config) {
1994
+ try {
1995
+ return nodemailer.createTransport(config);
1996
+ } catch (error) {
1997
+ throw this.redactError(error);
1998
+ }
1999
+ }
2000
+ /**
2001
+ * Scrubs the password out of an initialization failure.
2002
+ *
2003
+ * `dispatch()` covers the send path, but this one covers the build path — a
2004
+ * transport implementation that validates its configuration eagerly could throw
2005
+ * with the credential pair stringified into the message, and this `catch` is the
2006
+ * only thing between that and the audit entry. An error whose message needs no
2007
+ * change is returned untouched, so its type and stack survive.
2008
+ *
2009
+ * Always an `Error`, because `IEmailProvider.send` documents that it throws one
2010
+ * and a direct caller is entitled to rely on that. Identity is preserved only for
2011
+ * an `Error` whose message needed no change — there its type and stack are worth
2012
+ * keeping; anything else is wrapped.
2013
+ *
2014
+ * @param error - The raw failure.
2015
+ * @returns The original `Error` when nothing needed scrubbing, otherwise a plain
2016
+ * `Error` carrying the scrubbed message.
2017
+ */
2018
+ redactError(error) {
2019
+ if (error instanceof Error) {
2020
+ const message = this.redact(error.message);
2021
+ return message === error.message ? error : new Error(message);
2022
+ }
2023
+ return new Error(this.redact(String(error)));
2024
+ }
2025
+ /**
2026
+ * Resolves the transport configuration, applying defaults and validating that the
2027
+ * relay is fully described.
2028
+ *
2029
+ * @returns The resolved configuration.
2030
+ * @throws Error When `host` is missing, or `credentials` were supplied incomplete.
2031
+ */
2032
+ buildTransportConfig() {
2033
+ const options = __privateGet(this, _options2);
2034
+ const host = options.host;
2035
+ if (!host) {
2036
+ throw new Error("SmtpEmailProvider: missing host \u2014 pass { host } to the constructor");
2037
+ }
2038
+ const port = options.port ?? DEFAULT_PORT;
2039
+ const secure = options.secure ?? port === IMPLICIT_TLS_PORT;
2040
+ return {
2041
+ host,
2042
+ port,
2043
+ secure,
2044
+ requireTLS: options.requireTls ?? (!secure && !LOOPBACK_HOSTS.has(host.toLowerCase())),
2045
+ auth: this.resolveCredentials(),
2046
+ tls: options.tls,
2047
+ connectionTimeout: options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT_MS,
2048
+ greetingTimeout: options.greetingTimeout ?? DEFAULT_GREETING_TIMEOUT_MS,
2049
+ socketTimeout: options.socketTimeout ?? DEFAULT_SOCKET_TIMEOUT_MS
2050
+ };
2051
+ }
2052
+ /**
2053
+ * Resolves the credential pair to hand the transport.
2054
+ *
2055
+ * @returns The credential pair, or `undefined` for an open relay.
2056
+ * @throws Error When `credentials` were supplied but are missing `user` or `pass`
2057
+ * — that is a deployment declaring it logs in while its secrets failed to load, so
2058
+ * it must fail closed rather than fall back to an anonymous send.
2059
+ */
2060
+ resolveCredentials() {
2061
+ const credentials = __privateGet(this, _options2).credentials;
2062
+ if (credentials === void 0) {
2063
+ return void 0;
2064
+ }
2065
+ if (!areCredentialsComplete(credentials)) {
2066
+ throw new Error(
2067
+ "SmtpEmailProvider: incomplete credentials \u2014 `credentials` needs both `user` and `pass`"
2068
+ );
2069
+ }
2070
+ return { user: credentials.user, pass: credentials.pass };
2071
+ }
2072
+ /**
2073
+ * Dynamically imports the optional `nodemailer` peer dependency, tolerating both
2074
+ * shapes the specifier can resolve to — a namespace carrying `createTransport` as
2075
+ * a named export, and one where the CommonJS module lands under `default`.
2076
+ *
2077
+ * @returns The module's callable surface.
2078
+ * @throws Error When the package is not installed in the consumer app.
2079
+ */
2080
+ async loadNodemailer() {
2081
+ let mod;
2082
+ try {
2083
+ mod = await import(NODEMAILER_MODULE);
2084
+ } catch {
2085
+ throw new Error(
2086
+ "`nodemailer` package is not installed. Run `pnpm add nodemailer` in the consumer app."
2087
+ );
2088
+ }
2089
+ const candidate = mod.createTransport ? mod : mod.default;
2090
+ if (!candidate?.createTransport) {
2091
+ throw new Error("`nodemailer` package exposes no createTransport export");
2092
+ }
2093
+ return candidate;
2094
+ }
2095
+ };
2096
+ _transportPromise = new WeakMap();
2097
+ _options2 = new WeakMap();
2098
+ SmtpEmailProvider = __decorateClass([
2099
+ Injectable()
2100
+ ], SmtpEmailProvider);
1729
2101
  var MS_PER_SECOND3 = 1e3;
1730
2102
  var InMemoryOtpStorage = class {
1731
2103
  constructor() {
@@ -2114,4 +2486,4 @@ var DEFAULT_TTLS = {
2114
2486
  OTP_GENERIC_SECONDS: 600
2115
2487
  };
2116
2488
 
2117
- export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
2489
+ export { BYMAX_NOTIFICATION_EMAIL_PROVIDER, BYMAX_NOTIFICATION_LOG_REPOSITORY, BYMAX_NOTIFICATION_OPTIONS, BYMAX_NOTIFICATION_OTP_STORAGE, BYMAX_NOTIFICATION_PUSH_PROVIDER, BYMAX_NOTIFICATION_SMS_PROVIDER, BYMAX_NOTIFICATION_TEMPLATE_RENDERER, BymaxNotificationModule, CANONICAL_EMAIL_TEMPLATES, DEFAULT_TTLS, DefaultTemplateRenderer, EmailService, InMemoryOtpStorage, NOTIFICATION_ERROR_CODES, NOTIFICATION_ERROR_DEFINITIONS, NOTIFICATION_PURPOSES, NoOpEmailProvider, NoOpNotificationLogRepository, NotificationAuditInterceptor, NotificationException, NotificationService, OtpService, RedisOtpStorage, ResendEmailProvider, SmtpEmailProvider, cooldownExpiresAt, formatCooldown, generateOtpCode, hashTenantRecipient, safeCompare, toRetryAfterHeader };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-notification",
3
- "version": "1.0.6",
3
+ "version": "1.1.1",
4
4
  "description": "Multi-channel notification library for NestJS — email, OTP, SMS, push — with pluggable providers and storage, multi-tenant by design, zero runtime dependencies.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -98,7 +98,7 @@
98
98
  "@nestjs/core": "^11.1.18",
99
99
  "reflect-metadata": "^0.2.0",
100
100
  "rxjs": "^7.8.0",
101
- "ioredis": "^5.0.0",
101
+ "ioredis": "^6.0.0",
102
102
  "resend": "^4.0.0 || ^5.0.0 || ^6.0.0",
103
103
  "@sendgrid/mail": "^8.0.0",
104
104
  "@aws-sdk/client-ses": "^3.0.0",