@astratra/notify 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,229 @@
1
+ # @astratra/notify
2
+
3
+ Les messages sortants, faits une fois : **e-mail, SMS, notifications poussées**.
4
+
5
+ Le transport est toujours injecté — SMTP, une API HTTP, Twilio, Infobip,
6
+ web-push, Expo. Ce package apporte l'anneau autour, et c'est le même anneau
7
+ pour les trois canaux :
8
+
9
+ - **rien ne lève jamais** — un message est la conséquence d'une action, pas
10
+ l'action ;
11
+ - **l'absence de configuration est visible**, jamais silencieuse ;
12
+ - **ce qui vient de l'utilisateur ne devient jamais une instruction**.
13
+
14
+ Aucune dépendance à l'exécution.
15
+
16
+ ---
17
+
18
+ # E-mail
19
+
20
+ ## Un envoi raté ne fait jamais échouer l'appelant
21
+
22
+ Un e-mail de confirmation est la **conséquence** d'une action. Quand la
23
+ commande est passée et l'argent encaissé, une coupure SMTP ne doit pas se
24
+ transformer en erreur 500 qui annonce au client que sa commande a échoué.
25
+
26
+ Donc rien ne lève. Chaque appel renvoie un résultat que tu peux consulter,
27
+ journaliser, ou ignorer.
28
+
29
+ ```js
30
+ const { createMailer } = require('@astratra/notify');
31
+
32
+ const mailer = createMailer({
33
+ channels: {
34
+ transactional: {
35
+ from: 'no-reply@acme.cd',
36
+ fromName: 'Acme',
37
+ send: (message) => transporter.sendMail(message), // nodemailer, Brevo, Resend…
38
+ },
39
+ alerts: {
40
+ from: 'alertes@acme.cd',
41
+ send: (message) => alertTransporter.sendMail(message),
42
+ },
43
+ },
44
+ });
45
+
46
+ const { sent, reason } = await mailer.send({
47
+ to: 'jean@ecole.cd',
48
+ subject: 'Votre commande est confirmée',
49
+ text, html,
50
+ });
51
+ ```
52
+
53
+ Plusieurs canaux, parce qu'un reçu et une alerte de sécurité n'ont pas à
54
+ voyager sur la même réputation d'expéditeur ni à partager les mêmes
55
+ identifiants.
56
+
57
+ Un canal sans identifiants ne fait pas tomber l'application : il journalise et
58
+ laisse passer. Un produit en développement ne doit pas planter à chaque
59
+ inscription faute de configuration SMTP.
60
+
61
+ ## L'injection d'en-têtes
62
+
63
+ Les en-têtes sont séparés par des retours à la ligne. Un saut de ligne dans un
64
+ sujet ne reste donc pas dans le sujet : il le **termine** et en commence un
65
+ nouveau.
66
+
67
+ ```
68
+ subject = "Commande confirmée\r\nBcc: tout@le-monde.cd"
69
+ ```
70
+
71
+ Ce qui suit devient un en-tête à part entière. Un formulaire de contact devient
72
+ un relais de spam, ou une copie silencieuse de chaque message. C'est une faille
73
+ ancienne, bien connue, et livrée tous les jours — parce que la chaîne a l'air
74
+ parfaitement ordinaire dans un débogueur.
75
+
76
+ Tout ce qui atterrit dans un en-tête passe par le nettoyage : sujet, nom
77
+ d'expéditeur, destinataires, `Reply-To`.
78
+
79
+ **Les mots sont conservés, pas supprimés.** Un sujet qui perd la moitié de ses
80
+ mots en silence est un rapport de bug que tu ne comprendras jamais.
81
+
82
+ **Une adresse invalide est refusée, pas réparée.** Un `Reply-To` malformé casse
83
+ silencieusement toutes les réponses, et personne ne le signale puisque le
84
+ message, lui, est bien arrivé.
85
+
86
+ **Une seule mauvaise adresse dans une liste ne fait pas perdre les autres.** Les
87
+ fournisseurs rejettent le message entier pour une adresse mal formée : une
88
+ faute de frappe coûterait tous les autres destinataires.
89
+
90
+ ## Le gabarit HTML
91
+
92
+ L'e-mail n'est pas le web. Outlook met en page le HTML avec Word, Gmail retire
93
+ les blocs `<style>`, et flexbox, grid, les variables CSS et les feuilles
94
+ externes sont tout simplement absents. Ce qui marche partout est ce qui marchait
95
+ en 2005 : des tableaux imbriqués et des styles en ligne.
96
+
97
+ ```js
98
+ const { renderEmail, renderText } = require('@astratra/notify');
99
+
100
+ const blocks = [
101
+ { type: 'heading', text: 'Code de modification' },
102
+ { type: 'paragraph', text: 'Votre code :' },
103
+ { type: 'code', value: '482915' },
104
+ { type: 'button', label: 'Ouvrir', url: 'https://app.acme.cd' },
105
+ { type: 'note', text: 'Valable dix minutes.' },
106
+ ];
107
+
108
+ await mailer.send({
109
+ to, subject: 'Votre code',
110
+ html: renderEmail({ blocks, preheader: 'Votre code de sécurité', theme: { accent: '#2563eb' } }),
111
+ text: renderText({ blocks }),
112
+ });
113
+ ```
114
+
115
+ Ce n'est pas un système de design : c'est le plus petit squelette qui arrive
116
+ identique dans Gmail, Outlook et Apple Mail, avec tes couleurs dessus.
117
+
118
+ **Le bouton est un tableau.** Un `<a>` stylé s'effondre en lien nu dans Outlook,
119
+ parce que le moteur de Word ignore le `padding` sur les éléments en ligne.
120
+
121
+ **Le pré-en-tête** est la ligne affichée à côté du sujet dans la boîte de
122
+ réception. Sans lui, les clients attrapent les premiers mots du corps — souvent
123
+ un texte alternatif égaré.
124
+
125
+ **La version texte n'est pas une politesse.** Un message sans partie texte est
126
+ moins bien noté par les filtres anti-spam, et certains lecteurs ne voient que
127
+ celle-là. La générer depuis les mêmes blocs garde les deux en phase.
128
+
129
+ **Tout est échappé.** Ça mord bien avant qu'on essaie de t'attaquer : un client
130
+ nommé « Dupont & Fils \<SARL\> » casse la mise en page de tous les messages où
131
+ il apparaît. Le bloc `html` est la porte de sortie, nommée explicitement pour
132
+ qu'elle ne s'ouvre jamais par accident.
133
+
134
+ ## Tester sans serveur mail
135
+
136
+ ```js
137
+ const { createCaptureChannel } = require('@astratra/notify');
138
+
139
+ const capture = createCaptureChannel({ from: 'no-reply@acme.cd' });
140
+ const mailer = createMailer({ channels: { transactional: capture } });
141
+
142
+ await service.confirmerCommande(id);
143
+
144
+ expect(capture.last().subject).toBe('Votre commande est confirmée');
145
+ ```
146
+
147
+ Utile aussi en développement, où un envoi réel atteindrait une vraie personne.
148
+
149
+ ---
150
+
151
+ # SMS
152
+
153
+ ```js
154
+ const { createSmsSender } = require('@astratra/notify');
155
+
156
+ const sms = createSmsSender({
157
+ transport: ({ to, text }) => twilioClient.messages.create({ to, from, body: text }),
158
+ });
159
+
160
+ const { sent } = await sms.send('+243 810 000 000', `Votre code : ${code}`);
161
+ ```
162
+
163
+ **Sans transport configuré, l'envoi est une simulation BRUYANTE.** Le message
164
+ part dans le journal, étiqueté `SIMULATION`, et le résultat le dit
165
+ (`simulated: true`). Une simulation qui a l'air réelle est pire qu'un échec :
166
+ quelqu'un attend un code qui n'a jamais quitté le journal.
167
+
168
+ Deux protections de plus : le numéro est nettoyé (espaces, points, tirets — ce
169
+ qui casse les fournisseurs) sans prétendre le valider, et **le texte est
170
+ plafonné** — un texte non borné concaténé dans un SMS est la façon dont un bug
171
+ devient une facture.
172
+
173
+ ---
174
+
175
+ # Notifications poussées
176
+
177
+ ## La leçon qui compte : les abonnements morts
178
+
179
+ Un abonnement push meurt en silence : application désinstallée, permission
180
+ révoquée, profil effacé. Le fournisseur répond 404 ou 410, et à partir de là
181
+ chaque envoi vers cet abonnement échoue, pour toujours.
182
+
183
+ Laissée seule, une liste d'abonnés n'accumule que des cadavres : les envois
184
+ ralentissent, les journaux d'erreurs se remplissent d'un bruit qui enterre les
185
+ vrais échecs, et certains fournisseurs étranglent les expéditeurs dont le taux
186
+ d'échec grimpe.
187
+
188
+ Un abonnement mort n'est donc pas une erreur à journaliser — c'est un **fait à
189
+ traiter** :
190
+
191
+ ```js
192
+ const { createPushSender } = require('@astratra/notify');
193
+
194
+ const push = createPushSender({
195
+ transport: (subscription, payload) =>
196
+ webpush.sendNotification(subscription, JSON.stringify(payload)),
197
+ // LE point du module : l'abonnement mort t'est rendu pour suppression.
198
+ onGone: (subscription) => Subscriptions.deleteOne({ endpoint: subscription.endpoint }),
199
+ });
200
+
201
+ const { delivered, gone, failed } = await push.broadcast(subscriptions, payload);
202
+ ```
203
+
204
+ Trois issues distinctes, jamais confondues : `delivered`, `gone` (mort, élagué),
205
+ `failed` (panne passagère, avec sa raison). Un abonnement mort ou en panne
206
+ n'arrête jamais les autres, et un élagage qui échoue ne transforme pas un `gone`
207
+ en `failed`.
208
+
209
+ Le statut du fournisseur est cherché où qu'il l'ait mis — `statusCode`,
210
+ `status`, `response.status` — parce que web-push et les clients HTTP ne sont pas
211
+ d'accord entre eux.
212
+
213
+ ---
214
+
215
+ ## Ce que ce package ne fait pas
216
+
217
+ - Il n'envoie **rien** lui-même : les transports sont injectés. Aucun SDK — ni
218
+ nodemailer, ni Twilio, ni web-push — n'est importé.
219
+ - Il ne stocke pas les abonnements : il te rend les morts, tu les supprimes.
220
+ - Il ne fait ni file d'attente ni relance — voir `@astratra/resilience`.
221
+ - Il ne gère pas le temps réel (websockets).
222
+ - Il n'a pas d'avis sur ton identité visuelle, seulement sur ce qui survit aux
223
+ clients mail.
224
+
225
+ ## Tests
226
+
227
+ ```bash
228
+ npm test --workspace @astratra/notify
229
+ ```
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@astratra/notify",
3
+ "version": "0.2.0",
4
+ "description": "Outbound messages done once \u2014 email, SMS and push. Transport injected, never throws, header-injection safe, loud simulation when unconfigured, dead push subscriptions handed back for pruning.",
5
+ "engines": {
6
+ "node": ">=20"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "type": "commonjs",
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "test": "jest"
16
+ },
17
+ "jest": {
18
+ "testMatch": [
19
+ "**/__tests__/**/*.test.js"
20
+ ]
21
+ },
22
+ "keywords": [
23
+ "astratra",
24
+ "email",
25
+ "sms",
26
+ "push",
27
+ "notifications",
28
+ "transactional"
29
+ ],
30
+ "license": "MIT",
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "devDependencies": {
35
+ "jest": "30.4.2"
36
+ }
37
+ }
package/src/headers.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Keeping user input out of mail headers.
3
+ *
4
+ * Headers are separated by CRLF. A newline inside a subject, a sender name or a
5
+ * reply-to therefore does not stay inside that field — it ENDS it and starts a
6
+ * new one. Anything after it becomes a header of its own:
7
+ *
8
+ * subject = "Order confirmed\r\nBcc: everyone@example.com"
9
+ *
10
+ * That is header injection, and it turns a contact form into a spam relay or a
11
+ * silent copy of every message. It is old, well known, and still shipped daily,
12
+ * because the string looks perfectly ordinary in a debugger.
13
+ *
14
+ * Anything that ends up in a header goes through here first.
15
+ */
16
+
17
+ /* CR, LF, NUL, and the Unicode line/paragraph separators — some mail libraries
18
+ normalise those two to a newline further down the chain. */
19
+ const BREAKS = /[\r\n\0\u2028\u2029]+/g;
20
+
21
+ /**
22
+ * Make a value safe to place in a header.
23
+ *
24
+ * Line breaks become a single space rather than disappearing: a subject that
25
+ * silently loses half its words is a bug report you will never understand.
26
+ */
27
+ function sanitizeHeader(value, options = {}) {
28
+ const maxLength = options.maxLength || 500;
29
+ const cleaned = String(value === null || value === undefined ? '' : value)
30
+ .replace(BREAKS, ' ')
31
+ .replace(/\s+/g, ' ')
32
+ .trim();
33
+ return cleaned.length > maxLength ? cleaned.slice(0, maxLength).trim() : cleaned;
34
+ }
35
+
36
+ /** Did this value carry something that had to be stripped? */
37
+ function hasHeaderInjection(value) {
38
+ BREAKS.lastIndex = 0;
39
+ return BREAKS.test(String(value === null || value === undefined ? '' : value));
40
+ }
41
+
42
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
43
+
44
+ /**
45
+ * An address, or nothing.
46
+ *
47
+ * Returning null on a malformed address rather than passing it through is
48
+ * deliberate: an invalid Reply-To silently breaks every reply to that message,
49
+ * and nobody reports it because the mail itself arrived.
50
+ */
51
+ function sanitizeAddress(value) {
52
+ const cleaned = sanitizeHeader(value, { maxLength: 320 });
53
+ return EMAIL.test(cleaned) ? cleaned : null;
54
+ }
55
+
56
+ /** `"Name" <address>`, with the name made safe and its quotes stripped. */
57
+ function formatSender(address, name) {
58
+ const safeAddress = sanitizeAddress(address);
59
+ if (!safeAddress) return null;
60
+ /* Quotes go, then trim again: stripping a trailing quote otherwise leaves a
61
+ dangling space inside the display name. The name stays inside its own
62
+ quotes, so an address smuggled into it is inert. */
63
+ const safeName = sanitizeHeader(name).replace(/"/g, '').trim();
64
+ return safeName ? `"${safeName}" <${safeAddress}>` : safeAddress;
65
+ }
66
+
67
+ module.exports = { sanitizeHeader, sanitizeAddress, formatSender, hasHeaderInjection, EMAIL };
package/src/index.d.ts ADDED
@@ -0,0 +1,161 @@
1
+ export type Awaitable<T> = T | Promise<T>;
2
+
3
+ /* ───────────────────────────── Email ───────────────────────────── */
4
+
5
+ /** Strip anything that could end a header and start a new one. */
6
+ export function sanitizeHeader(value: unknown, options?: { maxLength?: number }): string;
7
+ /** Returns the address, or null if it is not one — never a repaired guess. */
8
+ export function sanitizeAddress(value: unknown): string | null;
9
+ /** `"Name" <address>`, or null when there is no valid address. */
10
+ export function formatSender(address: unknown, name?: unknown): string | null;
11
+ export function hasHeaderInjection(value: unknown): boolean;
12
+ export const EMAIL: RegExp;
13
+
14
+ export interface OutgoingMessage {
15
+ from: string;
16
+ to: string[];
17
+ subject: string;
18
+ text?: string;
19
+ html?: string;
20
+ cc: string[];
21
+ bcc: string[];
22
+ replyTo?: string;
23
+ attachments?: unknown;
24
+ }
25
+
26
+ export interface MailChannel {
27
+ send(message: OutgoingMessage): Promise<unknown> | unknown;
28
+ from?: string;
29
+ fromName?: string;
30
+ replyTo?: string;
31
+ }
32
+
33
+ export interface SendResult {
34
+ sent: boolean;
35
+ channel: string;
36
+ to: string[];
37
+ reason?: 'unknown-channel' | 'no-recipient' | 'no-subject' | 'no-body' | 'no-sender' | 'send-failed';
38
+ error?: string;
39
+ result?: unknown;
40
+ }
41
+
42
+ export interface Mailer {
43
+ /** Never throws: the thing the mail was about has usually already happened. */
44
+ send(message: {
45
+ to: string | string[];
46
+ subject: string;
47
+ text?: string;
48
+ html?: string;
49
+ channel?: string;
50
+ from?: string;
51
+ fromName?: string;
52
+ replyTo?: string;
53
+ cc?: string | string[];
54
+ bcc?: string | string[];
55
+ attachments?: unknown;
56
+ }): Promise<SendResult>;
57
+ channels: string[];
58
+ defaultChannel: string;
59
+ }
60
+
61
+ export function createMailer(options: {
62
+ channels: Record<string, MailChannel>;
63
+ defaultChannel?: string;
64
+ logger?: { info?(m: string): void; warn?(m: string): void; error?(m: string): void };
65
+ subjectMaxLength?: number;
66
+ }): Mailer;
67
+
68
+ export interface CaptureChannel extends MailChannel {
69
+ sent: OutgoingMessage[];
70
+ last(): OutgoingMessage | null;
71
+ clear(): void;
72
+ }
73
+
74
+ /** A channel that records instead of sending — for tests and development. */
75
+ export function createCaptureChannel(config?: { from?: string; fromName?: string; replyTo?: string }): CaptureChannel;
76
+
77
+ export interface EmailTheme {
78
+ background?: string;
79
+ surface?: string;
80
+ text?: string;
81
+ muted?: string;
82
+ accent?: string;
83
+ accentText?: string;
84
+ border?: string;
85
+ fontFamily?: string;
86
+ width?: number;
87
+ }
88
+
89
+ export type EmailBlock =
90
+ | { type: 'heading' | 'paragraph' | 'note'; text: string }
91
+ | { type: 'code'; value: string }
92
+ | { type: 'button'; label: string; url: string }
93
+ | { type: 'divider' }
94
+ /** Not escaped — named so it can never happen by accident. */
95
+ | { type: 'html'; html: string };
96
+
97
+ export function renderEmail(options?: {
98
+ blocks?: EmailBlock[];
99
+ preheader?: string;
100
+ footer?: string;
101
+ theme?: EmailTheme;
102
+ }): string;
103
+
104
+ /** The same blocks as plain text — spam filters and screen readers want it. */
105
+ export function renderText(options?: { blocks?: EmailBlock[] }): string;
106
+
107
+ export function escapeHtml(value: unknown): string;
108
+ export const DEFAULT_THEME: Required<EmailTheme>;
109
+
110
+ /* ────────────────────────── SMS and push ────────────────────────── */
111
+
112
+ /** Digits and one leading plus, or null — never a guess. */
113
+ export function normalizePhone(value: unknown): string | null;
114
+
115
+ export interface SmsResult {
116
+ sent: boolean;
117
+ simulated?: boolean;
118
+ to?: string;
119
+ reason?: 'no-recipient' | 'no-text' | 'send-failed';
120
+ error?: string;
121
+ result?: unknown;
122
+ }
123
+
124
+ export interface SmsSender {
125
+ /** Never throws. Without a transport, the send is a LOUD simulation. */
126
+ send(to: unknown, text: unknown): Promise<SmsResult>;
127
+ normalizePhone(value: unknown): string | null;
128
+ }
129
+
130
+ export function createSmsSender(options?: {
131
+ transport?: (message: { to: string; text: string }) => Awaitable<unknown>;
132
+ /** Hard cap — an unbounded text concatenated into an SMS is how a bug becomes a bill. Default 480. */
133
+ maxLength?: number;
134
+ logger?: { info?(m: string): void; warn?(m: string): void; error?(m: string): void };
135
+ }): SmsSender;
136
+
137
+ export type PushStatus = 'delivered' | 'gone' | 'failed';
138
+
139
+ export interface PushReport {
140
+ delivered: number;
141
+ gone: number;
142
+ failed: number;
143
+ errors: string[];
144
+ }
145
+
146
+ export interface PushSender<Subscription = unknown, Payload = unknown> {
147
+ /** Never throws. 'gone' means the subscription is dead and was handed to onGone. */
148
+ send(subscription: Subscription, payload: Payload): Promise<{ status: PushStatus; error?: string }>;
149
+ /** One dead or failing subscription never stops the others. */
150
+ broadcast(subscriptions: Subscription[] | null | undefined, payload: Payload): Promise<PushReport>;
151
+ }
152
+
153
+ export function createPushSender<Subscription = unknown, Payload = unknown>(options: {
154
+ /** webpush.sendNotification, Expo's client… Must throw with the provider status reachable on the error. */
155
+ transport: (subscription: Subscription, payload: Payload) => Awaitable<unknown>;
156
+ /** Default: statusCode/status/response.status of 404 or 410. */
157
+ isGone?: (error: unknown) => boolean;
158
+ /** Delete the dead subscription from your store — the point of the module. */
159
+ onGone?: (subscription: Subscription) => Awaitable<void>;
160
+ logger?: { info?(m: string): void; warn?(m: string): void; error?(m: string): void };
161
+ }): PushSender<Subscription, Payload>;
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ ...require('./headers'),
3
+ ...require('./mailer'),
4
+ ...require('./template'),
5
+ ...require('./sms'),
6
+ ...require('./push')
7
+ };
package/src/mailer.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Sending mail, with the parts that are always the same.
3
+ *
4
+ * The transport is yours — SMTP, an HTTP API, whatever your provider offers.
5
+ * What this adds is the ring around it, and it is the same ring every time:
6
+ *
7
+ * nothing user-supplied reaches a header unsanitised;
8
+ * a send that fails does NOT fail the request that triggered it;
9
+ * several senders coexist without their credentials getting mixed up.
10
+ *
11
+ * That second point deserves saying plainly. A confirmation email is a
12
+ * consequence of an action, not the action itself. When the order is placed and
13
+ * the money taken, an SMTP timeout must not turn into a 500 that tells the
14
+ * customer their order failed. So nothing here throws: every call returns a
15
+ * result you can look at, log, or ignore.
16
+ */
17
+ const { sanitizeHeader, sanitizeAddress, formatSender } = require('./headers');
18
+
19
+ const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
20
+
21
+ const listOf = (value) => (Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]);
22
+
23
+ /**
24
+ * @param {object} options
25
+ * @param {Record<string, object>} options.channels named senders. Each one:
26
+ * { send: async (message) => any, from, fromName?, replyTo? }
27
+ * Several channels because a receipt and a security alert should not travel
28
+ * on the same reputation, nor share credentials.
29
+ * @param {string} [options.defaultChannel] defaults to the first declared.
30
+ * @param {object} [options.logger]
31
+ * @param {number} [options.subjectMaxLength]
32
+ */
33
+ function createMailer(options = {}) {
34
+ const channels = options.channels || {};
35
+ const names = Object.keys(channels);
36
+ if (!names.length) {
37
+ throw new Error('createMailer requires at least one channel.');
38
+ }
39
+
40
+ for (const [name, channel] of Object.entries(channels)) {
41
+ if (!channel || typeof channel.send !== 'function') {
42
+ throw new Error(`createMailer: channel "${name}" needs a send() function.`);
43
+ }
44
+ }
45
+
46
+ const defaultChannel = options.defaultChannel || names[0];
47
+ if (!channels[defaultChannel]) {
48
+ throw new Error(`createMailer: defaultChannel "${defaultChannel}" is not a declared channel.`);
49
+ }
50
+
51
+ const logger = options.logger || NOOP_LOGGER;
52
+ const subjectMaxLength = options.subjectMaxLength || 200;
53
+
54
+ /**
55
+ * @param {object} message { to, subject, text?, html?, channel?, from?,
56
+ * fromName?, replyTo?, cc?, bcc?, attachments? }
57
+ * @returns {Promise<{sent: boolean, channel: string, to: string[], reason?: string, error?: string, result?: any}>}
58
+ * Never throws.
59
+ */
60
+ async function send(message = {}) {
61
+ const channelName = message.channel || defaultChannel;
62
+ const channel = channels[channelName];
63
+
64
+ if (!channel) {
65
+ logger.error(`[mailer] unknown channel "${channelName}" — nothing sent`);
66
+ return { sent: false, channel: channelName, to: [], reason: 'unknown-channel' };
67
+ }
68
+
69
+ /* A malformed recipient is dropped rather than passed on: providers reject
70
+ the whole message for one bad address, so one typo in a list would lose
71
+ every other recipient too. */
72
+ const recipients = listOf(message.to).map(sanitizeAddress).filter(Boolean);
73
+ if (!recipients.length) {
74
+ logger.warn('[mailer] no valid recipient — nothing sent');
75
+ return { sent: false, channel: channelName, to: [], reason: 'no-recipient' };
76
+ }
77
+
78
+ const subject = sanitizeHeader(message.subject, { maxLength: subjectMaxLength });
79
+ if (!subject) {
80
+ logger.warn('[mailer] no subject — nothing sent');
81
+ return { sent: false, channel: channelName, to: recipients, reason: 'no-subject' };
82
+ }
83
+
84
+ if (!message.text && !message.html) {
85
+ logger.warn(`[mailer] "${subject}" has no body — nothing sent`);
86
+ return { sent: false, channel: channelName, to: recipients, reason: 'no-body' };
87
+ }
88
+
89
+ const from = formatSender(
90
+ message.from || channel.from,
91
+ message.fromName === undefined ? channel.fromName : message.fromName
92
+ );
93
+ if (!from) {
94
+ /* Not configured is not a crash. A product with no mail credentials in
95
+ development should log and carry on, not fall over on every signup. */
96
+ logger.warn(`[mailer] channel "${channelName}" has no valid sender address — nothing sent`);
97
+ return { sent: false, channel: channelName, to: recipients, reason: 'no-sender' };
98
+ }
99
+
100
+ const replyTo = sanitizeAddress(message.replyTo || channel.replyTo);
101
+
102
+ const payload = {
103
+ from,
104
+ to: recipients,
105
+ subject,
106
+ text: message.text,
107
+ html: message.html,
108
+ cc: listOf(message.cc).map(sanitizeAddress).filter(Boolean),
109
+ bcc: listOf(message.bcc).map(sanitizeAddress).filter(Boolean),
110
+ attachments: message.attachments
111
+ };
112
+ if (replyTo) payload.replyTo = replyTo;
113
+
114
+ try {
115
+ const result = await channel.send(payload);
116
+ logger.info(`[mailer] "${subject}" sent to ${recipients.length} recipient(s) via ${channelName}`);
117
+ return { sent: true, channel: channelName, to: recipients, result };
118
+ } catch (error) {
119
+ /* The caller decides what a failure means. Most of the time: log it and
120
+ move on, because the thing the mail was about already happened. */
121
+ logger.error(`[mailer] "${subject}" failed via ${channelName}: ${error.message}`);
122
+ return { sent: false, channel: channelName, to: recipients, reason: 'send-failed', error: error.message };
123
+ }
124
+ }
125
+
126
+ return { send, channels: names, defaultChannel };
127
+ }
128
+
129
+ /**
130
+ * A channel that records instead of sending.
131
+ *
132
+ * For tests, and for a development environment where a real send would reach a
133
+ * real person. Reading `sent` is how you assert on mail without a mail server.
134
+ */
135
+ function createCaptureChannel(config = {}) {
136
+ const sent = [];
137
+ return {
138
+ from: config.from || 'capture@example.invalid',
139
+ fromName: config.fromName,
140
+ replyTo: config.replyTo,
141
+ send: async (message) => { sent.push(message); return { captured: true }; },
142
+ sent,
143
+ last: () => sent[sent.length - 1] || null,
144
+ clear: () => { sent.length = 0; }
145
+ };
146
+ }
147
+
148
+ module.exports = { createMailer, createCaptureChannel };
package/src/push.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Push notifications, and the lesson that matters: DEAD SUBSCRIPTIONS.
3
+ *
4
+ * A push subscription dies quietly — the app is uninstalled, permissions
5
+ * revoked, the browser profile wiped. The provider answers 404 or 410, and
6
+ * from then on every send to that subscription fails, forever. Left alone, a
7
+ * subscriber list only accumulates corpses: sends get slower, error logs fill
8
+ * with noise that buries real failures, and some providers throttle senders
9
+ * whose failure rate climbs.
10
+ *
11
+ * So a dead subscription is not an error to log — it is a FACT to act on. The
12
+ * dispatcher separates the three outcomes and hands the dead ones back for
13
+ * pruning.
14
+ */
15
+
16
+ const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
17
+
18
+ /**
19
+ * @param {object} options
20
+ * @param {Function} options.transport async (subscription, payload) => any.
21
+ * webpush.sendNotification, Expo's client, your own — must THROW on failure
22
+ * with the provider's status reachable on the error.
23
+ * @param {Function} [options.isGone] (error) => boolean. Default: 404 or 410.
24
+ * @param {Function} [options.onGone] async (subscription) => void — delete it
25
+ * from your store. THIS is the point of the module.
26
+ * @param {object} [options.logger]
27
+ */
28
+ function createPushSender(options = {}) {
29
+ const transport = options.transport;
30
+ if (typeof transport !== 'function') {
31
+ throw new Error('createPushSender requires options.transport.');
32
+ }
33
+
34
+ const isGone = options.isGone || ((error) => {
35
+ const status = Number(error?.statusCode ?? error?.status ?? error?.response?.status);
36
+ return status === 404 || status === 410;
37
+ });
38
+ const onGone = options.onGone || null;
39
+ const logger = options.logger || NOOP_LOGGER;
40
+
41
+ /**
42
+ * Send to ONE subscription.
43
+ * @returns {Promise<{status: 'delivered'|'gone'|'failed', error?: string}>} never throws.
44
+ */
45
+ async function send(subscription, payload) {
46
+ try {
47
+ await transport(subscription, payload);
48
+ return { status: 'delivered' };
49
+ } catch (error) {
50
+ if (isGone(error)) {
51
+ /* Not an error: a fact. The subscription is dead and will never
52
+ deliver again — prune it, or send to it forever. */
53
+ if (onGone) {
54
+ try {
55
+ await onGone(subscription);
56
+ } catch (pruneError) {
57
+ logger.error(`[push] could not prune a dead subscription: ${pruneError.message}`);
58
+ }
59
+ }
60
+ return { status: 'gone' };
61
+ }
62
+ logger.error(`[push] delivery failed: ${error.message}`);
63
+ return { status: 'failed', error: error.message };
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Send to MANY. One dead or failing subscription must not stop the others —
69
+ * the report says how many of each, and failures carry their reasons.
70
+ */
71
+ async function broadcast(subscriptions, payload) {
72
+ const report = { delivered: 0, gone: 0, failed: 0, errors: [] };
73
+ for (const subscription of subscriptions || []) {
74
+ const outcome = await send(subscription, payload);
75
+ report[outcome.status] += 1;
76
+ if (outcome.status === 'failed' && report.errors.length < 10) report.errors.push(outcome.error);
77
+ }
78
+ return report;
79
+ }
80
+
81
+ return { send, broadcast };
82
+ }
83
+
84
+ module.exports = { createPushSender };
package/src/sms.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Sending SMS, whatever carries them.
3
+ *
4
+ * The transport is injected — Twilio, Infobip, a local gateway. What this adds
5
+ * is the same ring as mail: nothing user-facing throws, and the absence of a
6
+ * configured provider is a VISIBLE simulation, not a crash. A product in
7
+ * development sends its codes to the log, loudly labelled, instead of falling
8
+ * over on every verification — and instead of silently pretending it sent.
9
+ */
10
+
11
+ const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
12
+
13
+ /**
14
+ * A number good enough to hand a provider: digits and one leading plus.
15
+ *
16
+ * Not a validation — phone plans vary too much for a regex to rule on. What
17
+ * it strips is what breaks providers: spaces, dots, dashes, parentheses.
18
+ */
19
+ function normalizePhone(value) {
20
+ const raw = String(value === null || value === undefined ? '' : value).trim();
21
+ const cleaned = (raw.startsWith('+') ? '+' : '') + raw.replace(/\D/g, '');
22
+ return cleaned.length >= 8 ? cleaned : null;
23
+ }
24
+
25
+ /**
26
+ * @param {object} options
27
+ * @param {Function} [options.transport] async ({ to, text }) => any. Absent
28
+ * means SIMULATION: logged, labelled, returned as such.
29
+ * @param {number} [options.maxLength] hard cap. Default 480 (3 segments) —
30
+ * an unbounded text concatenated into an SMS is how a bug becomes a bill.
31
+ * @param {object} [options.logger]
32
+ */
33
+ function createSmsSender(options = {}) {
34
+ const transport = options.transport || null;
35
+ const maxLength = options.maxLength || 480;
36
+ const logger = options.logger || NOOP_LOGGER;
37
+
38
+ /**
39
+ * @returns {Promise<{sent: boolean, simulated?: boolean, to?: string, reason?: string, error?: string}>}
40
+ * Never throws.
41
+ */
42
+ async function send(to, text) {
43
+ const phone = normalizePhone(to);
44
+ if (!phone) {
45
+ logger.warn('[sms] no valid number — nothing sent');
46
+ return { sent: false, reason: 'no-recipient' };
47
+ }
48
+
49
+ const body = String(text === null || text === undefined ? '' : text).trim();
50
+ if (!body) {
51
+ logger.warn('[sms] empty message — nothing sent');
52
+ return { sent: false, to: phone, reason: 'no-text' };
53
+ }
54
+ const capped = body.length > maxLength ? `${body.slice(0, maxLength - 1)}…` : body;
55
+
56
+ if (!transport) {
57
+ /* Loud on purpose: a simulated send that looks real is worse than a
58
+ failure — someone waits for a code that never left the log. */
59
+ logger.warn(`[sms] SIMULATION — no transport configured. To ${phone}: ${capped}`);
60
+ return { sent: true, simulated: true, to: phone };
61
+ }
62
+
63
+ try {
64
+ const result = await transport({ to: phone, text: capped });
65
+ logger.info(`[sms] sent to ${phone}`);
66
+ return { sent: true, to: phone, result };
67
+ } catch (error) {
68
+ logger.error(`[sms] failed to ${phone}: ${error.message}`);
69
+ return { sent: false, to: phone, reason: 'send-failed', error: error.message };
70
+ }
71
+ }
72
+
73
+ return { send, normalizePhone };
74
+ }
75
+
76
+ module.exports = { createSmsSender, normalizePhone };
@@ -0,0 +1,151 @@
1
+ /**
2
+ * HTML that survives a mail client.
3
+ *
4
+ * Email rendering is not the web. Outlook uses Word to lay out HTML, Gmail
5
+ * strips `<style>` blocks and anything it does not recognise, and flexbox,
6
+ * grid, custom properties and external stylesheets are simply absent. What
7
+ * works everywhere is what worked in 2005: nested tables and inline styles.
8
+ *
9
+ * So this is not a design system. It is the smallest skeleton that arrives
10
+ * looking the same in Gmail, Outlook and Apple Mail, with your colours applied
11
+ * to it. Everything about the LOOK is yours; everything about the plumbing is
12
+ * here.
13
+ */
14
+
15
+ /**
16
+ * Escaping is not optional, and it is not only about scripts.
17
+ *
18
+ * A customer named "Dupont & Fils <SARL>" breaks the layout of every message
19
+ * they are named in, long before anybody tries to attack you.
20
+ */
21
+ function escapeHtml(value) {
22
+ return String(value === null || value === undefined ? '' : value)
23
+ .replace(/&/g, '&amp;')
24
+ .replace(/</g, '&lt;')
25
+ .replace(/>/g, '&gt;')
26
+ .replace(/"/g, '&quot;')
27
+ .replace(/'/g, '&#39;');
28
+ }
29
+
30
+ const DEFAULT_THEME = {
31
+ background: '#f4f5f7',
32
+ surface: '#ffffff',
33
+ text: '#1a1a1a',
34
+ muted: '#6b7280',
35
+ accent: '#2563eb',
36
+ accentText: '#ffffff',
37
+ border: '#e5e7eb',
38
+ fontFamily: 'Arial, Helvetica, sans-serif',
39
+ width: 600
40
+ };
41
+
42
+ /**
43
+ * The line shown next to the subject in an inbox list.
44
+ *
45
+ * Left unset, clients grab the first words of the body — usually "View this
46
+ * email in your browser" or a stray alt text. Hidden in the message itself.
47
+ */
48
+ function preheader(text) {
49
+ if (!text) return '';
50
+ return `<div style="display:none;font-size:1px;color:transparent;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden">${escapeHtml(text)}</div>`;
51
+ }
52
+
53
+ function paragraph(text, theme) {
54
+ return `<p style="margin:0 0 16px;font-size:15px;line-height:1.6;color:${theme.text}">${escapeHtml(text)}</p>`;
55
+ }
56
+
57
+ function heading(text, theme) {
58
+ return `<h1 style="margin:0 0 18px;font-size:22px;line-height:1.3;color:${theme.text};font-weight:700">${escapeHtml(text)}</h1>`;
59
+ }
60
+
61
+ /**
62
+ * A button, built as a table.
63
+ *
64
+ * A styled `<a>` collapses to a bare link in Outlook, because Word's rendering
65
+ * engine ignores padding on inline elements. A single-cell table with a
66
+ * background is the shape that survives.
67
+ */
68
+ function button(label, url, theme) {
69
+ const safeUrl = /^https?:\/\//i.test(String(url || '')) ? String(url) : '#';
70
+ return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 20px"><tr><td style="background:${theme.accent};border-radius:6px"><a href="${escapeHtml(safeUrl)}" style="display:inline-block;padding:12px 24px;font-size:15px;font-weight:700;color:${theme.accentText};text-decoration:none">${escapeHtml(label)}</a></td></tr></table>`;
71
+ }
72
+
73
+ /** A code to read aloud or retype — spaced out so it can be. */
74
+ function code(value, theme) {
75
+ return `<p style="margin:0 0 20px;font-size:30px;font-weight:800;letter-spacing:8px;color:${theme.text};font-family:monospace">${escapeHtml(value)}</p>`;
76
+ }
77
+
78
+ function divider(theme) {
79
+ return `<div style="height:1px;background:${theme.border};margin:0 0 20px"></div>`;
80
+ }
81
+
82
+ function note(text, theme) {
83
+ return `<p style="margin:0 0 12px;font-size:13px;line-height:1.5;color:${theme.muted}">${escapeHtml(text)}</p>`;
84
+ }
85
+
86
+ const RENDERERS = { heading, paragraph, button, code, divider, note };
87
+
88
+ /**
89
+ * @param {object} options
90
+ * @param {Array} options.blocks [{ type, ...args }] — heading, paragraph,
91
+ * button, code, divider, note, or { type: 'html', html } for your own markup.
92
+ * @param {string} [options.preheader]
93
+ * @param {string} [options.footer]
94
+ * @param {object} [options.theme]
95
+ * @returns {string} a complete HTML document.
96
+ */
97
+ function renderEmail(options = {}) {
98
+ const theme = { ...DEFAULT_THEME, ...(options.theme || {}) };
99
+ const blocks = options.blocks || [];
100
+
101
+ const body = blocks.map((block) => {
102
+ if (!block || !block.type) return '';
103
+ /* An escape hatch, and it is deliberately explicit: `html` says out loud
104
+ that this string is NOT escaped, so it never happens by accident. */
105
+ if (block.type === 'html') return block.html || '';
106
+ const render = RENDERERS[block.type];
107
+ if (!render) return '';
108
+ if (block.type === 'divider') return divider(theme);
109
+ if (block.type === 'button') return button(block.label, block.url, theme);
110
+ return render(block.text === undefined ? block.value : block.text, theme);
111
+ }).join('\n ');
112
+
113
+ const footer = options.footer
114
+ ? `<p style="margin:18px 0 0;font-size:12px;line-height:1.5;color:${theme.muted};text-align:center">${escapeHtml(options.footer)}</p>`
115
+ : '';
116
+
117
+ return `<!doctype html>
118
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
119
+ <body style="margin:0;padding:0;background:${theme.background}">
120
+ ${preheader(options.preheader)}
121
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:${theme.background};padding:28px 12px">
122
+ <tr><td align="center">
123
+ <table role="presentation" width="${theme.width}" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:${theme.width}px;background:${theme.surface};border-radius:10px;padding:32px;font-family:${theme.fontFamily}">
124
+ <tr><td>
125
+ ${body}
126
+ </td></tr>
127
+ </table>
128
+ ${footer}
129
+ </td></tr>
130
+ </table>
131
+ </body></html>`;
132
+ }
133
+
134
+ /**
135
+ * The same content as plain text.
136
+ *
137
+ * Not a courtesy. A message with no text part scores worse with spam filters,
138
+ * and some clients — and every screen reader working from the text part — show
139
+ * that version. Generating it from the same blocks keeps the two in step.
140
+ */
141
+ function renderText(options = {}) {
142
+ return (options.blocks || []).map((block) => {
143
+ if (!block || !block.type) return '';
144
+ if (block.type === 'divider') return '---';
145
+ if (block.type === 'button') return `${block.label}: ${block.url}`;
146
+ if (block.type === 'html') return '';
147
+ return String(block.text === undefined ? block.value : block.text);
148
+ }).filter(Boolean).join('\n\n');
149
+ }
150
+
151
+ module.exports = { renderEmail, renderText, escapeHtml, DEFAULT_THEME };