@miguelmorales13/nestkit 0.24.0 → 0.26.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/README.md +16 -3
- package/dist/auth/oauth/index.cjs +22 -14
- package/dist/auth/oauth/index.js +22 -14
- package/dist/auth/oauth/oauth-provider.d.ts +9 -0
- package/dist/auth/oauth/providers/apple.d.ts +3 -1
- package/dist/email/adapters/zeptomail.email.d.ts +27 -0
- package/dist/email/email.module.d.ts +2 -1
- package/dist/email/email.options.d.ts +10 -1
- package/dist/email/index.cjs +90 -10
- package/dist/email/index.d.ts +2 -1
- package/dist/email/index.js +89 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1415,6 +1415,11 @@ subidos por la persona, que necesitan un permiso que la app no tiene, y el callb
|
|
|
1415
1415
|
500. El flujo entero son unas cuarenta líneas de `fetch` y cada campo que se manda se ve en
|
|
1416
1416
|
`oauth-provider.ts`.
|
|
1417
1417
|
|
|
1418
|
+
**Red inyectable (0.26.0, opcional).** Todo proveedor acepta `fetchImpl?: typeof fetch` en sus credenciales
|
|
1419
|
+
(`googleProvider({ fetchImpl })`, etc.): lo usa para el canje del `code` por el token y para leer el perfil
|
|
1420
|
+
(Apple, también para sus llaves públicas). Sirve para pasar por un cliente con tiempo límite, reintentos y
|
|
1421
|
+
alertas. Sin la opción se usa el `fetch` global, igual que antes.
|
|
1422
|
+
|
|
1418
1423
|
Un proveedor es un objeto, no una clase que heredar: vienen ocho —`googleProvider`,
|
|
1419
1424
|
`appleProvider`, `facebookProvider`, `tiktokProvider`, `githubProvider`, `microsoftProvider`,
|
|
1420
1425
|
`discordProvider`, `linkedinProvider`— y uno nuevo es declarar cuatro URLs y una función que mapee su
|
|
@@ -1807,7 +1812,7 @@ suscripción que `PushManager.subscribe()` devuelve.
|
|
|
1807
1812
|
### `email` — correo transaccional con el proveedor como configuración
|
|
1808
1813
|
|
|
1809
1814
|
Un puerto, `EmailPort`, y el proveedor detrás se elige en una línea: **Resend**, **Brevo** (antes
|
|
1810
|
-
Sendinblue) o **cualquier servidor SMTP** vía Nodemailer. Mismo patrón que `storage`: nada en la
|
|
1815
|
+
Sendinblue), **ZeptoMail** (Zoho) o **cualquier servidor SMTP** vía Nodemailer. Mismo patrón que `storage`: nada en la
|
|
1811
1816
|
app depende de un cliente concreto, así que cambiar de proveedor no toca ninguna llamada.
|
|
1812
1817
|
|
|
1813
1818
|
```ts
|
|
@@ -1817,6 +1822,7 @@ import { EmailModule } from '@miguelmorales13/nestkit/email';
|
|
|
1817
1822
|
imports: [
|
|
1818
1823
|
EmailModule.forRoot({ provider: 'brevo' }), // lee BREVO_API_KEY y EMAIL_FROM
|
|
1819
1824
|
// EmailModule.forRoot({ provider: 'resend', from: 'Mi App <hola@miapp.mx>' }),
|
|
1825
|
+
// EmailModule.forRoot({ provider: 'zeptomail' }), // lee ZEPTOMAIL_API_KEY y EMAIL_FROM
|
|
1820
1826
|
// EmailModule.forRoot({ provider: 'smtp', smtp: { host, port: 587, user, password } }),
|
|
1821
1827
|
// EmailModule.forRoot({ provider: 'memory' }), // pruebas y desarrollo: nadie recibe nada
|
|
1822
1828
|
],
|
|
@@ -1846,7 +1852,7 @@ export class NotificationsService {
|
|
|
1846
1852
|
|
|
1847
1853
|
Lo que no pases en código sale del entorno: `EMAIL_PROVIDER`, `EMAIL_FROM`, `EMAIL_REPLY_TO`;
|
|
1848
1854
|
`RESEND_API_KEY`; `SMTP_HOST`, `SMTP_PORT`, `SMTP_SECURE`, `SMTP_USER`, `SMTP_PASSWORD`;
|
|
1849
|
-
`BREVO_API_KEY`. **No hay proveedor por defecto**: sin `provider` ni `EMAIL_PROVIDER` el módulo
|
|
1855
|
+
`BREVO_API_KEY`; `ZEPTOMAIL_API_KEY`, `ZEPTOMAIL_BASE_URL`. **No hay proveedor por defecto**: sin `provider` ni `EMAIL_PROVIDER` el módulo
|
|
1850
1856
|
falla al cablear, no en el primer envío. Lo mismo si el proveedor elegido no tiene credenciales.
|
|
1851
1857
|
|
|
1852
1858
|
El mensaje es el mismo para los tres —`from`, `to`/`cc`/`bcc`, `replyTo`, `subject`, `text`/`html`,
|
|
@@ -1862,6 +1868,13 @@ de su lista** (pdf, docx, xlsx, csv, png, jpg, zip… — un `.exe` o un `.json`
|
|
|
1862
1868
|
SMTP (`smtp-relay.brevo.com:587`, login + clave SMTP) también funciona con `provider: 'smtp'`, por
|
|
1863
1869
|
si se prefiere.
|
|
1864
1870
|
|
|
1871
|
+
**ZeptoMail** (el servicio transaccional de Zoho, centavos por correo) también va por REST con
|
|
1872
|
+
`fetch`: un `POST /email` con el token del Mail Agent en `Authorization: Zoho-enczapikey <token>`.
|
|
1873
|
+
Cosas a saber: el dominio del `from` debe estar verificado en ZeptoMail (SPF + DKIM) o responde 4xx;
|
|
1874
|
+
el token vive en un centro de datos, así que una cuenta `.eu`, `.in` o `.com.au` debe poner su host
|
|
1875
|
+
en `ZEPTOMAIL_BASE_URL` (`https://api.zeptomail.eu/v1.1`) o todo envío da 401; no tiene campo de
|
|
1876
|
+
etiquetas, por lo que los `tags` salen como cabeceras `X-Tag-<nombre>` como en SMTP.
|
|
1877
|
+
|
|
1865
1878
|
Los SDKs de Resend y Nodemailer se cargan **perezosamente en el primer envío**: una app en Brevo no
|
|
1866
1879
|
instala ninguno de los dos. `memory` guarda cada mensaje en `MemoryEmail.sent` — el buzón de salida
|
|
1867
1880
|
de las pruebas.
|
|
@@ -2055,7 +2068,7 @@ trae los datos.
|
|
|
2055
2068
|
| `@miguelmorales13/nestkit/payments` | `PaymentsModule`, `TERMINAL_PAYMENTS`, `TerminalPaymentsPort`, adaptadores `MercadoPagoTerminalPayments`/`ClipTerminalPayments`, `MercadoPagoConnect` (OAuth marketplace), `isIntegrableTerminalModel`, `createTerminalPaymentsWebhookController` |
|
|
2056
2069
|
| `@miguelmorales13/nestkit/storage` | `StorageModule`, `STORAGE`, `StoragePort`, adaptadores `LocalStorage`/`S3Storage`/`BunnyStorage` |
|
|
2057
2070
|
| `@miguelmorales13/nestkit/push` | `PushModule`, `PUSH`, `PushPort`, `PUSH_DEVICE_STORE`, `PushDeviceStorePort`, canales `FcmChannel`/`WebPushChannel`, `toFcmMessage` |
|
|
2058
|
-
| `@miguelmorales13/nestkit/email` | `EmailModule`, `EMAIL`, `EmailPort`, adaptadores `ResendEmail`/`SmtpEmail`/`BrevoEmail`/`MemoryEmail` |
|
|
2071
|
+
| `@miguelmorales13/nestkit/email` | `EmailModule`, `EMAIL`, `EmailPort`, adaptadores `ResendEmail`/`SmtpEmail`/`BrevoEmail`/`ZeptoMailEmail`/`MemoryEmail` |
|
|
2059
2072
|
| `@miguelmorales13/nestkit/email/resend` | `ResendModule`, `RESEND_CLIENT` |
|
|
2060
2073
|
| `@miguelmorales13/nestkit/email/nodemailer` | `NodemailerModule`, `NODEMAILER_TRANSPORT` |
|
|
2061
2074
|
| `@miguelmorales13/nestkit/i18n` | `I18nModule`, `t`, `translate`, `currentLanguage`, `I18nInterceptor`, `TranslatorPort`, `NestI18nTranslator`, `translateOr` |
|
|
@@ -32,6 +32,7 @@ async function readJson(response, what) {
|
|
|
32
32
|
function googleProvider(credentials = {}) {
|
|
33
33
|
return {
|
|
34
34
|
name: "google",
|
|
35
|
+
fetchImpl: credentials.fetchImpl,
|
|
35
36
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.GOOGLE_CLIENT_ID)),
|
|
36
37
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.GOOGLE_CLIENT_SECRET)),
|
|
37
38
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.GOOGLE_CALLBACK_URL)),
|
|
@@ -47,7 +48,7 @@ function googleProvider(credentials = {}) {
|
|
|
47
48
|
},
|
|
48
49
|
async fetchProfile(accessToken) {
|
|
49
50
|
const data = await readJson(
|
|
50
|
-
await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
|
|
51
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://www.googleapis.com/oauth2/v3/userinfo", {
|
|
51
52
|
headers: { Authorization: `Bearer ${accessToken}` }
|
|
52
53
|
}),
|
|
53
54
|
"Google userinfo"
|
|
@@ -69,6 +70,7 @@ function facebookProvider(credentials = {}) {
|
|
|
69
70
|
const version = _nullishCoalesce(process.env.FACEBOOK_GRAPH_VERSION, () => ( "v21.0"));
|
|
70
71
|
return {
|
|
71
72
|
name: "facebook",
|
|
73
|
+
fetchImpl: credentials.fetchImpl,
|
|
72
74
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.FACEBOOK_APP_ID)),
|
|
73
75
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.FACEBOOK_APP_SECRET)),
|
|
74
76
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.FACEBOOK_CALLBACK_URL)),
|
|
@@ -79,7 +81,7 @@ function facebookProvider(credentials = {}) {
|
|
|
79
81
|
const url = new URL(`https://graph.facebook.com/${version}/me`);
|
|
80
82
|
url.searchParams.set("fields", "id,name,email,picture.type(large)");
|
|
81
83
|
const data = await readJson(
|
|
82
|
-
await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
84
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
83
85
|
"Facebook me"
|
|
84
86
|
);
|
|
85
87
|
const picture = data.picture;
|
|
@@ -113,7 +115,7 @@ async function exchangeCode(provider, code) {
|
|
|
113
115
|
code
|
|
114
116
|
});
|
|
115
117
|
const data = await readJson(
|
|
116
|
-
await fetch(provider.tokenUrl, {
|
|
118
|
+
await (_nullishCoalesce(provider.fetchImpl, () => ( fetch)))(provider.tokenUrl, {
|
|
117
119
|
method: "POST",
|
|
118
120
|
headers: {
|
|
119
121
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
@@ -145,6 +147,7 @@ function appleProvider(credentials = {}) {
|
|
|
145
147
|
const configured = Boolean(clientId && teamId && keyId && privateKey);
|
|
146
148
|
return {
|
|
147
149
|
name: "apple",
|
|
150
|
+
fetchImpl: credentials.fetchImpl,
|
|
148
151
|
clientId,
|
|
149
152
|
// Only offered as configured when every piece exists: `provider()` tests
|
|
150
153
|
// `clientSecret` for truthiness, and a function that would throw later
|
|
@@ -158,7 +161,7 @@ function appleProvider(credentials = {}) {
|
|
|
158
161
|
callbackMethod: "POST",
|
|
159
162
|
async fetchProfile(_accessToken, tokens, callback) {
|
|
160
163
|
if (!tokens.id_token) throw new Error("Apple token exchange returned no id_token.");
|
|
161
|
-
const claims = await verifyAppleIdToken(tokens.id_token, clientId, keysUrl);
|
|
164
|
+
const claims = await verifyAppleIdToken(tokens.id_token, clientId, keysUrl, credentials.fetchImpl);
|
|
162
165
|
const verified = claims.email_verified === true || claims.email_verified === "true";
|
|
163
166
|
return {
|
|
164
167
|
providerAccountId: claims.sub,
|
|
@@ -180,17 +183,17 @@ function mintClientSecret(clientId, teamId, keyId, privateKey) {
|
|
|
180
183
|
}
|
|
181
184
|
var cachedKeys;
|
|
182
185
|
var KEYS_TTL_MS = 60 * 60 * 1e3;
|
|
183
|
-
async function appleKeys(keysUrl, kid) {
|
|
186
|
+
async function appleKeys(keysUrl, kid, fetchImpl) {
|
|
184
187
|
const fresh = cachedKeys && Date.now() - cachedKeys.fetchedAt < KEYS_TTL_MS;
|
|
185
188
|
if (fresh && cachedKeys.keys.some((k) => k.kid === kid)) return cachedKeys.keys;
|
|
186
|
-
const data = await readJson(await fetch(keysUrl), "Apple keys");
|
|
189
|
+
const data = await readJson(await (_nullishCoalesce(fetchImpl, () => ( fetch)))(keysUrl), "Apple keys");
|
|
187
190
|
cachedKeys = { fetchedAt: Date.now(), keys: _nullishCoalesce(data.keys, () => ( [])) };
|
|
188
191
|
return cachedKeys.keys;
|
|
189
192
|
}
|
|
190
|
-
async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL) {
|
|
193
|
+
async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL, fetchImpl) {
|
|
191
194
|
const decoded = _jsonwebtoken2.default.decode(idToken, { complete: true });
|
|
192
195
|
const kid = _optionalChain([decoded, 'optionalAccess', _5 => _5.header, 'access', _6 => _6.kid]);
|
|
193
|
-
const key = (await appleKeys(keysUrl, kid)).find((k) => k.kid === kid);
|
|
196
|
+
const key = (await appleKeys(keysUrl, kid, fetchImpl)).find((k) => k.kid === kid);
|
|
194
197
|
if (!key) throw new Error("Apple id_token is signed with a key Apple does not publish.");
|
|
195
198
|
const pem = _crypto.createPublicKey.call(void 0, { key, format: "jwk" }).export({ type: "spki", format: "pem" });
|
|
196
199
|
return _jsonwebtoken2.default.verify(idToken, pem, { algorithms: ["RS256"], audience: clientId, issuer: ISSUER });
|
|
@@ -211,6 +214,7 @@ function nameFromCallback(callback) {
|
|
|
211
214
|
function tiktokProvider(credentials = {}) {
|
|
212
215
|
return {
|
|
213
216
|
name: "tiktok",
|
|
217
|
+
fetchImpl: credentials.fetchImpl,
|
|
214
218
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.TIKTOK_CLIENT_KEY)),
|
|
215
219
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.TIKTOK_CLIENT_SECRET)),
|
|
216
220
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.TIKTOK_CALLBACK_URL)),
|
|
@@ -222,7 +226,7 @@ function tiktokProvider(credentials = {}) {
|
|
|
222
226
|
const url = new URL("https://open.tiktokapis.com/v2/user/info/");
|
|
223
227
|
url.searchParams.set("fields", "open_id,display_name,avatar_url");
|
|
224
228
|
const data = await readJson(
|
|
225
|
-
await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
229
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
226
230
|
"TikTok user info"
|
|
227
231
|
);
|
|
228
232
|
const error = data.error;
|
|
@@ -243,6 +247,7 @@ function tiktokProvider(credentials = {}) {
|
|
|
243
247
|
function githubProvider(credentials = {}) {
|
|
244
248
|
return {
|
|
245
249
|
name: "github",
|
|
250
|
+
fetchImpl: credentials.fetchImpl,
|
|
246
251
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.GITHUB_CLIENT_ID)),
|
|
247
252
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.GITHUB_CLIENT_SECRET)),
|
|
248
253
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.GITHUB_CALLBACK_URL)),
|
|
@@ -255,9 +260,9 @@ function githubProvider(credentials = {}) {
|
|
|
255
260
|
Accept: "application/vnd.github+json",
|
|
256
261
|
"User-Agent": "nestkit"
|
|
257
262
|
};
|
|
258
|
-
const user = await readJson(await fetch("https://api.github.com/user", { headers }), "GitHub user");
|
|
263
|
+
const user = await readJson(await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://api.github.com/user", { headers }), "GitHub user");
|
|
259
264
|
const emails = await readJson(
|
|
260
|
-
await fetch("https://api.github.com/user/emails", { headers }),
|
|
265
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://api.github.com/user/emails", { headers }),
|
|
261
266
|
"GitHub emails"
|
|
262
267
|
);
|
|
263
268
|
const primary = Array.isArray(emails) ? _nullishCoalesce(emails.find((e) => e.primary && e.verified), () => ( emails.find((e) => e.verified))) : void 0;
|
|
@@ -276,6 +281,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
276
281
|
const tenant = _nullishCoalesce(_nullishCoalesce(credentials.tenant, () => ( process.env.MICROSOFT_TENANT)), () => ( "common"));
|
|
277
282
|
return {
|
|
278
283
|
name: "microsoft",
|
|
284
|
+
fetchImpl: credentials.fetchImpl,
|
|
279
285
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.MICROSOFT_CLIENT_ID)),
|
|
280
286
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.MICROSOFT_CLIENT_SECRET)),
|
|
281
287
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.MICROSOFT_CALLBACK_URL)),
|
|
@@ -284,7 +290,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
284
290
|
scope: _nullishCoalesce(credentials.scope, () => ( "openid profile email User.Read")),
|
|
285
291
|
async fetchProfile(accessToken) {
|
|
286
292
|
const me = await readJson(
|
|
287
|
-
await fetch("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
293
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
288
294
|
"Microsoft Graph me"
|
|
289
295
|
);
|
|
290
296
|
const email = _nullishCoalesce(me.mail, () => ( me.userPrincipalName));
|
|
@@ -301,6 +307,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
301
307
|
function discordProvider(credentials = {}) {
|
|
302
308
|
return {
|
|
303
309
|
name: "discord",
|
|
310
|
+
fetchImpl: credentials.fetchImpl,
|
|
304
311
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.DISCORD_CLIENT_ID)),
|
|
305
312
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.DISCORD_CLIENT_SECRET)),
|
|
306
313
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.DISCORD_CALLBACK_URL)),
|
|
@@ -309,7 +316,7 @@ function discordProvider(credentials = {}) {
|
|
|
309
316
|
scope: _nullishCoalesce(credentials.scope, () => ( "identify email")),
|
|
310
317
|
async fetchProfile(accessToken) {
|
|
311
318
|
const user = await readJson(
|
|
312
|
-
await fetch("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
319
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
313
320
|
"Discord user"
|
|
314
321
|
);
|
|
315
322
|
const id = String(user.id);
|
|
@@ -328,6 +335,7 @@ function discordProvider(credentials = {}) {
|
|
|
328
335
|
function linkedinProvider(credentials = {}) {
|
|
329
336
|
return {
|
|
330
337
|
name: "linkedin",
|
|
338
|
+
fetchImpl: credentials.fetchImpl,
|
|
331
339
|
clientId: _nullishCoalesce(credentials.clientId, () => ( process.env.LINKEDIN_CLIENT_ID)),
|
|
332
340
|
clientSecret: _nullishCoalesce(credentials.clientSecret, () => ( process.env.LINKEDIN_CLIENT_SECRET)),
|
|
333
341
|
callbackUrl: _nullishCoalesce(credentials.callbackUrl, () => ( process.env.LINKEDIN_CALLBACK_URL)),
|
|
@@ -336,7 +344,7 @@ function linkedinProvider(credentials = {}) {
|
|
|
336
344
|
scope: _nullishCoalesce(credentials.scope, () => ( "openid profile email")),
|
|
337
345
|
async fetchProfile(accessToken) {
|
|
338
346
|
const claims = await readJson(
|
|
339
|
-
await fetch("https://api.linkedin.com/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
347
|
+
await (_nullishCoalesce(credentials.fetchImpl, () => ( fetch)))("https://api.linkedin.com/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
340
348
|
"LinkedIn userinfo"
|
|
341
349
|
);
|
|
342
350
|
return {
|
package/dist/auth/oauth/index.js
CHANGED
|
@@ -32,6 +32,7 @@ async function readJson(response, what) {
|
|
|
32
32
|
function googleProvider(credentials = {}) {
|
|
33
33
|
return {
|
|
34
34
|
name: "google",
|
|
35
|
+
fetchImpl: credentials.fetchImpl,
|
|
35
36
|
clientId: credentials.clientId ?? process.env.GOOGLE_CLIENT_ID,
|
|
36
37
|
clientSecret: credentials.clientSecret ?? process.env.GOOGLE_CLIENT_SECRET,
|
|
37
38
|
callbackUrl: credentials.callbackUrl ?? process.env.GOOGLE_CALLBACK_URL,
|
|
@@ -47,7 +48,7 @@ function googleProvider(credentials = {}) {
|
|
|
47
48
|
},
|
|
48
49
|
async fetchProfile(accessToken) {
|
|
49
50
|
const data = await readJson(
|
|
50
|
-
await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
|
|
51
|
+
await (credentials.fetchImpl ?? fetch)("https://www.googleapis.com/oauth2/v3/userinfo", {
|
|
51
52
|
headers: { Authorization: `Bearer ${accessToken}` }
|
|
52
53
|
}),
|
|
53
54
|
"Google userinfo"
|
|
@@ -69,6 +70,7 @@ function facebookProvider(credentials = {}) {
|
|
|
69
70
|
const version = process.env.FACEBOOK_GRAPH_VERSION ?? "v21.0";
|
|
70
71
|
return {
|
|
71
72
|
name: "facebook",
|
|
73
|
+
fetchImpl: credentials.fetchImpl,
|
|
72
74
|
clientId: credentials.clientId ?? process.env.FACEBOOK_APP_ID,
|
|
73
75
|
clientSecret: credentials.clientSecret ?? process.env.FACEBOOK_APP_SECRET,
|
|
74
76
|
callbackUrl: credentials.callbackUrl ?? process.env.FACEBOOK_CALLBACK_URL,
|
|
@@ -79,7 +81,7 @@ function facebookProvider(credentials = {}) {
|
|
|
79
81
|
const url = new URL(`https://graph.facebook.com/${version}/me`);
|
|
80
82
|
url.searchParams.set("fields", "id,name,email,picture.type(large)");
|
|
81
83
|
const data = await readJson(
|
|
82
|
-
await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
84
|
+
await (credentials.fetchImpl ?? fetch)(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
83
85
|
"Facebook me"
|
|
84
86
|
);
|
|
85
87
|
const picture = data.picture;
|
|
@@ -113,7 +115,7 @@ async function exchangeCode(provider, code) {
|
|
|
113
115
|
code
|
|
114
116
|
});
|
|
115
117
|
const data = await readJson(
|
|
116
|
-
await fetch(provider.tokenUrl, {
|
|
118
|
+
await (provider.fetchImpl ?? fetch)(provider.tokenUrl, {
|
|
117
119
|
method: "POST",
|
|
118
120
|
headers: {
|
|
119
121
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
@@ -145,6 +147,7 @@ function appleProvider(credentials = {}) {
|
|
|
145
147
|
const configured = Boolean(clientId && teamId && keyId && privateKey);
|
|
146
148
|
return {
|
|
147
149
|
name: "apple",
|
|
150
|
+
fetchImpl: credentials.fetchImpl,
|
|
148
151
|
clientId,
|
|
149
152
|
// Only offered as configured when every piece exists: `provider()` tests
|
|
150
153
|
// `clientSecret` for truthiness, and a function that would throw later
|
|
@@ -158,7 +161,7 @@ function appleProvider(credentials = {}) {
|
|
|
158
161
|
callbackMethod: "POST",
|
|
159
162
|
async fetchProfile(_accessToken, tokens, callback) {
|
|
160
163
|
if (!tokens.id_token) throw new Error("Apple token exchange returned no id_token.");
|
|
161
|
-
const claims = await verifyAppleIdToken(tokens.id_token, clientId, keysUrl);
|
|
164
|
+
const claims = await verifyAppleIdToken(tokens.id_token, clientId, keysUrl, credentials.fetchImpl);
|
|
162
165
|
const verified = claims.email_verified === true || claims.email_verified === "true";
|
|
163
166
|
return {
|
|
164
167
|
providerAccountId: claims.sub,
|
|
@@ -180,17 +183,17 @@ function mintClientSecret(clientId, teamId, keyId, privateKey) {
|
|
|
180
183
|
}
|
|
181
184
|
var cachedKeys;
|
|
182
185
|
var KEYS_TTL_MS = 60 * 60 * 1e3;
|
|
183
|
-
async function appleKeys(keysUrl, kid) {
|
|
186
|
+
async function appleKeys(keysUrl, kid, fetchImpl) {
|
|
184
187
|
const fresh = cachedKeys && Date.now() - cachedKeys.fetchedAt < KEYS_TTL_MS;
|
|
185
188
|
if (fresh && cachedKeys.keys.some((k) => k.kid === kid)) return cachedKeys.keys;
|
|
186
|
-
const data = await readJson(await fetch(keysUrl), "Apple keys");
|
|
189
|
+
const data = await readJson(await (fetchImpl ?? fetch)(keysUrl), "Apple keys");
|
|
187
190
|
cachedKeys = { fetchedAt: Date.now(), keys: data.keys ?? [] };
|
|
188
191
|
return cachedKeys.keys;
|
|
189
192
|
}
|
|
190
|
-
async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL) {
|
|
193
|
+
async function verifyAppleIdToken(idToken, clientId, keysUrl = KEYS_URL, fetchImpl) {
|
|
191
194
|
const decoded = jwt.decode(idToken, { complete: true });
|
|
192
195
|
const kid = decoded?.header.kid;
|
|
193
|
-
const key = (await appleKeys(keysUrl, kid)).find((k) => k.kid === kid);
|
|
196
|
+
const key = (await appleKeys(keysUrl, kid, fetchImpl)).find((k) => k.kid === kid);
|
|
194
197
|
if (!key) throw new Error("Apple id_token is signed with a key Apple does not publish.");
|
|
195
198
|
const pem = createPublicKey({ key, format: "jwk" }).export({ type: "spki", format: "pem" });
|
|
196
199
|
return jwt.verify(idToken, pem, { algorithms: ["RS256"], audience: clientId, issuer: ISSUER });
|
|
@@ -211,6 +214,7 @@ function nameFromCallback(callback) {
|
|
|
211
214
|
function tiktokProvider(credentials = {}) {
|
|
212
215
|
return {
|
|
213
216
|
name: "tiktok",
|
|
217
|
+
fetchImpl: credentials.fetchImpl,
|
|
214
218
|
clientId: credentials.clientId ?? process.env.TIKTOK_CLIENT_KEY,
|
|
215
219
|
clientSecret: credentials.clientSecret ?? process.env.TIKTOK_CLIENT_SECRET,
|
|
216
220
|
callbackUrl: credentials.callbackUrl ?? process.env.TIKTOK_CALLBACK_URL,
|
|
@@ -222,7 +226,7 @@ function tiktokProvider(credentials = {}) {
|
|
|
222
226
|
const url = new URL("https://open.tiktokapis.com/v2/user/info/");
|
|
223
227
|
url.searchParams.set("fields", "open_id,display_name,avatar_url");
|
|
224
228
|
const data = await readJson(
|
|
225
|
-
await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
229
|
+
await (credentials.fetchImpl ?? fetch)(url, { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
226
230
|
"TikTok user info"
|
|
227
231
|
);
|
|
228
232
|
const error = data.error;
|
|
@@ -243,6 +247,7 @@ function tiktokProvider(credentials = {}) {
|
|
|
243
247
|
function githubProvider(credentials = {}) {
|
|
244
248
|
return {
|
|
245
249
|
name: "github",
|
|
250
|
+
fetchImpl: credentials.fetchImpl,
|
|
246
251
|
clientId: credentials.clientId ?? process.env.GITHUB_CLIENT_ID,
|
|
247
252
|
clientSecret: credentials.clientSecret ?? process.env.GITHUB_CLIENT_SECRET,
|
|
248
253
|
callbackUrl: credentials.callbackUrl ?? process.env.GITHUB_CALLBACK_URL,
|
|
@@ -255,9 +260,9 @@ function githubProvider(credentials = {}) {
|
|
|
255
260
|
Accept: "application/vnd.github+json",
|
|
256
261
|
"User-Agent": "nestkit"
|
|
257
262
|
};
|
|
258
|
-
const user = await readJson(await fetch("https://api.github.com/user", { headers }), "GitHub user");
|
|
263
|
+
const user = await readJson(await (credentials.fetchImpl ?? fetch)("https://api.github.com/user", { headers }), "GitHub user");
|
|
259
264
|
const emails = await readJson(
|
|
260
|
-
await fetch("https://api.github.com/user/emails", { headers }),
|
|
265
|
+
await (credentials.fetchImpl ?? fetch)("https://api.github.com/user/emails", { headers }),
|
|
261
266
|
"GitHub emails"
|
|
262
267
|
);
|
|
263
268
|
const primary = Array.isArray(emails) ? emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified) : void 0;
|
|
@@ -276,6 +281,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
276
281
|
const tenant = credentials.tenant ?? process.env.MICROSOFT_TENANT ?? "common";
|
|
277
282
|
return {
|
|
278
283
|
name: "microsoft",
|
|
284
|
+
fetchImpl: credentials.fetchImpl,
|
|
279
285
|
clientId: credentials.clientId ?? process.env.MICROSOFT_CLIENT_ID,
|
|
280
286
|
clientSecret: credentials.clientSecret ?? process.env.MICROSOFT_CLIENT_SECRET,
|
|
281
287
|
callbackUrl: credentials.callbackUrl ?? process.env.MICROSOFT_CALLBACK_URL,
|
|
@@ -284,7 +290,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
284
290
|
scope: credentials.scope ?? "openid profile email User.Read",
|
|
285
291
|
async fetchProfile(accessToken) {
|
|
286
292
|
const me = await readJson(
|
|
287
|
-
await fetch("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
293
|
+
await (credentials.fetchImpl ?? fetch)("https://graph.microsoft.com/v1.0/me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
288
294
|
"Microsoft Graph me"
|
|
289
295
|
);
|
|
290
296
|
const email = me.mail ?? me.userPrincipalName;
|
|
@@ -301,6 +307,7 @@ function microsoftProvider(credentials = {}) {
|
|
|
301
307
|
function discordProvider(credentials = {}) {
|
|
302
308
|
return {
|
|
303
309
|
name: "discord",
|
|
310
|
+
fetchImpl: credentials.fetchImpl,
|
|
304
311
|
clientId: credentials.clientId ?? process.env.DISCORD_CLIENT_ID,
|
|
305
312
|
clientSecret: credentials.clientSecret ?? process.env.DISCORD_CLIENT_SECRET,
|
|
306
313
|
callbackUrl: credentials.callbackUrl ?? process.env.DISCORD_CALLBACK_URL,
|
|
@@ -309,7 +316,7 @@ function discordProvider(credentials = {}) {
|
|
|
309
316
|
scope: credentials.scope ?? "identify email",
|
|
310
317
|
async fetchProfile(accessToken) {
|
|
311
318
|
const user = await readJson(
|
|
312
|
-
await fetch("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
319
|
+
await (credentials.fetchImpl ?? fetch)("https://discord.com/api/users/@me", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
313
320
|
"Discord user"
|
|
314
321
|
);
|
|
315
322
|
const id = String(user.id);
|
|
@@ -328,6 +335,7 @@ function discordProvider(credentials = {}) {
|
|
|
328
335
|
function linkedinProvider(credentials = {}) {
|
|
329
336
|
return {
|
|
330
337
|
name: "linkedin",
|
|
338
|
+
fetchImpl: credentials.fetchImpl,
|
|
331
339
|
clientId: credentials.clientId ?? process.env.LINKEDIN_CLIENT_ID,
|
|
332
340
|
clientSecret: credentials.clientSecret ?? process.env.LINKEDIN_CLIENT_SECRET,
|
|
333
341
|
callbackUrl: credentials.callbackUrl ?? process.env.LINKEDIN_CALLBACK_URL,
|
|
@@ -336,7 +344,7 @@ function linkedinProvider(credentials = {}) {
|
|
|
336
344
|
scope: credentials.scope ?? "openid profile email",
|
|
337
345
|
async fetchProfile(accessToken) {
|
|
338
346
|
const claims = await readJson(
|
|
339
|
-
await fetch("https://api.linkedin.com/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
347
|
+
await (credentials.fetchImpl ?? fetch)("https://api.linkedin.com/v2/userinfo", { headers: { Authorization: `Bearer ${accessToken}` } }),
|
|
340
348
|
"LinkedIn userinfo"
|
|
341
349
|
);
|
|
342
350
|
return {
|
|
@@ -63,6 +63,8 @@ export interface OAuthProviderConfig {
|
|
|
63
63
|
authorizeUrl: string;
|
|
64
64
|
/** Where the `code` is exchanged for an access token. */
|
|
65
65
|
tokenUrl: string;
|
|
66
|
+
/** Optional network hook for the token exchange (`exchangeCode`). Default: global `fetch`. */
|
|
67
|
+
fetchImpl?: typeof fetch;
|
|
66
68
|
scope: string;
|
|
67
69
|
/** Extra query parameters for the consent screen (`prompt`, `access_type`…). */
|
|
68
70
|
authorizeParams?: Record<string, string>;
|
|
@@ -92,6 +94,13 @@ export interface ProviderCredentials {
|
|
|
92
94
|
callbackUrl?: string;
|
|
93
95
|
/** Overrides the default scope. */
|
|
94
96
|
scope?: string;
|
|
97
|
+
/**
|
|
98
|
+
* Optional network hook for this provider's own calls (profile reads, and
|
|
99
|
+
* the `code` exchange via `OAuthProviderConfig.fetchImpl`). Lets the app
|
|
100
|
+
* route them through a resilient client (timeout, retries, alerts).
|
|
101
|
+
* Default: the global `fetch`.
|
|
102
|
+
*/
|
|
103
|
+
fetchImpl?: typeof fetch;
|
|
95
104
|
}
|
|
96
105
|
/**
|
|
97
106
|
* Reads a provider's JSON, or throws with the body when it fails.
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type OAuthProviderConfig } from '../oauth-provider.js';
|
|
2
2
|
export interface AppleCredentials {
|
|
3
|
+
/** Optional network hook (token exchange and Apple's public keys). Default: global `fetch`. */
|
|
4
|
+
fetchImpl?: typeof fetch;
|
|
3
5
|
/** The Services ID (`com.example.web`), not the App ID. `APPLE_CLIENT_ID`. */
|
|
4
6
|
clientId?: string;
|
|
5
7
|
/** `APPLE_TEAM_ID`. */
|
|
@@ -54,5 +56,5 @@ export declare function appleProvider(credentials?: AppleCredentials): OAuthProv
|
|
|
54
56
|
*/
|
|
55
57
|
export declare function mintClientSecret(clientId: string, teamId: string, keyId: string, privateKey: string): string;
|
|
56
58
|
/** Signature, issuer, audience and expiry — the four things a forged or replayed token fails. */
|
|
57
|
-
export declare function verifyAppleIdToken(idToken: string, clientId: string, keysUrl?: string): Promise<AppleIdClaims>;
|
|
59
|
+
export declare function verifyAppleIdToken(idToken: string, clientId: string, keysUrl?: string, fetchImpl?: typeof fetch): Promise<AppleIdClaims>;
|
|
58
60
|
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ZeptoMailEmailOptions } from '../email.options.js';
|
|
2
|
+
import { type EmailMessage, type EmailPort, type SentEmail } from '../email.port.js';
|
|
3
|
+
/**
|
|
4
|
+
* ZeptoMail (Zoho's transactional service) over its REST API — one `POST
|
|
5
|
+
* /email` with the Send Mail token in `Authorization: Zoho-enczapikey <token>`.
|
|
6
|
+
* No SDK, for the same reason as `brevo`: the call is a dozen lines of `fetch`.
|
|
7
|
+
*
|
|
8
|
+
* The token is per Mail Agent and lives in a data centre: a `.eu`, `.in` or
|
|
9
|
+
* `.com.au` account must point `baseUrl` at its own host
|
|
10
|
+
* (`https://api.zeptomail.eu/v1.1`), or every send answers 401.
|
|
11
|
+
*
|
|
12
|
+
* The `from` domain has to be verified in ZeptoMail (SPF + DKIM) before it
|
|
13
|
+
* sends; until then the API answers 4xx and this adapter raises it.
|
|
14
|
+
* Attachments travel base64-encoded inside the JSON. `tags` have no field
|
|
15
|
+
* here, so they go out as `X-Tag-<name>` headers, as in the SMTP adapter.
|
|
16
|
+
*/
|
|
17
|
+
export declare class ZeptoMailEmail implements EmailPort {
|
|
18
|
+
private readonly options;
|
|
19
|
+
private readonly defaults;
|
|
20
|
+
private readonly baseUrl;
|
|
21
|
+
private readonly fetchImpl;
|
|
22
|
+
constructor(options: ZeptoMailEmailOptions, defaults?: {
|
|
23
|
+
from?: string;
|
|
24
|
+
replyTo?: string;
|
|
25
|
+
});
|
|
26
|
+
send(input: EmailMessage): Promise<SentEmail>;
|
|
27
|
+
}
|
|
@@ -8,7 +8,8 @@ import { type EmailPort } from './email.port.js';
|
|
|
8
8
|
*
|
|
9
9
|
* Recognised vars: `EMAIL_PROVIDER`, `EMAIL_FROM`, `EMAIL_REPLY_TO`; resend
|
|
10
10
|
* `RESEND_API_KEY`; smtp `SMTP_HOST`, `SMTP_PORT`, `SMTP_SECURE`, `SMTP_USER`,
|
|
11
|
-
* `SMTP_PASSWORD`; brevo `BREVO_API_KEY`, `BREVO_BASE_URL
|
|
11
|
+
* `SMTP_PASSWORD`; brevo `BREVO_API_KEY`, `BREVO_BASE_URL`; zeptomail `ZEPTOMAIL_API_KEY`,
|
|
12
|
+
* `ZEPTOMAIL_BASE_URL`.
|
|
12
13
|
*/
|
|
13
14
|
export declare function resolveEmailOptions(options?: EmailOptions): EmailOptions;
|
|
14
15
|
/** Constructs the adapter the options select, failing loudly on missing config. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** DI token carrying the resolved {@link EmailOptions}. */
|
|
2
2
|
export declare const EMAIL_OPTIONS: unique symbol;
|
|
3
3
|
/** Which adapter backs the {@link EmailPort}. */
|
|
4
|
-
export type EmailProvider = 'resend' | 'smtp' | 'brevo' | 'memory';
|
|
4
|
+
export type EmailProvider = 'resend' | 'smtp' | 'brevo' | 'zeptomail' | 'memory';
|
|
5
5
|
export interface ResendEmailOptions {
|
|
6
6
|
apiKey: string;
|
|
7
7
|
}
|
|
@@ -26,6 +26,14 @@ export interface BrevoEmailOptions {
|
|
|
26
26
|
/** For tests. Defaults to the global `fetch`. */
|
|
27
27
|
fetchImpl?: typeof fetch;
|
|
28
28
|
}
|
|
29
|
+
export interface ZeptoMailEmailOptions {
|
|
30
|
+
/** The Mail Agent's Send Mail token (the value after `Zoho-enczapikey`). */
|
|
31
|
+
apiKey: string;
|
|
32
|
+
/** Defaults to `https://api.zeptomail.com/v1.1`; other data centres use `.eu`, `.in`, `.com.au`… */
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
/** For tests. Defaults to the global `fetch`. */
|
|
35
|
+
fetchImpl?: typeof fetch;
|
|
36
|
+
}
|
|
29
37
|
export interface EmailOptions {
|
|
30
38
|
/** Read from `EMAIL_PROVIDER` when omitted. There is no default: a misconfigured app must not send nowhere in silence. */
|
|
31
39
|
provider?: EmailProvider;
|
|
@@ -36,4 +44,5 @@ export interface EmailOptions {
|
|
|
36
44
|
resend?: ResendEmailOptions;
|
|
37
45
|
smtp?: SmtpEmailOptions;
|
|
38
46
|
brevo?: BrevoEmailOptions;
|
|
47
|
+
zeptomail?: ZeptoMailEmailOptions;
|
|
39
48
|
}
|
package/dist/email/index.cjs
CHANGED
|
@@ -28,19 +28,19 @@ var EMAIL_OPTIONS = /* @__PURE__ */ Symbol("EMAIL_OPTIONS");
|
|
|
28
28
|
|
|
29
29
|
// src/email/address.ts
|
|
30
30
|
var NAMED = /^\s*(?:"?([^"]*)"?\s*)?<\s*([^<>\s]+)\s*>\s*$/;
|
|
31
|
-
function parseAddress(
|
|
32
|
-
if (typeof
|
|
33
|
-
return
|
|
31
|
+
function parseAddress(address2) {
|
|
32
|
+
if (typeof address2 !== "string") {
|
|
33
|
+
return address2.name ? { email: address2.email.trim(), name: address2.name } : { email: address2.email.trim() };
|
|
34
34
|
}
|
|
35
|
-
const match = NAMED.exec(
|
|
35
|
+
const match = NAMED.exec(address2);
|
|
36
36
|
if (match) {
|
|
37
37
|
const name = _optionalChain([match, 'access', _ => _[1], 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]);
|
|
38
38
|
return name ? { email: match[2], name } : { email: match[2] };
|
|
39
39
|
}
|
|
40
|
-
return { email:
|
|
40
|
+
return { email: address2.trim() };
|
|
41
41
|
}
|
|
42
|
-
function formatAddress(
|
|
43
|
-
const { email, name } = parseAddress(
|
|
42
|
+
function formatAddress(address2) {
|
|
43
|
+
const { email, name } = parseAddress(address2);
|
|
44
44
|
if (!name) return email;
|
|
45
45
|
const safe = /[(),:;<>@[\]"]/.test(name) ? `"${name.replace(/"/g, '\\"')}"` : name;
|
|
46
46
|
return `${safe} <${email}>`;
|
|
@@ -239,6 +239,81 @@ var SmtpEmail = class {
|
|
|
239
239
|
}
|
|
240
240
|
};
|
|
241
241
|
|
|
242
|
+
// src/email/adapters/zeptomail.email.ts
|
|
243
|
+
var PROVIDER4 = "zeptomail";
|
|
244
|
+
var DEFAULT_BASE_URL2 = "https://api.zeptomail.com/v1.1";
|
|
245
|
+
var address = (value) => {
|
|
246
|
+
const { email, name } = parseAddress(value);
|
|
247
|
+
return name ? { address: email, name } : { address: email };
|
|
248
|
+
};
|
|
249
|
+
var recipient = (value) => ({ email_address: address(value) });
|
|
250
|
+
var ZeptoMailEmail = class {
|
|
251
|
+
constructor(options, defaults = {}) {
|
|
252
|
+
this.options = options;
|
|
253
|
+
this.defaults = defaults;
|
|
254
|
+
if (!options.apiKey) {
|
|
255
|
+
throw new Error('EmailModule: provider "zeptomail" selected but no apiKey / ZEPTOMAIL_API_KEY set.');
|
|
256
|
+
}
|
|
257
|
+
this.baseUrl = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL2))).replace(/\/$/, "");
|
|
258
|
+
this.fetchImpl = _nullishCoalesce(options.fetchImpl, () => ( globalThis.fetch));
|
|
259
|
+
}
|
|
260
|
+
async send(input) {
|
|
261
|
+
const message = completeMessage(input, this.defaults);
|
|
262
|
+
const body = {
|
|
263
|
+
from: address(message.from),
|
|
264
|
+
to: toList(message.to).map(recipient),
|
|
265
|
+
subject: message.subject
|
|
266
|
+
};
|
|
267
|
+
const cc = toList(message.cc).map(recipient);
|
|
268
|
+
const bcc = toList(message.bcc).map(recipient);
|
|
269
|
+
if (cc.length) body.cc = cc;
|
|
270
|
+
if (bcc.length) body.bcc = bcc;
|
|
271
|
+
if (message.replyTo) body.reply_to = [address(message.replyTo)];
|
|
272
|
+
if (message.html) body.htmlbody = message.html;
|
|
273
|
+
if (message.text) body.textbody = message.text;
|
|
274
|
+
const headers = {
|
|
275
|
+
...message.headers,
|
|
276
|
+
...Object.fromEntries(Object.entries(_nullishCoalesce(message.tags, () => ( {}))).map(([k, v]) => [`X-Tag-${k}`, v]))
|
|
277
|
+
};
|
|
278
|
+
if (Object.keys(headers).length) body.mime_headers = headers;
|
|
279
|
+
if (_optionalChain([message, 'access', _15 => _15.attachments, 'optionalAccess', _16 => _16.length])) {
|
|
280
|
+
body.attachments = message.attachments.map((a) => ({
|
|
281
|
+
name: a.filename,
|
|
282
|
+
content: attachmentBuffer(a.content).toString("base64"),
|
|
283
|
+
mime_type: _nullishCoalesce(a.contentType, () => ( "application/octet-stream"))
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
let response;
|
|
287
|
+
try {
|
|
288
|
+
response = await this.fetchImpl(`${this.baseUrl}/email`, {
|
|
289
|
+
method: "POST",
|
|
290
|
+
headers: {
|
|
291
|
+
authorization: `Zoho-enczapikey ${this.options.apiKey}`,
|
|
292
|
+
"content-type": "application/json",
|
|
293
|
+
accept: "application/json"
|
|
294
|
+
},
|
|
295
|
+
body: JSON.stringify(body)
|
|
296
|
+
});
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
throw new EmailProviderException(
|
|
299
|
+
PROVIDER4,
|
|
300
|
+
0,
|
|
301
|
+
{ error: cause instanceof Error ? cause.message : String(cause) },
|
|
302
|
+
`${PROVIDER4} is unreachable`
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const text = await response.text();
|
|
306
|
+
let parsed = text;
|
|
307
|
+
try {
|
|
308
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
309
|
+
} catch (e2) {
|
|
310
|
+
}
|
|
311
|
+
if (!response.ok) throw new EmailProviderException(PROVIDER4, response.status, parsed);
|
|
312
|
+
const id = _nullishCoalesce(_optionalChain([parsed, 'optionalAccess', _17 => _17.request_id]), () => ( null));
|
|
313
|
+
return { id, provider: PROVIDER4 };
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
242
317
|
// src/email/email.module.ts
|
|
243
318
|
var env = (k) => process.env[k] || void 0;
|
|
244
319
|
function resolveEmailOptions(options = {}) {
|
|
@@ -254,7 +329,8 @@ function resolveEmailOptions(options = {}) {
|
|
|
254
329
|
user: env("SMTP_USER"),
|
|
255
330
|
password: env("SMTP_PASSWORD")
|
|
256
331
|
} : void 0))),
|
|
257
|
-
brevo: _nullishCoalesce(options.brevo, () => ( (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0)))
|
|
332
|
+
brevo: _nullishCoalesce(options.brevo, () => ( (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0))),
|
|
333
|
+
zeptomail: _nullishCoalesce(options.zeptomail, () => ( (env("ZEPTOMAIL_API_KEY") ? { apiKey: env("ZEPTOMAIL_API_KEY"), baseUrl: env("ZEPTOMAIL_BASE_URL") } : void 0)))
|
|
258
334
|
};
|
|
259
335
|
}
|
|
260
336
|
function createEmailAdapter(options = {}) {
|
|
@@ -270,10 +346,13 @@ function createEmailAdapter(options = {}) {
|
|
|
270
346
|
case "brevo":
|
|
271
347
|
if (!resolved.brevo) throw new Error('EmailModule: provider "brevo" selected but no brevo options / BREVO_API_KEY set.');
|
|
272
348
|
return new BrevoEmail(resolved.brevo, defaults);
|
|
349
|
+
case "zeptomail":
|
|
350
|
+
if (!resolved.zeptomail) throw new Error('EmailModule: provider "zeptomail" selected but no zeptomail options / ZEPTOMAIL_API_KEY set.');
|
|
351
|
+
return new ZeptoMailEmail(resolved.zeptomail, defaults);
|
|
273
352
|
case "memory":
|
|
274
353
|
return new MemoryEmail(defaults);
|
|
275
354
|
case void 0:
|
|
276
|
-
throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | memory).");
|
|
355
|
+
throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | zeptomail | memory).");
|
|
277
356
|
default:
|
|
278
357
|
throw new Error(`EmailModule: unknown provider "${String(resolved.provider)}".`);
|
|
279
358
|
}
|
|
@@ -311,4 +390,5 @@ EmailModule = exports.EmailModule = _chunk2REOCMUDcjs.__decorateClass.call(void
|
|
|
311
390
|
|
|
312
391
|
|
|
313
392
|
|
|
314
|
-
|
|
393
|
+
|
|
394
|
+
exports.BrevoEmail = BrevoEmail; exports.EMAIL = EMAIL; exports.EMAIL_OPTIONS = EMAIL_OPTIONS; exports.EmailModule = EmailModule; exports.EmailProviderException = EmailProviderException; exports.MemoryEmail = MemoryEmail; exports.ResendEmail = ResendEmail; exports.SmtpEmail = SmtpEmail; exports.ZeptoMailEmail = ZeptoMailEmail; exports.createEmailAdapter = createEmailAdapter; exports.formatAddress = formatAddress; exports.parseAddress = parseAddress; exports.resolveEmailOptions = resolveEmailOptions;
|
package/dist/email/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
export { EMAIL, EmailProviderException } from './email.port.js';
|
|
2
2
|
export type { EmailPort, EmailMessage, EmailAddress, EmailAttachment, SentEmail } from './email.port.js';
|
|
3
3
|
export { EMAIL_OPTIONS } from './email.options.js';
|
|
4
|
-
export type { EmailOptions, EmailProvider, ResendEmailOptions, SmtpEmailOptions, BrevoEmailOptions, } from './email.options.js';
|
|
4
|
+
export type { EmailOptions, EmailProvider, ResendEmailOptions, SmtpEmailOptions, BrevoEmailOptions, ZeptoMailEmailOptions, } from './email.options.js';
|
|
5
5
|
export { EmailModule, createEmailAdapter, resolveEmailOptions } from './email.module.js';
|
|
6
6
|
export { parseAddress, formatAddress } from './address.js';
|
|
7
7
|
export { BrevoEmail } from './adapters/brevo.email.js';
|
|
8
8
|
export { ResendEmail } from './adapters/resend.email.js';
|
|
9
9
|
export type { ResendLike } from './adapters/resend.email.js';
|
|
10
|
+
export { ZeptoMailEmail } from './adapters/zeptomail.email.js';
|
|
10
11
|
export { SmtpEmail } from './adapters/smtp.email.js';
|
|
11
12
|
export type { TransporterLike } from './adapters/smtp.email.js';
|
|
12
13
|
export { MemoryEmail } from './adapters/memory.email.js';
|
package/dist/email/index.js
CHANGED
|
@@ -28,19 +28,19 @@ import { Global, Module } from "@nestjs/common";
|
|
|
28
28
|
|
|
29
29
|
// src/email/address.ts
|
|
30
30
|
var NAMED = /^\s*(?:"?([^"]*)"?\s*)?<\s*([^<>\s]+)\s*>\s*$/;
|
|
31
|
-
function parseAddress(
|
|
32
|
-
if (typeof
|
|
33
|
-
return
|
|
31
|
+
function parseAddress(address2) {
|
|
32
|
+
if (typeof address2 !== "string") {
|
|
33
|
+
return address2.name ? { email: address2.email.trim(), name: address2.name } : { email: address2.email.trim() };
|
|
34
34
|
}
|
|
35
|
-
const match = NAMED.exec(
|
|
35
|
+
const match = NAMED.exec(address2);
|
|
36
36
|
if (match) {
|
|
37
37
|
const name = match[1]?.trim();
|
|
38
38
|
return name ? { email: match[2], name } : { email: match[2] };
|
|
39
39
|
}
|
|
40
|
-
return { email:
|
|
40
|
+
return { email: address2.trim() };
|
|
41
41
|
}
|
|
42
|
-
function formatAddress(
|
|
43
|
-
const { email, name } = parseAddress(
|
|
42
|
+
function formatAddress(address2) {
|
|
43
|
+
const { email, name } = parseAddress(address2);
|
|
44
44
|
if (!name) return email;
|
|
45
45
|
const safe = /[(),:;<>@[\]"]/.test(name) ? `"${name.replace(/"/g, '\\"')}"` : name;
|
|
46
46
|
return `${safe} <${email}>`;
|
|
@@ -239,6 +239,81 @@ var SmtpEmail = class {
|
|
|
239
239
|
}
|
|
240
240
|
};
|
|
241
241
|
|
|
242
|
+
// src/email/adapters/zeptomail.email.ts
|
|
243
|
+
var PROVIDER4 = "zeptomail";
|
|
244
|
+
var DEFAULT_BASE_URL2 = "https://api.zeptomail.com/v1.1";
|
|
245
|
+
var address = (value) => {
|
|
246
|
+
const { email, name } = parseAddress(value);
|
|
247
|
+
return name ? { address: email, name } : { address: email };
|
|
248
|
+
};
|
|
249
|
+
var recipient = (value) => ({ email_address: address(value) });
|
|
250
|
+
var ZeptoMailEmail = class {
|
|
251
|
+
constructor(options, defaults = {}) {
|
|
252
|
+
this.options = options;
|
|
253
|
+
this.defaults = defaults;
|
|
254
|
+
if (!options.apiKey) {
|
|
255
|
+
throw new Error('EmailModule: provider "zeptomail" selected but no apiKey / ZEPTOMAIL_API_KEY set.');
|
|
256
|
+
}
|
|
257
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/$/, "");
|
|
258
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
259
|
+
}
|
|
260
|
+
async send(input) {
|
|
261
|
+
const message = completeMessage(input, this.defaults);
|
|
262
|
+
const body = {
|
|
263
|
+
from: address(message.from),
|
|
264
|
+
to: toList(message.to).map(recipient),
|
|
265
|
+
subject: message.subject
|
|
266
|
+
};
|
|
267
|
+
const cc = toList(message.cc).map(recipient);
|
|
268
|
+
const bcc = toList(message.bcc).map(recipient);
|
|
269
|
+
if (cc.length) body.cc = cc;
|
|
270
|
+
if (bcc.length) body.bcc = bcc;
|
|
271
|
+
if (message.replyTo) body.reply_to = [address(message.replyTo)];
|
|
272
|
+
if (message.html) body.htmlbody = message.html;
|
|
273
|
+
if (message.text) body.textbody = message.text;
|
|
274
|
+
const headers = {
|
|
275
|
+
...message.headers,
|
|
276
|
+
...Object.fromEntries(Object.entries(message.tags ?? {}).map(([k, v]) => [`X-Tag-${k}`, v]))
|
|
277
|
+
};
|
|
278
|
+
if (Object.keys(headers).length) body.mime_headers = headers;
|
|
279
|
+
if (message.attachments?.length) {
|
|
280
|
+
body.attachments = message.attachments.map((a) => ({
|
|
281
|
+
name: a.filename,
|
|
282
|
+
content: attachmentBuffer(a.content).toString("base64"),
|
|
283
|
+
mime_type: a.contentType ?? "application/octet-stream"
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
let response;
|
|
287
|
+
try {
|
|
288
|
+
response = await this.fetchImpl(`${this.baseUrl}/email`, {
|
|
289
|
+
method: "POST",
|
|
290
|
+
headers: {
|
|
291
|
+
authorization: `Zoho-enczapikey ${this.options.apiKey}`,
|
|
292
|
+
"content-type": "application/json",
|
|
293
|
+
accept: "application/json"
|
|
294
|
+
},
|
|
295
|
+
body: JSON.stringify(body)
|
|
296
|
+
});
|
|
297
|
+
} catch (cause) {
|
|
298
|
+
throw new EmailProviderException(
|
|
299
|
+
PROVIDER4,
|
|
300
|
+
0,
|
|
301
|
+
{ error: cause instanceof Error ? cause.message : String(cause) },
|
|
302
|
+
`${PROVIDER4} is unreachable`
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const text = await response.text();
|
|
306
|
+
let parsed = text;
|
|
307
|
+
try {
|
|
308
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
309
|
+
} catch {
|
|
310
|
+
}
|
|
311
|
+
if (!response.ok) throw new EmailProviderException(PROVIDER4, response.status, parsed);
|
|
312
|
+
const id = parsed?.request_id ?? null;
|
|
313
|
+
return { id, provider: PROVIDER4 };
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
|
|
242
317
|
// src/email/email.module.ts
|
|
243
318
|
var env = (k) => process.env[k] || void 0;
|
|
244
319
|
function resolveEmailOptions(options = {}) {
|
|
@@ -254,7 +329,8 @@ function resolveEmailOptions(options = {}) {
|
|
|
254
329
|
user: env("SMTP_USER"),
|
|
255
330
|
password: env("SMTP_PASSWORD")
|
|
256
331
|
} : void 0),
|
|
257
|
-
brevo: options.brevo ?? (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0)
|
|
332
|
+
brevo: options.brevo ?? (env("BREVO_API_KEY") ? { apiKey: env("BREVO_API_KEY"), baseUrl: env("BREVO_BASE_URL") } : void 0),
|
|
333
|
+
zeptomail: options.zeptomail ?? (env("ZEPTOMAIL_API_KEY") ? { apiKey: env("ZEPTOMAIL_API_KEY"), baseUrl: env("ZEPTOMAIL_BASE_URL") } : void 0)
|
|
258
334
|
};
|
|
259
335
|
}
|
|
260
336
|
function createEmailAdapter(options = {}) {
|
|
@@ -270,10 +346,13 @@ function createEmailAdapter(options = {}) {
|
|
|
270
346
|
case "brevo":
|
|
271
347
|
if (!resolved.brevo) throw new Error('EmailModule: provider "brevo" selected but no brevo options / BREVO_API_KEY set.');
|
|
272
348
|
return new BrevoEmail(resolved.brevo, defaults);
|
|
349
|
+
case "zeptomail":
|
|
350
|
+
if (!resolved.zeptomail) throw new Error('EmailModule: provider "zeptomail" selected but no zeptomail options / ZEPTOMAIL_API_KEY set.');
|
|
351
|
+
return new ZeptoMailEmail(resolved.zeptomail, defaults);
|
|
273
352
|
case "memory":
|
|
274
353
|
return new MemoryEmail(defaults);
|
|
275
354
|
case void 0:
|
|
276
|
-
throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | memory).");
|
|
355
|
+
throw new Error("EmailModule: no provider selected. Pass `provider` or set EMAIL_PROVIDER (resend | smtp | brevo | zeptomail | memory).");
|
|
277
356
|
default:
|
|
278
357
|
throw new Error(`EmailModule: unknown provider "${String(resolved.provider)}".`);
|
|
279
358
|
}
|
|
@@ -307,6 +386,7 @@ export {
|
|
|
307
386
|
MemoryEmail,
|
|
308
387
|
ResendEmail,
|
|
309
388
|
SmtpEmail,
|
|
389
|
+
ZeptoMailEmail,
|
|
310
390
|
createEmailAdapter,
|
|
311
391
|
formatAddress,
|
|
312
392
|
parseAddress,
|