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