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