@adatechnology/push-provider 0.1.3 → 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/dist/index.cjs +235 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +36 -3
- package/dist/index.d.ts +36 -3
- package/dist/index.js +231 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -31,9 +31,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
// src/index.ts
|
|
32
32
|
var index_exports = {};
|
|
33
33
|
__export(index_exports, {
|
|
34
|
+
buildVapidJwt: () => buildVapidJwt,
|
|
34
35
|
createExpoPushProvider: () => createExpoPushProvider,
|
|
35
36
|
createFcmPushProvider: () => createFcmPushProvider,
|
|
36
37
|
createPushProvider: () => createPushProvider,
|
|
38
|
+
createWebPushProvider: () => createWebPushProvider,
|
|
39
|
+
encryptPayloadRfc8291: () => encryptPayloadRfc8291,
|
|
40
|
+
generateVapidKeys: () => generateVapidKeys,
|
|
37
41
|
isFcmError: () => isFcmError,
|
|
38
42
|
sendExpoPushBatch: () => sendExpoPushBatch
|
|
39
43
|
});
|
|
@@ -247,20 +251,248 @@ function createFcmPushProvider(config = {}) {
|
|
|
247
251
|
}
|
|
248
252
|
__name(createFcmPushProvider, "createFcmPushProvider");
|
|
249
253
|
|
|
250
|
-
// src/
|
|
254
|
+
// src/WebPushProvider.ts
|
|
255
|
+
var import_node_crypto = __toESM(require("crypto"), 1);
|
|
251
256
|
var import_notification_contracts3 = require("@adatechnology/notification-contracts");
|
|
257
|
+
function generateVapidKeys() {
|
|
258
|
+
const ecdh = import_node_crypto.default.createECDH("prime256v1");
|
|
259
|
+
ecdh.generateKeys();
|
|
260
|
+
const publicKey = ecdh.getPublicKey().toString("base64url");
|
|
261
|
+
const privateKey = ecdh.getPrivateKey().toString("base64url");
|
|
262
|
+
return {
|
|
263
|
+
publicKey,
|
|
264
|
+
privateKey
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
__name(generateVapidKeys, "generateVapidKeys");
|
|
268
|
+
function parseWebPushSubscription(params) {
|
|
269
|
+
if (params.subscription) return params.subscription;
|
|
270
|
+
try {
|
|
271
|
+
const parsed = JSON.parse(params.token);
|
|
272
|
+
if (typeof parsed?.endpoint === "string" && typeof parsed?.keys === "object" && parsed.keys !== null) {
|
|
273
|
+
const keys = parsed.keys;
|
|
274
|
+
if (typeof keys.p256dh === "string" && typeof keys.auth === "string") {
|
|
275
|
+
return {
|
|
276
|
+
endpoint: parsed.endpoint,
|
|
277
|
+
keys: {
|
|
278
|
+
p256dh: keys.p256dh,
|
|
279
|
+
auth: keys.auth
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
if (params.token.startsWith("http://") || params.token.startsWith("https://")) {
|
|
286
|
+
return void 0;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return void 0;
|
|
290
|
+
}
|
|
291
|
+
__name(parseWebPushSubscription, "parseWebPushSubscription");
|
|
292
|
+
function buildVapidJwt(params) {
|
|
293
|
+
const header = {
|
|
294
|
+
alg: "ES256",
|
|
295
|
+
typ: "JWT"
|
|
296
|
+
};
|
|
297
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
298
|
+
const exp = now + (params.expirationSeconds ?? 12 * 3600);
|
|
299
|
+
const payload = {
|
|
300
|
+
aud: params.audience,
|
|
301
|
+
exp,
|
|
302
|
+
sub: params.subject
|
|
303
|
+
};
|
|
304
|
+
const encodedHeader = Buffer.from(JSON.stringify(header)).toString("base64url");
|
|
305
|
+
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
306
|
+
const unsignedToken = `${encodedHeader}.${encodedPayload}`;
|
|
307
|
+
const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, "base64url");
|
|
308
|
+
const privKeyBytes = Buffer.from(params.privateKeyBase64Url, "base64url");
|
|
309
|
+
const keyObject = import_node_crypto.default.createPrivateKey({
|
|
310
|
+
key: {
|
|
311
|
+
kty: "EC",
|
|
312
|
+
crv: "P-256",
|
|
313
|
+
x: pubKeyBytes.subarray(1, 33).toString("base64url"),
|
|
314
|
+
y: pubKeyBytes.subarray(33, 65).toString("base64url"),
|
|
315
|
+
d: privKeyBytes.toString("base64url")
|
|
316
|
+
},
|
|
317
|
+
format: "jwk"
|
|
318
|
+
});
|
|
319
|
+
const signer = import_node_crypto.default.createSign("SHA256");
|
|
320
|
+
signer.update(unsignedToken);
|
|
321
|
+
const signature = signer.sign({
|
|
322
|
+
key: keyObject,
|
|
323
|
+
dsaEncoding: "ieee-p1363"
|
|
324
|
+
}).toString("base64url");
|
|
325
|
+
return `${unsignedToken}.${signature}`;
|
|
326
|
+
}
|
|
327
|
+
__name(buildVapidJwt, "buildVapidJwt");
|
|
328
|
+
function encryptPayloadRfc8291(payloadText, subscription) {
|
|
329
|
+
const clientPub = Buffer.from(subscription.keys.p256dh, "base64url");
|
|
330
|
+
const clientAuth = Buffer.from(subscription.keys.auth, "base64url");
|
|
331
|
+
const serverEcdh = import_node_crypto.default.createECDH("prime256v1");
|
|
332
|
+
serverEcdh.generateKeys();
|
|
333
|
+
const serverPub = serverEcdh.getPublicKey();
|
|
334
|
+
const sharedSecret = serverEcdh.computeSecret(clientPub);
|
|
335
|
+
const authInfo = Buffer.concat([
|
|
336
|
+
Buffer.from("WebPush: info\0"),
|
|
337
|
+
clientPub,
|
|
338
|
+
serverPub
|
|
339
|
+
]);
|
|
340
|
+
const ikm = import_node_crypto.default.hkdfSync("sha256", sharedSecret, clientAuth, authInfo, 32);
|
|
341
|
+
const salt = import_node_crypto.default.randomBytes(16);
|
|
342
|
+
const cekInfo = Buffer.from("Content-Encoding: aes128gcm\0");
|
|
343
|
+
const cek = import_node_crypto.default.hkdfSync("sha256", Buffer.from(ikm), salt, cekInfo, 16);
|
|
344
|
+
const nonceInfo = Buffer.from("Content-Encoding: nonce\0");
|
|
345
|
+
const nonce = import_node_crypto.default.hkdfSync("sha256", Buffer.from(ikm), salt, nonceInfo, 12);
|
|
346
|
+
const cipher = import_node_crypto.default.createCipheriv("aes-128-gcm", Buffer.from(cek), Buffer.from(nonce));
|
|
347
|
+
const plaintext = Buffer.concat([
|
|
348
|
+
Buffer.from(payloadText, "utf-8"),
|
|
349
|
+
Buffer.from([
|
|
350
|
+
2
|
|
351
|
+
])
|
|
352
|
+
]);
|
|
353
|
+
const encrypted = Buffer.concat([
|
|
354
|
+
cipher.update(plaintext),
|
|
355
|
+
cipher.final(),
|
|
356
|
+
cipher.getAuthTag()
|
|
357
|
+
]);
|
|
358
|
+
const recordHeader = Buffer.concat([
|
|
359
|
+
salt,
|
|
360
|
+
Buffer.from([
|
|
361
|
+
0,
|
|
362
|
+
0,
|
|
363
|
+
16,
|
|
364
|
+
0
|
|
365
|
+
]),
|
|
366
|
+
Buffer.from([
|
|
367
|
+
serverPub.length
|
|
368
|
+
]),
|
|
369
|
+
serverPub
|
|
370
|
+
]);
|
|
371
|
+
const fullBody = Buffer.concat([
|
|
372
|
+
recordHeader,
|
|
373
|
+
encrypted
|
|
374
|
+
]);
|
|
375
|
+
return {
|
|
376
|
+
body: fullBody,
|
|
377
|
+
headers: {
|
|
378
|
+
"Content-Type": "application/octet-stream",
|
|
379
|
+
"Content-Encoding": "aes128gcm"
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
__name(encryptPayloadRfc8291, "encryptPayloadRfc8291");
|
|
384
|
+
function createWebPushProvider(config = {}) {
|
|
385
|
+
if (!config.vapidKeys) {
|
|
386
|
+
throw new import_notification_contracts3.ConfigMissingError("vapidKeys");
|
|
387
|
+
}
|
|
388
|
+
const { vapidKeys } = config;
|
|
389
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
390
|
+
const defaultTtl = config.defaultTtlSeconds ?? 86400;
|
|
391
|
+
return {
|
|
392
|
+
driver: import_notification_contracts3.PUSH_DRIVER.WEBPUSH,
|
|
393
|
+
async send(params) {
|
|
394
|
+
const subscription = parseWebPushSubscription(params);
|
|
395
|
+
if (!subscription) {
|
|
396
|
+
return {
|
|
397
|
+
outcome: "permanent",
|
|
398
|
+
errorCode: "webpush_subscription_invalid_or_missing_keys"
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
let audience;
|
|
402
|
+
try {
|
|
403
|
+
const url = new URL(subscription.endpoint);
|
|
404
|
+
audience = `${url.protocol}//${url.host}`;
|
|
405
|
+
} catch {
|
|
406
|
+
return {
|
|
407
|
+
outcome: "invalid_target",
|
|
408
|
+
errorCode: "invalid_endpoint_url"
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
const jwt = buildVapidJwt({
|
|
412
|
+
audience,
|
|
413
|
+
subject: vapidKeys.subject,
|
|
414
|
+
publicKeyBase64Url: vapidKeys.publicKey,
|
|
415
|
+
privateKeyBase64Url: vapidKeys.privateKey
|
|
416
|
+
});
|
|
417
|
+
const payload = JSON.stringify({
|
|
418
|
+
title: params.title,
|
|
419
|
+
body: params.body,
|
|
420
|
+
badge: params.badge,
|
|
421
|
+
data: params.data
|
|
422
|
+
});
|
|
423
|
+
const encrypted = encryptPayloadRfc8291(payload, subscription);
|
|
424
|
+
try {
|
|
425
|
+
const response = await fetchImpl(subscription.endpoint, {
|
|
426
|
+
method: "POST",
|
|
427
|
+
headers: {
|
|
428
|
+
...encrypted.headers,
|
|
429
|
+
TTL: String(defaultTtl),
|
|
430
|
+
Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`
|
|
431
|
+
},
|
|
432
|
+
body: Buffer.from(encrypted.body)
|
|
433
|
+
});
|
|
434
|
+
if (response.status === 201 || response.status === 200 || response.status === 204) {
|
|
435
|
+
const location = response.headers.get("location") ?? void 0;
|
|
436
|
+
return {
|
|
437
|
+
outcome: "sent",
|
|
438
|
+
providerMessageId: location
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
if (response.status === 404 || response.status === 410) {
|
|
442
|
+
return {
|
|
443
|
+
outcome: "invalid_target",
|
|
444
|
+
errorCode: `webpush_${response.status}_gone`
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
if (response.status === 429) {
|
|
448
|
+
const retryHeader = response.headers.get("retry-after");
|
|
449
|
+
const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60;
|
|
450
|
+
return {
|
|
451
|
+
outcome: "retriable",
|
|
452
|
+
errorCode: "webpush_rate_limit",
|
|
453
|
+
retryAfterSeconds
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
if (response.status >= 500) {
|
|
457
|
+
return {
|
|
458
|
+
outcome: "retriable",
|
|
459
|
+
errorCode: `webpush_server_${response.status}`
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
return {
|
|
463
|
+
outcome: "permanent",
|
|
464
|
+
errorCode: `webpush_status_${response.status}`
|
|
465
|
+
};
|
|
466
|
+
} catch (err) {
|
|
467
|
+
return {
|
|
468
|
+
outcome: "retriable",
|
|
469
|
+
errorCode: err instanceof Error ? err.message : "webpush_network_error"
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
__name(createWebPushProvider, "createWebPushProvider");
|
|
476
|
+
|
|
477
|
+
// src/PushProviderFactory.ts
|
|
478
|
+
var import_notification_contracts4 = require("@adatechnology/notification-contracts");
|
|
252
479
|
function createPushProvider(params) {
|
|
253
|
-
if (params.driver ===
|
|
254
|
-
if (params.driver ===
|
|
480
|
+
if (params.driver === import_notification_contracts4.PUSH_DRIVER.EXPO) return createExpoPushProvider(params);
|
|
481
|
+
if (params.driver === import_notification_contracts4.PUSH_DRIVER.FCM) return createFcmPushProvider(params);
|
|
482
|
+
if (params.driver === import_notification_contracts4.PUSH_DRIVER.WEBPUSH) return createWebPushProvider(params);
|
|
255
483
|
const _exhaustive = params;
|
|
256
484
|
throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
|
|
257
485
|
}
|
|
258
486
|
__name(createPushProvider, "createPushProvider");
|
|
259
487
|
// Annotate the CommonJS export names for ESM import in node:
|
|
260
488
|
0 && (module.exports = {
|
|
489
|
+
buildVapidJwt,
|
|
261
490
|
createExpoPushProvider,
|
|
262
491
|
createFcmPushProvider,
|
|
263
492
|
createPushProvider,
|
|
493
|
+
createWebPushProvider,
|
|
494
|
+
encryptPayloadRfc8291,
|
|
495
|
+
generateVapidKeys,
|
|
264
496
|
isFcmError,
|
|
265
497
|
sendExpoPushBatch
|
|
266
498
|
});
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createExpoPushProvider, sendExpoPushBatch } from './ExpoPushProvider'\nexport type { ExpoPushProviderConfig } from './ExpoPushProvider'\nexport type { ExpoPushMessage, ExpoPushTicket, ExpoPushResponse } from './expoTypes'\n\nexport { createFcmPushProvider } from './FcmPushProvider'\nexport type { FcmPushProviderConfig } from './FcmPushProvider'\nexport type { FcmMessage, FcmError, FcmMessagingClient } from './FcmMessagingClient'\nexport { isFcmError } from './FcmMessagingClient'\n\nexport { createPushProvider } from './PushProviderFactory'\nexport type { CreatePushProviderParams } from './PushProviderFactory'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;ACIA,oCAA4B;AAK5B,IAAMA,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD,MAAIA,OAAOC,WAAW,KAAM,QAAO;IAAEC,SAAS;IAAQC,mBAAmBH,OAAOI;EAAG;AAEnF,QAAMC,YAAYL,OAAOM,SAASC,SAAS;AAC3C,MAAIF,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAkBG;EAAU;AACvF,MAAIA,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAaG;EAAU;AAGlF,SAAO;IAAEH,SAAS;IAAaG;EAAU;AAC3C;AATSN;AAWT,SAASS,mBAAmBP,QAAc;AACxC,MAAIA,WAAW,OAAOA,UAAU,IAAK,QAAO;IAAEC,SAAS;IAAaG,WAAW,QAAQJ,MAAAA;EAAS;AAChG,SAAO;IAAEC,SAAS;IAAaG,WAAW,QAAQJ,MAAAA;EAAS;AAC7D;AAHSO;AAKT,eAAeC,kBACbC,UACAC,QAA8B;AAE9B,QAAMC,YAAYD,OAAOC,aAAaC;AACtC,QAAMC,UAAkC;IACtCC,QAAQ;IACR,gBAAgB;EAClB;AACA,MAAIJ,OAAOK,YAAaF,SAAQG,gBAAgB,UAAUN,OAAOK,WAAW;AAE5E,QAAME,WAAW,MAAMN,UAAUvB,eAAe;IAC9C8B,QAAQ;IACRL;IACAM,MAAMC,KAAKC,UAAUZ,QAAAA;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A;EAAG,GAAGG,OAAAA;AAEpG,SAAOD,MAAMY,UAAUP,GAAAA;AACzB;AAXeT;AAaR,SAASiB,sBAAsBhB,SAAgC,CAAC,GAAC;AACtE,MAAIiB;AAEJ,WAASC,gBAAAA;AACP,QAAIlB,OAAOmB,gBAAiB,QAAOC,QAAQC,QAAQrB,OAAOmB,eAAe;AACzEF,sBAAkBlB,sBAAsBC,MAAAA;AACxC,WAAOiB;EACT;AAJSC;AAMT,SAAO;IACLI,QAAQC,2CAAYC;IACpB,MAAMC,KAAK7C,QAAsB;AAC/B,YAAM8C,SAAS,MAAMR,cAAAA;AACrB,UAAI;AACF,cAAMS,oBAAoB,MAAMD,OAAOD,KAAK9C,gBAAgBC,MAAAA,CAAAA;AAC5D,eAAO;UAAEL,SAAS;UAAQoD;QAAkB;MAC9C,SAAStD,OAAO;AACd,eAAOD,iBAAiBC,KAAAA;MAC1B;IACF;EACF;AACF;AArBgB2C;;;AErEhB,IAAAY,iCAA4B;AAUrB,SAASC,mBAAmBC,QAAgC;AACjE,MAAIA,OAAOC,WAAWC,2CAAYC,KAAM,QAAOC,uBAAuBJ,MAAAA;AACtE,MAAIA,OAAOC,WAAWC,2CAAYG,IAAK,QAAOC,sBAAsBN,MAAAA;AAEpE,QAAMO,cAAqBP;AAC3B,QAAM,IAAIQ,MAAM,gCAAgCC,OAAQF,YAAqCN,MAAM,CAAA,EAAG;AACxG;AANgBF;","names":["EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","import_notification_contracts","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","import_notification_contracts","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","_exhaustive","Error","String"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/WebPushProvider.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nexport { createExpoPushProvider, sendExpoPushBatch } from './ExpoPushProvider'\nexport type { ExpoPushProviderConfig } from './ExpoPushProvider'\nexport type { ExpoPushMessage, ExpoPushTicket, ExpoPushResponse } from './expoTypes'\n\nexport { createFcmPushProvider } from './FcmPushProvider'\nexport type { FcmPushProviderConfig } from './FcmPushProvider'\nexport type { FcmMessage, FcmError, FcmMessagingClient } from './FcmMessagingClient'\nexport { isFcmError } from './FcmMessagingClient'\n\nexport { createWebPushProvider, generateVapidKeys, buildVapidJwt, encryptPayloadRfc8291 } from './WebPushProvider'\nexport type { WebPushProviderConfig } from './WebPushProvider'\n\nexport { createPushProvider } from './PushProviderFactory'\nexport type { CreatePushProviderParams } from './PushProviderFactory'\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Driver de Web Push nativo (W3C Push API / RFC 8030, RFC 8291, RFC 8292).\n * Não depende de Firebase nem do Google Cloud: autentica via chaves VAPID próprias\n * e despacha diretamente para os endpoints dos navegadores (Mozilla, Apple, Google).\n */\n\nimport crypto from 'node:crypto'\nimport {\n ConfigMissingError,\n PUSH_DRIVER,\n type DeliveryAttemptResult,\n type PushDriverPort,\n type SendPushParams,\n type VapidKeys,\n type WebPushSubscription,\n} from '@adatechnology/notification-contracts'\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport type WebPushProviderConfig = {\n readonly vapidKeys?: VapidKeys\n readonly fetchImpl?: FetchLike\n readonly defaultTtlSeconds?: number\n}\n\nexport function generateVapidKeys(): { publicKey: string; privateKey: string } {\n const ecdh = crypto.createECDH('prime256v1')\n ecdh.generateKeys()\n const publicKey = ecdh.getPublicKey().toString('base64url')\n const privateKey = ecdh.getPrivateKey().toString('base64url')\n return { publicKey, privateKey }\n}\n\nfunction parseWebPushSubscription(params: SendPushParams): WebPushSubscription | undefined {\n if (params.subscription) return params.subscription\n try {\n const parsed = JSON.parse(params.token) as Record<string, unknown>\n if (typeof parsed?.endpoint === 'string' && typeof parsed?.keys === 'object' && parsed.keys !== null) {\n const keys = parsed.keys as Record<string, unknown>\n if (typeof keys.p256dh === 'string' && typeof keys.auth === 'string') {\n return {\n endpoint: parsed.endpoint,\n keys: { p256dh: keys.p256dh, auth: keys.auth },\n }\n }\n }\n } catch {\n // Não é JSON serializado; token pode ser a URL de endpoint pura\n if (params.token.startsWith('http://') || params.token.startsWith('https://')) {\n return undefined // endpoint sem keys não pode ser criptografado\n }\n }\n return undefined\n}\n\nexport function buildVapidJwt(params: {\n audience: string\n subject: string\n privateKeyBase64Url: string\n publicKeyBase64Url: string\n expirationSeconds?: number\n}): string {\n const header = { alg: 'ES256', typ: 'JWT' }\n const now = Math.floor(Date.now() / 1000)\n const exp = now + (params.expirationSeconds ?? 12 * 3600)\n const payload = { aud: params.audience, exp, sub: params.subject }\n\n const encodedHeader = Buffer.from(JSON.stringify(header)).toString('base64url')\n const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url')\n const unsignedToken = `${encodedHeader}.${encodedPayload}`\n\n const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, 'base64url')\n const privKeyBytes = Buffer.from(params.privateKeyBase64Url, 'base64url')\n\n const keyObject = crypto.createPrivateKey({\n key: {\n kty: 'EC',\n crv: 'P-256',\n x: pubKeyBytes.subarray(1, 33).toString('base64url'),\n y: pubKeyBytes.subarray(33, 65).toString('base64url'),\n d: privKeyBytes.toString('base64url'),\n },\n format: 'jwk',\n })\n\n const signer = crypto.createSign('SHA256')\n signer.update(unsignedToken)\n const signature = signer.sign({ key: keyObject, dsaEncoding: 'ieee-p1363' }).toString('base64url')\n\n return `${unsignedToken}.${signature}`\n}\n\nexport function encryptPayloadRfc8291(\n payloadText: string,\n subscription: WebPushSubscription,\n): { body: Uint8Array; headers: Record<string, string> } {\n const clientPub = Buffer.from(subscription.keys.p256dh, 'base64url')\n const clientAuth = Buffer.from(subscription.keys.auth, 'base64url')\n\n const serverEcdh = crypto.createECDH('prime256v1')\n serverEcdh.generateKeys()\n const serverPub = serverEcdh.getPublicKey()\n\n const sharedSecret = serverEcdh.computeSecret(clientPub)\n\n const authInfo = Buffer.concat([Buffer.from('WebPush: info\\0'), clientPub, serverPub])\n const ikm = crypto.hkdfSync('sha256', sharedSecret, clientAuth, authInfo, 32)\n\n const salt = crypto.randomBytes(16)\n const cekInfo = Buffer.from('Content-Encoding: aes128gcm\\0')\n const cek = crypto.hkdfSync('sha256', Buffer.from(ikm), salt, cekInfo, 16)\n\n const nonceInfo = Buffer.from('Content-Encoding: nonce\\0')\n const nonce = crypto.hkdfSync('sha256', Buffer.from(ikm), salt, nonceInfo, 12)\n\n const cipher = crypto.createCipheriv('aes-128-gcm', Buffer.from(cek), Buffer.from(nonce))\n const plaintext = Buffer.concat([Buffer.from(payloadText, 'utf-8'), Buffer.from([2])])\n const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()])\n\n // Cabeçalho RFC 8188 (salt: 16b, rs: 4b big-endian, idlen: 1b, key: 65b)\n const recordHeader = Buffer.concat([salt, Buffer.from([0, 0, 16, 0]), Buffer.from([serverPub.length]), serverPub])\n\n const fullBody = Buffer.concat([recordHeader, encrypted])\n\n return {\n body: fullBody,\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'Content-Encoding': 'aes128gcm',\n },\n }\n}\n\nexport function createWebPushProvider(config: WebPushProviderConfig = {}): PushDriverPort {\n if (!config.vapidKeys) {\n throw new ConfigMissingError('vapidKeys')\n }\n\n const { vapidKeys } = config\n const fetchImpl = config.fetchImpl ?? fetch\n const defaultTtl = config.defaultTtlSeconds ?? 86400\n\n return {\n driver: PUSH_DRIVER.WEBPUSH,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const subscription = parseWebPushSubscription(params)\n if (!subscription) {\n return {\n outcome: 'permanent',\n errorCode: 'webpush_subscription_invalid_or_missing_keys',\n }\n }\n\n let audience: string\n try {\n const url = new URL(subscription.endpoint)\n audience = `${url.protocol}//${url.host}`\n } catch {\n return { outcome: 'invalid_target', errorCode: 'invalid_endpoint_url' }\n }\n\n const jwt = buildVapidJwt({\n audience,\n subject: vapidKeys.subject,\n publicKeyBase64Url: vapidKeys.publicKey,\n privateKeyBase64Url: vapidKeys.privateKey,\n })\n\n const payload = JSON.stringify({\n title: params.title,\n body: params.body,\n badge: params.badge,\n data: params.data,\n })\n\n const encrypted = encryptPayloadRfc8291(payload, subscription)\n\n try {\n const response = await fetchImpl(subscription.endpoint, {\n method: 'POST',\n headers: {\n ...encrypted.headers,\n TTL: String(defaultTtl),\n Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`,\n },\n body: Buffer.from(encrypted.body),\n })\n\n if (response.status === 201 || response.status === 200 || response.status === 204) {\n const location = response.headers.get('location') ?? undefined\n return { outcome: 'sent', providerMessageId: location }\n }\n\n if (response.status === 404 || response.status === 410) {\n return { outcome: 'invalid_target', errorCode: `webpush_${response.status}_gone` }\n }\n\n if (response.status === 429) {\n const retryHeader = response.headers.get('retry-after')\n const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60\n return { outcome: 'retriable', errorCode: 'webpush_rate_limit', retryAfterSeconds }\n }\n\n if (response.status >= 500) {\n return { outcome: 'retriable', errorCode: `webpush_server_${response.status}` }\n }\n\n return { outcome: 'permanent', errorCode: `webpush_status_${response.status}` }\n } catch (err) {\n return {\n outcome: 'retriable',\n errorCode: err instanceof Error ? err.message : 'webpush_network_error',\n }\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\nimport { createWebPushProvider, type WebPushProviderConfig } from './WebPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.WEBPUSH } & WebPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n if (params.driver === PUSH_DRIVER.WEBPUSH) return createWebPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;ACIA,oCAA4B;AAK5B,IAAMA,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD,MAAIA,OAAOC,WAAW,KAAM,QAAO;IAAEC,SAAS;IAAQC,mBAAmBH,OAAOI;EAAG;AAEnF,QAAMC,YAAYL,OAAO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S,SAASK,MAAM;UAAQ;QACnF;AAEA,YAAIL,SAASK,WAAW,KAAK;AAC3B,gBAAMI,cAAcT,SAASvB,QAAQ8B,IAAI,aAAA;AACzC,gBAAMG,oBAAoBD,cAAcE,SAASF,aAAa,EAAA,KAAO,KAAK;AAC1E,iBAAO;YAAEnB,SAAS;YAAaC,WAAW;YAAsBmB;UAAkB;QACpF;AAEA,YAAIV,SAASK,UAAU,KAAK;AAC1B,iBAAO;YAAEf,SAAS;YAAaC,WAAW,kBAAkBS,SAASK,MAAM;UAAG;QAChF;AAEA,eAAO;UAAEf,SAAS;UAAaC,WAAW,kBAAkBS,SAASK,MAAM;QAAG;MAChF,SAASO,KAAK;AACZ,eAAO;UACLtB,SAAS;UACTC,WAAWqB,eAAeC,QAAQD,IAAIE,UAAU;QAClD;MACF;IACF;EACF;AACF;AAnFgBpC;;;ACnIhB,IAAAqC,iCAA4B;AAYrB,SAASC,mBAAmBC,QAAgC;AACjE,MAAIA,OAAOC,WAAWC,2CAAYC,KAAM,QAAOC,uBAAuBJ,MAAAA;AACtE,MAAIA,OAAOC,WAAWC,2CAAYG,IAAK,QAAOC,sBAAsBN,MAAAA;AACpE,MAAIA,OAAOC,WAAWC,2CAAYK,QAAS,QAAOC,sBAAsBR,MAAAA;AAExE,QAAMS,cAAqBT;AAC3B,QAAM,IAAIU,MAAM,gCAAgCC,OAAQF,YAAqCR,MAAM,CAAA,EAAG;AACxG;AAPgBF;","names":["EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","import_notification_contracts","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","import_notification_contracts","generateVapidKeys","ecdh","crypto","createECDH","generateKeys","publicKey","getPublicKey","toString","privateKey","getPrivateKey","parseWebPushSubscription","params","subscription","parsed","JSON","parse","token","endpoint","keys","p256dh","auth","startsWith","undefined","buildVapidJwt","header","alg","typ","now","Math","floor","Date","exp","expirationSeconds","payload","aud","audience","sub","subject","encodedHeader","Buffer","from","stringify","encodedPayload","unsignedToken","pubKeyBytes","publicKeyBase64Url","privKeyBytes","privateKeyBase64Url","keyObject","createPrivateKey","key","kty","crv","x","subarray","y","d","format","signer","createSign","update","signature","sign","dsaEncoding","encryptPayloadRfc8291","payloadText","clientPub","clientAuth","serverEcdh","serverPub","sharedSecret","computeSecret","authInfo","concat","ikm","hkdfSync","salt","randomBytes","cekInfo","cek","nonceInfo","nonce","cipher","createCipheriv","plaintext","encrypted","final","getAuthTag","recordHeader","length","fullBody","body","headers","createWebPushProvider","config","vapidKeys","ConfigMissingError","fetchImpl","fetch","defaultTtl","defaultTtlSeconds","driver","PUSH_DRIVER","WEBPUSH","send","outcome","errorCode","url","URL","protocol","host","jwt","title","badge","data","response","method","TTL","String","Authorization","status","location","get","providerMessageId","retryHeader","retryAfterSeconds","parseInt","err","Error","message","import_notification_contracts","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","WEBPUSH","createWebPushProvider","_exhaustive","Error","String"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PushDriverPort, DeliveryAttemptResult, PUSH_DRIVER } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { PushDriverPort, DeliveryAttemptResult, VapidKeys, WebPushSubscription, PUSH_DRIVER } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -99,6 +99,37 @@ type FcmPushProviderConfig = {
|
|
|
99
99
|
};
|
|
100
100
|
declare function createFcmPushProvider(config?: FcmPushProviderConfig): PushDriverPort;
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
104
|
+
*
|
|
105
|
+
* Driver de Web Push nativo (W3C Push API / RFC 8030, RFC 8291, RFC 8292).
|
|
106
|
+
* Não depende de Firebase nem do Google Cloud: autentica via chaves VAPID próprias
|
|
107
|
+
* e despacha diretamente para os endpoints dos navegadores (Mozilla, Apple, Google).
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
111
|
+
type WebPushProviderConfig = {
|
|
112
|
+
readonly vapidKeys?: VapidKeys;
|
|
113
|
+
readonly fetchImpl?: FetchLike;
|
|
114
|
+
readonly defaultTtlSeconds?: number;
|
|
115
|
+
};
|
|
116
|
+
declare function generateVapidKeys(): {
|
|
117
|
+
publicKey: string;
|
|
118
|
+
privateKey: string;
|
|
119
|
+
};
|
|
120
|
+
declare function buildVapidJwt(params: {
|
|
121
|
+
audience: string;
|
|
122
|
+
subject: string;
|
|
123
|
+
privateKeyBase64Url: string;
|
|
124
|
+
publicKeyBase64Url: string;
|
|
125
|
+
expirationSeconds?: number;
|
|
126
|
+
}): string;
|
|
127
|
+
declare function encryptPayloadRfc8291(payloadText: string, subscription: WebPushSubscription): {
|
|
128
|
+
body: Uint8Array;
|
|
129
|
+
headers: Record<string, string>;
|
|
130
|
+
};
|
|
131
|
+
declare function createWebPushProvider(config?: WebPushProviderConfig): PushDriverPort;
|
|
132
|
+
|
|
102
133
|
/**
|
|
103
134
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
104
135
|
*/
|
|
@@ -107,7 +138,9 @@ type CreatePushProviderParams = ({
|
|
|
107
138
|
readonly driver: typeof PUSH_DRIVER.EXPO;
|
|
108
139
|
} & ExpoPushProviderConfig) | ({
|
|
109
140
|
readonly driver: typeof PUSH_DRIVER.FCM;
|
|
110
|
-
} & FcmPushProviderConfig)
|
|
141
|
+
} & FcmPushProviderConfig) | ({
|
|
142
|
+
readonly driver: typeof PUSH_DRIVER.WEBPUSH;
|
|
143
|
+
} & WebPushProviderConfig);
|
|
111
144
|
declare function createPushProvider(params: CreatePushProviderParams): PushDriverPort;
|
|
112
145
|
|
|
113
|
-
export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, createExpoPushProvider, createFcmPushProvider, createPushProvider, isFcmError, sendExpoPushBatch };
|
|
146
|
+
export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, type WebPushProviderConfig, buildVapidJwt, createExpoPushProvider, createFcmPushProvider, createPushProvider, createWebPushProvider, encryptPayloadRfc8291, generateVapidKeys, isFcmError, sendExpoPushBatch };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PushDriverPort, DeliveryAttemptResult, PUSH_DRIVER } from '@adatechnology/notification-contracts';
|
|
1
|
+
import { PushDriverPort, DeliveryAttemptResult, VapidKeys, WebPushSubscription, PUSH_DRIVER } from '@adatechnology/notification-contracts';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
@@ -99,6 +99,37 @@ type FcmPushProviderConfig = {
|
|
|
99
99
|
};
|
|
100
100
|
declare function createFcmPushProvider(config?: FcmPushProviderConfig): PushDriverPort;
|
|
101
101
|
|
|
102
|
+
/**
|
|
103
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
104
|
+
*
|
|
105
|
+
* Driver de Web Push nativo (W3C Push API / RFC 8030, RFC 8291, RFC 8292).
|
|
106
|
+
* Não depende de Firebase nem do Google Cloud: autentica via chaves VAPID próprias
|
|
107
|
+
* e despacha diretamente para os endpoints dos navegadores (Mozilla, Apple, Google).
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
111
|
+
type WebPushProviderConfig = {
|
|
112
|
+
readonly vapidKeys?: VapidKeys;
|
|
113
|
+
readonly fetchImpl?: FetchLike;
|
|
114
|
+
readonly defaultTtlSeconds?: number;
|
|
115
|
+
};
|
|
116
|
+
declare function generateVapidKeys(): {
|
|
117
|
+
publicKey: string;
|
|
118
|
+
privateKey: string;
|
|
119
|
+
};
|
|
120
|
+
declare function buildVapidJwt(params: {
|
|
121
|
+
audience: string;
|
|
122
|
+
subject: string;
|
|
123
|
+
privateKeyBase64Url: string;
|
|
124
|
+
publicKeyBase64Url: string;
|
|
125
|
+
expirationSeconds?: number;
|
|
126
|
+
}): string;
|
|
127
|
+
declare function encryptPayloadRfc8291(payloadText: string, subscription: WebPushSubscription): {
|
|
128
|
+
body: Uint8Array;
|
|
129
|
+
headers: Record<string, string>;
|
|
130
|
+
};
|
|
131
|
+
declare function createWebPushProvider(config?: WebPushProviderConfig): PushDriverPort;
|
|
132
|
+
|
|
102
133
|
/**
|
|
103
134
|
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
104
135
|
*/
|
|
@@ -107,7 +138,9 @@ type CreatePushProviderParams = ({
|
|
|
107
138
|
readonly driver: typeof PUSH_DRIVER.EXPO;
|
|
108
139
|
} & ExpoPushProviderConfig) | ({
|
|
109
140
|
readonly driver: typeof PUSH_DRIVER.FCM;
|
|
110
|
-
} & FcmPushProviderConfig)
|
|
141
|
+
} & FcmPushProviderConfig) | ({
|
|
142
|
+
readonly driver: typeof PUSH_DRIVER.WEBPUSH;
|
|
143
|
+
} & WebPushProviderConfig);
|
|
111
144
|
declare function createPushProvider(params: CreatePushProviderParams): PushDriverPort;
|
|
112
145
|
|
|
113
|
-
export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, createExpoPushProvider, createFcmPushProvider, createPushProvider, isFcmError, sendExpoPushBatch };
|
|
146
|
+
export { type CreatePushProviderParams, type ExpoPushMessage, type ExpoPushProviderConfig, type ExpoPushResponse, type ExpoPushTicket, type FcmError, type FcmMessage, type FcmMessagingClient, type FcmPushProviderConfig, type WebPushProviderConfig, buildVapidJwt, createExpoPushProvider, createFcmPushProvider, createPushProvider, createWebPushProvider, encryptPayloadRfc8291, generateVapidKeys, isFcmError, sendExpoPushBatch };
|
package/dist/index.js
CHANGED
|
@@ -209,19 +209,247 @@ function createFcmPushProvider(config = {}) {
|
|
|
209
209
|
}
|
|
210
210
|
__name(createFcmPushProvider, "createFcmPushProvider");
|
|
211
211
|
|
|
212
|
+
// src/WebPushProvider.ts
|
|
213
|
+
import crypto from "crypto";
|
|
214
|
+
import { ConfigMissingError as ConfigMissingError2, PUSH_DRIVER as PUSH_DRIVER3 } from "@adatechnology/notification-contracts";
|
|
215
|
+
function generateVapidKeys() {
|
|
216
|
+
const ecdh = crypto.createECDH("prime256v1");
|
|
217
|
+
ecdh.generateKeys();
|
|
218
|
+
const publicKey = ecdh.getPublicKey().toString("base64url");
|
|
219
|
+
const privateKey = ecdh.getPrivateKey().toString("base64url");
|
|
220
|
+
return {
|
|
221
|
+
publicKey,
|
|
222
|
+
privateKey
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
__name(generateVapidKeys, "generateVapidKeys");
|
|
226
|
+
function parseWebPushSubscription(params) {
|
|
227
|
+
if (params.subscription) return params.subscription;
|
|
228
|
+
try {
|
|
229
|
+
const parsed = JSON.parse(params.token);
|
|
230
|
+
if (typeof parsed?.endpoint === "string" && typeof parsed?.keys === "object" && parsed.keys !== null) {
|
|
231
|
+
const keys = parsed.keys;
|
|
232
|
+
if (typeof keys.p256dh === "string" && typeof keys.auth === "string") {
|
|
233
|
+
return {
|
|
234
|
+
endpoint: parsed.endpoint,
|
|
235
|
+
keys: {
|
|
236
|
+
p256dh: keys.p256dh,
|
|
237
|
+
auth: keys.auth
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
} catch {
|
|
243
|
+
if (params.token.startsWith("http://") || params.token.startsWith("https://")) {
|
|
244
|
+
return void 0;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return void 0;
|
|
248
|
+
}
|
|
249
|
+
__name(parseWebPushSubscription, "parseWebPushSubscription");
|
|
250
|
+
function buildVapidJwt(params) {
|
|
251
|
+
const header = {
|
|
252
|
+
alg: "ES256",
|
|
253
|
+
typ: "JWT"
|
|
254
|
+
};
|
|
255
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
256
|
+
const exp = now + (params.expirationSeconds ?? 12 * 3600);
|
|
257
|
+
const payload = {
|
|
258
|
+
aud: params.audience,
|
|
259
|
+
exp,
|
|
260
|
+
sub: params.subject
|
|
261
|
+
};
|
|
262
|
+
const encodedHeader = Buffer.from(JSON.stringify(header)).toString("base64url");
|
|
263
|
+
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
264
|
+
const unsignedToken = `${encodedHeader}.${encodedPayload}`;
|
|
265
|
+
const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, "base64url");
|
|
266
|
+
const privKeyBytes = Buffer.from(params.privateKeyBase64Url, "base64url");
|
|
267
|
+
const keyObject = crypto.createPrivateKey({
|
|
268
|
+
key: {
|
|
269
|
+
kty: "EC",
|
|
270
|
+
crv: "P-256",
|
|
271
|
+
x: pubKeyBytes.subarray(1, 33).toString("base64url"),
|
|
272
|
+
y: pubKeyBytes.subarray(33, 65).toString("base64url"),
|
|
273
|
+
d: privKeyBytes.toString("base64url")
|
|
274
|
+
},
|
|
275
|
+
format: "jwk"
|
|
276
|
+
});
|
|
277
|
+
const signer = crypto.createSign("SHA256");
|
|
278
|
+
signer.update(unsignedToken);
|
|
279
|
+
const signature = signer.sign({
|
|
280
|
+
key: keyObject,
|
|
281
|
+
dsaEncoding: "ieee-p1363"
|
|
282
|
+
}).toString("base64url");
|
|
283
|
+
return `${unsignedToken}.${signature}`;
|
|
284
|
+
}
|
|
285
|
+
__name(buildVapidJwt, "buildVapidJwt");
|
|
286
|
+
function encryptPayloadRfc8291(payloadText, subscription) {
|
|
287
|
+
const clientPub = Buffer.from(subscription.keys.p256dh, "base64url");
|
|
288
|
+
const clientAuth = Buffer.from(subscription.keys.auth, "base64url");
|
|
289
|
+
const serverEcdh = crypto.createECDH("prime256v1");
|
|
290
|
+
serverEcdh.generateKeys();
|
|
291
|
+
const serverPub = serverEcdh.getPublicKey();
|
|
292
|
+
const sharedSecret = serverEcdh.computeSecret(clientPub);
|
|
293
|
+
const authInfo = Buffer.concat([
|
|
294
|
+
Buffer.from("WebPush: info\0"),
|
|
295
|
+
clientPub,
|
|
296
|
+
serverPub
|
|
297
|
+
]);
|
|
298
|
+
const ikm = crypto.hkdfSync("sha256", sharedSecret, clientAuth, authInfo, 32);
|
|
299
|
+
const salt = crypto.randomBytes(16);
|
|
300
|
+
const cekInfo = Buffer.from("Content-Encoding: aes128gcm\0");
|
|
301
|
+
const cek = crypto.hkdfSync("sha256", Buffer.from(ikm), salt, cekInfo, 16);
|
|
302
|
+
const nonceInfo = Buffer.from("Content-Encoding: nonce\0");
|
|
303
|
+
const nonce = crypto.hkdfSync("sha256", Buffer.from(ikm), salt, nonceInfo, 12);
|
|
304
|
+
const cipher = crypto.createCipheriv("aes-128-gcm", Buffer.from(cek), Buffer.from(nonce));
|
|
305
|
+
const plaintext = Buffer.concat([
|
|
306
|
+
Buffer.from(payloadText, "utf-8"),
|
|
307
|
+
Buffer.from([
|
|
308
|
+
2
|
|
309
|
+
])
|
|
310
|
+
]);
|
|
311
|
+
const encrypted = Buffer.concat([
|
|
312
|
+
cipher.update(plaintext),
|
|
313
|
+
cipher.final(),
|
|
314
|
+
cipher.getAuthTag()
|
|
315
|
+
]);
|
|
316
|
+
const recordHeader = Buffer.concat([
|
|
317
|
+
salt,
|
|
318
|
+
Buffer.from([
|
|
319
|
+
0,
|
|
320
|
+
0,
|
|
321
|
+
16,
|
|
322
|
+
0
|
|
323
|
+
]),
|
|
324
|
+
Buffer.from([
|
|
325
|
+
serverPub.length
|
|
326
|
+
]),
|
|
327
|
+
serverPub
|
|
328
|
+
]);
|
|
329
|
+
const fullBody = Buffer.concat([
|
|
330
|
+
recordHeader,
|
|
331
|
+
encrypted
|
|
332
|
+
]);
|
|
333
|
+
return {
|
|
334
|
+
body: fullBody,
|
|
335
|
+
headers: {
|
|
336
|
+
"Content-Type": "application/octet-stream",
|
|
337
|
+
"Content-Encoding": "aes128gcm"
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
__name(encryptPayloadRfc8291, "encryptPayloadRfc8291");
|
|
342
|
+
function createWebPushProvider(config = {}) {
|
|
343
|
+
if (!config.vapidKeys) {
|
|
344
|
+
throw new ConfigMissingError2("vapidKeys");
|
|
345
|
+
}
|
|
346
|
+
const { vapidKeys } = config;
|
|
347
|
+
const fetchImpl = config.fetchImpl ?? fetch;
|
|
348
|
+
const defaultTtl = config.defaultTtlSeconds ?? 86400;
|
|
349
|
+
return {
|
|
350
|
+
driver: PUSH_DRIVER3.WEBPUSH,
|
|
351
|
+
async send(params) {
|
|
352
|
+
const subscription = parseWebPushSubscription(params);
|
|
353
|
+
if (!subscription) {
|
|
354
|
+
return {
|
|
355
|
+
outcome: "permanent",
|
|
356
|
+
errorCode: "webpush_subscription_invalid_or_missing_keys"
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
let audience;
|
|
360
|
+
try {
|
|
361
|
+
const url = new URL(subscription.endpoint);
|
|
362
|
+
audience = `${url.protocol}//${url.host}`;
|
|
363
|
+
} catch {
|
|
364
|
+
return {
|
|
365
|
+
outcome: "invalid_target",
|
|
366
|
+
errorCode: "invalid_endpoint_url"
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
const jwt = buildVapidJwt({
|
|
370
|
+
audience,
|
|
371
|
+
subject: vapidKeys.subject,
|
|
372
|
+
publicKeyBase64Url: vapidKeys.publicKey,
|
|
373
|
+
privateKeyBase64Url: vapidKeys.privateKey
|
|
374
|
+
});
|
|
375
|
+
const payload = JSON.stringify({
|
|
376
|
+
title: params.title,
|
|
377
|
+
body: params.body,
|
|
378
|
+
badge: params.badge,
|
|
379
|
+
data: params.data
|
|
380
|
+
});
|
|
381
|
+
const encrypted = encryptPayloadRfc8291(payload, subscription);
|
|
382
|
+
try {
|
|
383
|
+
const response = await fetchImpl(subscription.endpoint, {
|
|
384
|
+
method: "POST",
|
|
385
|
+
headers: {
|
|
386
|
+
...encrypted.headers,
|
|
387
|
+
TTL: String(defaultTtl),
|
|
388
|
+
Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`
|
|
389
|
+
},
|
|
390
|
+
body: Buffer.from(encrypted.body)
|
|
391
|
+
});
|
|
392
|
+
if (response.status === 201 || response.status === 200 || response.status === 204) {
|
|
393
|
+
const location = response.headers.get("location") ?? void 0;
|
|
394
|
+
return {
|
|
395
|
+
outcome: "sent",
|
|
396
|
+
providerMessageId: location
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
if (response.status === 404 || response.status === 410) {
|
|
400
|
+
return {
|
|
401
|
+
outcome: "invalid_target",
|
|
402
|
+
errorCode: `webpush_${response.status}_gone`
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
if (response.status === 429) {
|
|
406
|
+
const retryHeader = response.headers.get("retry-after");
|
|
407
|
+
const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60;
|
|
408
|
+
return {
|
|
409
|
+
outcome: "retriable",
|
|
410
|
+
errorCode: "webpush_rate_limit",
|
|
411
|
+
retryAfterSeconds
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
if (response.status >= 500) {
|
|
415
|
+
return {
|
|
416
|
+
outcome: "retriable",
|
|
417
|
+
errorCode: `webpush_server_${response.status}`
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
outcome: "permanent",
|
|
422
|
+
errorCode: `webpush_status_${response.status}`
|
|
423
|
+
};
|
|
424
|
+
} catch (err) {
|
|
425
|
+
return {
|
|
426
|
+
outcome: "retriable",
|
|
427
|
+
errorCode: err instanceof Error ? err.message : "webpush_network_error"
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
__name(createWebPushProvider, "createWebPushProvider");
|
|
434
|
+
|
|
212
435
|
// src/PushProviderFactory.ts
|
|
213
|
-
import { PUSH_DRIVER as
|
|
436
|
+
import { PUSH_DRIVER as PUSH_DRIVER4 } from "@adatechnology/notification-contracts";
|
|
214
437
|
function createPushProvider(params) {
|
|
215
|
-
if (params.driver ===
|
|
216
|
-
if (params.driver ===
|
|
438
|
+
if (params.driver === PUSH_DRIVER4.EXPO) return createExpoPushProvider(params);
|
|
439
|
+
if (params.driver === PUSH_DRIVER4.FCM) return createFcmPushProvider(params);
|
|
440
|
+
if (params.driver === PUSH_DRIVER4.WEBPUSH) return createWebPushProvider(params);
|
|
217
441
|
const _exhaustive = params;
|
|
218
442
|
throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
|
|
219
443
|
}
|
|
220
444
|
__name(createPushProvider, "createPushProvider");
|
|
221
445
|
export {
|
|
446
|
+
buildVapidJwt,
|
|
222
447
|
createExpoPushProvider,
|
|
223
448
|
createFcmPushProvider,
|
|
224
449
|
createPushProvider,
|
|
450
|
+
createWebPushProvider,
|
|
451
|
+
encryptPayloadRfc8291,
|
|
452
|
+
generateVapidKeys,
|
|
225
453
|
isFcmError,
|
|
226
454
|
sendExpoPushBatch
|
|
227
455
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;AAIA,SAASA,mBAAmB;AAK5B,IAAMC,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD,MAAIA,OAAOC,WAAW,KAAM,QAAO;IAAEC,SAAS;IAAQC,mBAAmBH,OAAOI;EAAG;AAEnF,QAAMC,YAAYL,OAAOM,SAASC,SAAS;AAC3C,MAAIF,cAAc,sBAAuB,QAAO;IAAEH,SAAS;IAAkBG;EAAU;AACvF,MAAIA,c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AAmBC,QAAgC;AACjE,MAAIA,OAAOC,WAAWC,aAAYC,KAAM,QAAOC,uBAAuBJ,MAAAA;AACtE,MAAIA,OAAOC,WAAWC,aAAYG,IAAK,QAAOC,sBAAsBN,MAAAA;AAEpE,QAAMO,cAAqBP;AAC3B,QAAM,IAAIQ,MAAM,gCAAgCC,OAAQF,YAAqCN,MAAM,CAAA,EAAG;AACxG;AANgBF;","names":["PUSH_DRIVER","EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","ConfigMissingError","DEVICE_PLATFORM","PUSH_DRIVER","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","PUSH_DRIVER","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","_exhaustive","Error","String"]}
|
|
1
|
+
{"version":3,"sources":["../src/ExpoPushProvider.ts","../src/FcmPushProvider.ts","../src/FcmMessagingClient.ts","../src/WebPushProvider.ts","../src/PushProviderFactory.ts"],"sourcesContent":["/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport type { ExpoPushMessage, ExpoPushResponse, ExpoPushTicket } from './expoTypes'\n\nconst EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'\n\n// Limite documentado da API — enviar mais que isso na mesma chamada é rejeitado pela Expo.\nconst EXPO_PUSH_CHUNK_SIZE = 100\n\nexport type ExpoPushProviderConfig = {\n /** Access token de organização Expo (EAS) — opcional para apps standalone sem EAS. */\n readonly accessToken?: string\n /** Injeção para teste; produção usa o `fetch` global. */\n readonly fetchImpl?: typeof fetch\n}\n\nfunction chunkArray<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = []\n for (let offset = 0; offset < items.length; offset += size) {\n chunks.push(items.slice(offset, offset + size) as T[])\n }\n return chunks\n}\n\n// Ticket de erro documentado pela Expo — \"apaga o token\" é sempre DeviceNotRegistered.\nfunction classifyExpoTicket(ticket: ExpoPushTicket): DeliveryAttemptResult {\n if (ticket.status === 'ok') return { outcome: 'sent', providerMessageId: ticket.id }\n\n const errorCode = ticket.details?.error ?? 'unknown'\n if (errorCode === 'DeviceNotRegistered') return { outcome: 'invalid_target', errorCode }\n if (errorCode === 'MessageRateExceeded') return { outcome: 'retriable', errorCode }\n // MessageTooBig, InvalidCredentials e qualquer código novo: tratar como definitivo é mais seguro\n // que retry silencioso — o host vê o erro no primeiro delivery em vez de gastar 5 tentativas.\n return { outcome: 'permanent', errorCode }\n}\n\nfunction classifyHttpStatus(status: number): DeliveryAttemptResult {\n if (status === 429 || status >= 500) return { outcome: 'retriable', errorCode: `http_${status}` }\n return { outcome: 'permanent', errorCode: `http_${status}` }\n}\n\nasync function sendExpoPushChunk(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig,\n): Promise<DeliveryAttemptResult[]> {\n const fetchImpl = config.fetchImpl ?? fetch\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n if (config.accessToken) headers.Authorization = `Bearer ${config.accessToken}`\n\n const response = await fetchImpl(EXPO_PUSH_URL, {\n method: 'POST',\n headers,\n body: JSON.stringify(messages),\n })\n\n if (!response.ok) {\n const outcome = classifyHttpStatus(response.status)\n return messages.map(() => outcome)\n }\n\n const payload = (await response.json()) as ExpoPushResponse\n return payload.data.map(classifyExpoTicket)\n}\n\n/**\n * Envio em lote — usado internamente por `send()` (lote de 1) e exportado para o `notification-module`\n * poder despachar várias entregas na mesma janela de dispatch sem uma chamada HTTP por token.\n */\nexport async function sendExpoPushBatch(\n messages: readonly ExpoPushMessage[],\n config: ExpoPushProviderConfig = {},\n): Promise<DeliveryAttemptResult[]> {\n const chunks = chunkArray(messages, EXPO_PUSH_CHUNK_SIZE)\n const chunkResults = await Promise.all(chunks.map((chunk) => sendExpoPushChunk(chunk, config)))\n return chunkResults.flat()\n}\n\nexport function createExpoPushProvider(config: ExpoPushProviderConfig = {}): PushDriverPort {\n return {\n driver: PUSH_DRIVER.EXPO,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const message: ExpoPushMessage = {\n to: params.token,\n title: params.title,\n body: params.body,\n data: params.data,\n badge: params.badge,\n }\n\n const [result] = await sendExpoPushBatch([message], config)\n return result\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { ConfigMissingError, DEVICE_PLATFORM, PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { DeliveryAttemptResult, PushDriverPort, SendPushParams } from '@adatechnology/notification-contracts'\n\nimport { isFcmError, type FcmMessage, type FcmMessagingClient } from './FcmMessagingClient'\n\nexport type FcmPushProviderConfig = {\n /** Conteúdo do JSON de credencial de serviço (nunca um caminho de arquivo — evita I/O no boot). */\n readonly serviceAccountJson?: string\n /** Nome do app do firebase-admin; só relevante se o processo hospeda mais de um. */\n readonly appName?: string\n /** Injeção de teste — presente, o `firebase-admin` real nunca é importado. */\n readonly messagingClient?: FcmMessagingClient\n}\n\n// admin.messaging(): FirebaseMessagingError.code documentado pelo SDK.\nconst INVALID_TARGET_CODES = new Set([\n 'messaging/registration-token-not-registered',\n 'messaging/invalid-registration-token',\n])\nconst RETRIABLE_CODES = new Set([\n 'messaging/message-rate-exceeded',\n 'messaging/device-message-rate-exceeded',\n 'messaging/quota-exceeded',\n 'messaging/unavailable',\n 'messaging/internal-error',\n])\n\nfunction classifyFcmError(error: unknown): DeliveryAttemptResult {\n if (!isFcmError(error)) return { outcome: 'retriable', errorCode: 'unknown' }\n if (INVALID_TARGET_CODES.has(error.code)) return { outcome: 'invalid_target', errorCode: error.code }\n if (RETRIABLE_CODES.has(error.code)) return { outcome: 'retriable', errorCode: error.code }\n return { outcome: 'permanent', errorCode: error.code }\n}\n\n/**\n * Web push usa o mesmo `messaging().send()` do FCM — só o bloco `webpush` muda. É o que permite\n * validar o canal push inteiro pelo PWA do quickcart, sem depender de um app mobile.\n */\nfunction buildFcmMessage(params: SendPushParams): FcmMessage {\n const base = {\n token: params.token,\n notification: { title: params.title, body: params.body },\n data: params.data,\n }\n\n if (params.platform === DEVICE_PLATFORM.WEB) {\n return { ...base, webpush: { notification: { title: params.title, body: params.body } } }\n }\n if (params.platform === DEVICE_PLATFORM.IOS) {\n return { ...base, apns: { payload: { aps: { badge: params.badge } } } }\n }\n return params.badge === undefined ? base : { ...base, android: { notification: { notificationCount: params.badge } } }\n}\n\n// firebase-admin (~40 MB) só é importado quando o driver FCM é de fato usado sem cliente injetado\n// — quem só usa Expo, ou quem testa com dublê, nunca carrega o SDK.\nasync function initFirebaseMessaging(config: FcmPushProviderConfig): Promise<FcmMessagingClient> {\n if (!config.serviceAccountJson) throw new ConfigMissingError('serviceAccountJson')\n\n const admin = await import('firebase-admin')\n const appName = config.appName ?? 'adatechnology-notification-push'\n const existingApp = admin.apps.find((app) => app?.name === appName)\n const app =\n existingApp ??\n admin.initializeApp({ credential: admin.credential.cert(JSON.parse(config.serviceAccountJson)) }, appName)\n\n return admin.messaging(app)\n}\n\nexport function createFcmPushProvider(config: FcmPushProviderConfig = {}): PushDriverPort {\n let clientPromise: Promise<FcmMessagingClient> | undefined\n\n function resolveClient(): Promise<FcmMessagingClient> {\n if (config.messagingClient) return Promise.resolve(config.messagingClient)\n clientPromise ??= initFirebaseMessaging(config)\n return clientPromise\n }\n\n return {\n driver: PUSH_DRIVER.FCM,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const client = await resolveClient()\n try {\n const providerMessageId = await client.send(buildFcmMessage(params))\n return { outcome: 'sent', providerMessageId }\n } catch (error) {\n return classifyFcmError(error)\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\n/**\n * Forma mínima que o `admin.messaging()` do `firebase-admin` já satisfaz. Declarada por\n * estrutura — e não importada do pacote — para que os testes injetem um dublê sem carregar o SDK\n * real, e para o provider não amarrar a versão exata do `firebase-admin` do consumidor.\n */\nexport type FcmMessage = {\n readonly token: string\n readonly notification: { readonly title: string; readonly body: string }\n readonly data?: Readonly<Record<string, string>>\n readonly android?: { readonly notification?: { readonly notificationCount?: number } }\n readonly apns?: { readonly payload: { readonly aps: { readonly badge?: number } } }\n /** Presente só quando o token é de web push — o mesmo `send()` atende os três destinos. */\n readonly webpush?: { readonly notification?: { readonly title?: string; readonly body?: string } }\n}\n\nexport type FcmError = {\n readonly code: string\n readonly message: string\n}\n\nexport type FcmMessagingClient = {\n send(message: FcmMessage): Promise<string>\n}\n\nexport function isFcmError(error: unknown): error is FcmError {\n return typeof error === 'object' && error !== null && 'code' in error && typeof (error as FcmError).code === 'string'\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n *\n * Driver de Web Push nativo (W3C Push API / RFC 8030, RFC 8291, RFC 8292).\n * Não depende de Firebase nem do Google Cloud: autentica via chaves VAPID próprias\n * e despacha diretamente para os endpoints dos navegadores (Mozilla, Apple, Google).\n */\n\nimport crypto from 'node:crypto'\nimport {\n ConfigMissingError,\n PUSH_DRIVER,\n type DeliveryAttemptResult,\n type PushDriverPort,\n type SendPushParams,\n type VapidKeys,\n type WebPushSubscription,\n} from '@adatechnology/notification-contracts'\n\nexport type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n\nexport type WebPushProviderConfig = {\n readonly vapidKeys?: VapidKeys\n readonly fetchImpl?: FetchLike\n readonly defaultTtlSeconds?: number\n}\n\nexport function generateVapidKeys(): { publicKey: string; privateKey: string } {\n const ecdh = crypto.createECDH('prime256v1')\n ecdh.generateKeys()\n const publicKey = ecdh.getPublicKey().toString('base64url')\n const privateKey = ecdh.getPrivateKey().toString('base64url')\n return { publicKey, privateKey }\n}\n\nfunction parseWebPushSubscription(params: SendPushParams): WebPushSubscription | undefined {\n if (params.subscription) return params.subscription\n try {\n const parsed = JSON.parse(params.token) as Record<string, unknown>\n if (typeof parsed?.endpoint === 'string' && typeof parsed?.keys === 'object' && parsed.keys !== null) {\n const keys = parsed.keys as Record<string, unknown>\n if (typeof keys.p256dh === 'string' && typeof keys.auth === 'string') {\n return {\n endpoint: parsed.endpoint,\n keys: { p256dh: keys.p256dh, auth: keys.auth },\n }\n }\n }\n } catch {\n // Não é JSON serializado; token pode ser a URL de endpoint pura\n if (params.token.startsWith('http://') || params.token.startsWith('https://')) {\n return undefined // endpoint sem keys não pode ser criptografado\n }\n }\n return undefined\n}\n\nexport function buildVapidJwt(params: {\n audience: string\n subject: string\n privateKeyBase64Url: string\n publicKeyBase64Url: string\n expirationSeconds?: number\n}): string {\n const header = { alg: 'ES256', typ: 'JWT' }\n const now = Math.floor(Date.now() / 1000)\n const exp = now + (params.expirationSeconds ?? 12 * 3600)\n const payload = { aud: params.audience, exp, sub: params.subject }\n\n const encodedHeader = Buffer.from(JSON.stringify(header)).toString('base64url')\n const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64url')\n const unsignedToken = `${encodedHeader}.${encodedPayload}`\n\n const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, 'base64url')\n const privKeyBytes = Buffer.from(params.privateKeyBase64Url, 'base64url')\n\n const keyObject = crypto.createPrivateKey({\n key: {\n kty: 'EC',\n crv: 'P-256',\n x: pubKeyBytes.subarray(1, 33).toString('base64url'),\n y: pubKeyBytes.subarray(33, 65).toString('base64url'),\n d: privKeyBytes.toString('base64url'),\n },\n format: 'jwk',\n })\n\n const signer = crypto.createSign('SHA256')\n signer.update(unsignedToken)\n const signature = signer.sign({ key: keyObject, dsaEncoding: 'ieee-p1363' }).toString('base64url')\n\n return `${unsignedToken}.${signature}`\n}\n\nexport function encryptPayloadRfc8291(\n payloadText: string,\n subscription: WebPushSubscription,\n): { body: Uint8Array; headers: Record<string, string> } {\n const clientPub = Buffer.from(subscription.keys.p256dh, 'base64url')\n const clientAuth = Buffer.from(subscription.keys.auth, 'base64url')\n\n const serverEcdh = crypto.createECDH('prime256v1')\n serverEcdh.generateKeys()\n const serverPub = serverEcdh.getPublicKey()\n\n const sharedSecret = serverEcdh.computeSecret(clientPub)\n\n const authInfo = Buffer.concat([Buffer.from('WebPush: info\\0'), clientPub, serverPub])\n const ikm = crypto.hkdfSync('sha256', sharedSecret, clientAuth, authInfo, 32)\n\n const salt = crypto.randomBytes(16)\n const cekInfo = Buffer.from('Content-Encoding: aes128gcm\\0')\n const cek = crypto.hkdfSync('sha256', Buffer.from(ikm), salt, cekInfo, 16)\n\n const nonceInfo = Buffer.from('Content-Encoding: nonce\\0')\n const nonce = crypto.hkdfSync('sha256', Buffer.from(ikm), salt, nonceInfo, 12)\n\n const cipher = crypto.createCipheriv('aes-128-gcm', Buffer.from(cek), Buffer.from(nonce))\n const plaintext = Buffer.concat([Buffer.from(payloadText, 'utf-8'), Buffer.from([2])])\n const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()])\n\n // Cabeçalho RFC 8188 (salt: 16b, rs: 4b big-endian, idlen: 1b, key: 65b)\n const recordHeader = Buffer.concat([salt, Buffer.from([0, 0, 16, 0]), Buffer.from([serverPub.length]), serverPub])\n\n const fullBody = Buffer.concat([recordHeader, encrypted])\n\n return {\n body: fullBody,\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'Content-Encoding': 'aes128gcm',\n },\n }\n}\n\nexport function createWebPushProvider(config: WebPushProviderConfig = {}): PushDriverPort {\n if (!config.vapidKeys) {\n throw new ConfigMissingError('vapidKeys')\n }\n\n const { vapidKeys } = config\n const fetchImpl = config.fetchImpl ?? fetch\n const defaultTtl = config.defaultTtlSeconds ?? 86400\n\n return {\n driver: PUSH_DRIVER.WEBPUSH,\n async send(params: SendPushParams): Promise<DeliveryAttemptResult> {\n const subscription = parseWebPushSubscription(params)\n if (!subscription) {\n return {\n outcome: 'permanent',\n errorCode: 'webpush_subscription_invalid_or_missing_keys',\n }\n }\n\n let audience: string\n try {\n const url = new URL(subscription.endpoint)\n audience = `${url.protocol}//${url.host}`\n } catch {\n return { outcome: 'invalid_target', errorCode: 'invalid_endpoint_url' }\n }\n\n const jwt = buildVapidJwt({\n audience,\n subject: vapidKeys.subject,\n publicKeyBase64Url: vapidKeys.publicKey,\n privateKeyBase64Url: vapidKeys.privateKey,\n })\n\n const payload = JSON.stringify({\n title: params.title,\n body: params.body,\n badge: params.badge,\n data: params.data,\n })\n\n const encrypted = encryptPayloadRfc8291(payload, subscription)\n\n try {\n const response = await fetchImpl(subscription.endpoint, {\n method: 'POST',\n headers: {\n ...encrypted.headers,\n TTL: String(defaultTtl),\n Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`,\n },\n body: Buffer.from(encrypted.body),\n })\n\n if (response.status === 201 || response.status === 200 || response.status === 204) {\n const location = response.headers.get('location') ?? undefined\n return { outcome: 'sent', providerMessageId: location }\n }\n\n if (response.status === 404 || response.status === 410) {\n return { outcome: 'invalid_target', errorCode: `webpush_${response.status}_gone` }\n }\n\n if (response.status === 429) {\n const retryHeader = response.headers.get('retry-after')\n const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60\n return { outcome: 'retriable', errorCode: 'webpush_rate_limit', retryAfterSeconds }\n }\n\n if (response.status >= 500) {\n return { outcome: 'retriable', errorCode: `webpush_server_${response.status}` }\n }\n\n return { outcome: 'permanent', errorCode: `webpush_status_${response.status}` }\n } catch (err) {\n return {\n outcome: 'retriable',\n errorCode: err instanceof Error ? err.message : 'webpush_network_error',\n }\n }\n },\n }\n}\n","/**\n * Copyright (c) 2026 Ada Technology. MIT License.\n */\n\nimport { PUSH_DRIVER } from '@adatechnology/notification-contracts'\nimport type { PushDriverPort } from '@adatechnology/notification-contracts'\n\nimport { createExpoPushProvider, type ExpoPushProviderConfig } from './ExpoPushProvider'\nimport { createFcmPushProvider, type FcmPushProviderConfig } from './FcmPushProvider'\nimport { createWebPushProvider, type WebPushProviderConfig } from './WebPushProvider'\n\nexport type CreatePushProviderParams =\n | ({ readonly driver: typeof PUSH_DRIVER.EXPO } & ExpoPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.FCM } & FcmPushProviderConfig)\n | ({ readonly driver: typeof PUSH_DRIVER.WEBPUSH } & WebPushProviderConfig)\n\nexport function createPushProvider(params: CreatePushProviderParams): PushDriverPort {\n if (params.driver === PUSH_DRIVER.EXPO) return createExpoPushProvider(params)\n if (params.driver === PUSH_DRIVER.FCM) return createFcmPushProvider(params)\n if (params.driver === PUSH_DRIVER.WEBPUSH) return createWebPushProvider(params)\n\n const _exhaustive: never = params\n throw new Error(`Driver de push desconhecido: ${String((_exhaustive as { driver?: unknown }).driver)}`)\n}\n"],"mappings":";;;;AAIA,SAASA,mBAAmB;AAK5B,IAAMC,gBAAgB;AAGtB,IAAMC,uBAAuB;AAS7B,SAASC,WAAcC,OAAqBC,MAAY;AACtD,QAAMC,SAAgB,CAAA;AACtB,WAASC,SAAS,GAAGA,SAASH,MAAMI,QAAQD,UAAUF,MAAM;AAC1DC,WAAOG,KAAKL,MAAMM,MAAMH,QAAQA,SAASF,IAAAA,CAAAA;EAC3C;AACA,SAAOC;AACT;AANSH;AAST,SAASQ,mBAAmBC,QAAsB;AAChD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AAW,OAAOL,SAASK,WAAW,KAAK;AACtD,iBAAO;YAAEf,SAAS;YAAkBC,WAAW,WAAWS,SAASK,MAAM;UAAQ;QACnF;AAEA,YAAIL,SAASK,WAAW,KAAK;AAC3B,gBAAMI,cAAcT,SAASvB,QAAQ8B,IAAI,aAAA;AACzC,gBAAMG,oBAAoBD,cAAcE,SAASF,aAAa,EAAA,KAAO,KAAK;AAC1E,iBAAO;YAAEnB,SAAS;YAAaC,WAAW;YAAsBmB;UAAkB;QACpF;AAEA,YAAIV,SAASK,UAAU,KAAK;AAC1B,iBAAO;YAAEf,SAAS;YAAaC,WAAW,kBAAkBS,SAASK,MAAM;UAAG;QAChF;AAEA,eAAO;UAAEf,SAAS;UAAaC,WAAW,kBAAkBS,SAASK,MAAM;QAAG;MAChF,SAASO,KAAK;AACZ,eAAO;UACLtB,SAAS;UACTC,WAAWqB,eAAeC,QAAQD,IAAIE,UAAU;QAClD;MACF;IACF;EACF;AACF;AAnFgBpC;;;ACnIhB,SAASqC,eAAAA,oBAAmB;AAYrB,SAASC,mBAAmBC,QAAgC;AACjE,MAAIA,OAAOC,WAAWC,aAAYC,KAAM,QAAOC,uBAAuBJ,MAAAA;AACtE,MAAIA,OAAOC,WAAWC,aAAYG,IAAK,QAAOC,sBAAsBN,MAAAA;AACpE,MAAIA,OAAOC,WAAWC,aAAYK,QAAS,QAAOC,sBAAsBR,MAAAA;AAExE,QAAMS,cAAqBT;AAC3B,QAAM,IAAIU,MAAM,gCAAgCC,OAAQF,YAAqCR,MAAM,CAAA,EAAG;AACxG;AAPgBF;","names":["PUSH_DRIVER","EXPO_PUSH_URL","EXPO_PUSH_CHUNK_SIZE","chunkArray","items","size","chunks","offset","length","push","slice","classifyExpoTicket","ticket","status","outcome","providerMessageId","id","errorCode","details","error","classifyHttpStatus","sendExpoPushChunk","messages","config","fetchImpl","fetch","headers","Accept","accessToken","Authorization","response","method","body","JSON","stringify","ok","map","payload","json","data","sendExpoPushBatch","chunkResults","Promise","all","chunk","flat","createExpoPushProvider","driver","PUSH_DRIVER","EXPO","send","params","message","to","token","title","badge","result","ConfigMissingError","DEVICE_PLATFORM","PUSH_DRIVER","isFcmError","error","code","INVALID_TARGET_CODES","Set","RETRIABLE_CODES","classifyFcmError","error","isFcmError","outcome","errorCode","has","code","buildFcmMessage","params","base","token","notification","title","body","data","platform","DEVICE_PLATFORM","WEB","webpush","IOS","apns","payload","aps","badge","undefined","android","notificationCount","initFirebaseMessaging","config","serviceAccountJson","ConfigMissingError","admin","appName","existingApp","apps","find","app","name","initializeApp","credential","cert","JSON","parse","messaging","createFcmPushProvider","clientPromise","resolveClient","messagingClient","Promise","resolve","driver","PUSH_DRIVER","FCM","send","client","providerMessageId","crypto","ConfigMissingError","PUSH_DRIVER","generateVapidKeys","ecdh","crypto","createECDH","generateKeys","publicKey","getPublicKey","toString","privateKey","getPrivateKey","parseWebPushSubscription","params","subscription","parsed","JSON","parse","token","endpoint","keys","p256dh","auth","startsWith","undefined","buildVapidJwt","header","alg","typ","now","Math","floor","Date","exp","expirationSeconds","payload","aud","audience","sub","subject","encodedHeader","Buffer","from","stringify","encodedPayload","unsignedToken","pubKeyBytes","publicKeyBase64Url","privKeyBytes","privateKeyBase64Url","keyObject","createPrivateKey","key","kty","crv","x","subarray","y","d","format","signer","createSign","update","signature","sign","dsaEncoding","encryptPayloadRfc8291","payloadText","clientPub","clientAuth","serverEcdh","serverPub","sharedSecret","computeSecret","authInfo","concat","ikm","hkdfSync","salt","randomBytes","cekInfo","cek","nonceInfo","nonce","cipher","createCipheriv","plaintext","encrypted","final","getAuthTag","recordHeader","length","fullBody","body","headers","createWebPushProvider","config","vapidKeys","ConfigMissingError","fetchImpl","fetch","defaultTtl","defaultTtlSeconds","driver","PUSH_DRIVER","WEBPUSH","send","outcome","errorCode","url","URL","protocol","host","jwt","title","badge","data","response","method","TTL","String","Authorization","status","location","get","providerMessageId","retryHeader","retryAfterSeconds","parseInt","err","Error","message","PUSH_DRIVER","createPushProvider","params","driver","PUSH_DRIVER","EXPO","createExpoPushProvider","FCM","createFcmPushProvider","WEBPUSH","createWebPushProvider","_exhaustive","Error","String"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adatechnology/push-provider",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Stateless push notification providers (Expo, FCM) behind a single port — part of the notification trio",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@adatechnology/notification-contracts": "0.
|
|
24
|
+
"@adatechnology/notification-contracts": "0.4.0"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
27
|
"firebase-admin": ">=12 <14"
|