@bymax-one/nest-notification 1.1.0 → 1.1.2

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