@adatechnology/push-provider 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
  });
@@ -212,7 +216,8 @@ function buildFcmMessage(params) {
212
216
  __name(buildFcmMessage, "buildFcmMessage");
213
217
  async function initFirebaseMessaging(config) {
214
218
  if (!config.serviceAccountJson) throw new import_notification_contracts2.ConfigMissingError("serviceAccountJson");
215
- const admin = await import("firebase-admin");
219
+ const pkg = "firebase-admin";
220
+ const admin = await import(pkg);
216
221
  const appName = config.appName ?? "adatechnology-notification-push";
217
222
  const existingApp = admin.apps.find((app2) => app2?.name === appName);
218
223
  const app = existingApp ?? admin.initializeApp({
@@ -247,20 +252,248 @@ function createFcmPushProvider(config = {}) {
247
252
  }
248
253
  __name(createFcmPushProvider, "createFcmPushProvider");
249
254
 
250
- // src/PushProviderFactory.ts
255
+ // src/WebPushProvider.ts
256
+ var import_node_crypto = __toESM(require("crypto"), 1);
251
257
  var import_notification_contracts3 = require("@adatechnology/notification-contracts");
258
+ function generateVapidKeys() {
259
+ const ecdh = import_node_crypto.default.createECDH("prime256v1");
260
+ ecdh.generateKeys();
261
+ const publicKey = ecdh.getPublicKey().toString("base64url");
262
+ const privateKey = ecdh.getPrivateKey().toString("base64url");
263
+ return {
264
+ publicKey,
265
+ privateKey
266
+ };
267
+ }
268
+ __name(generateVapidKeys, "generateVapidKeys");
269
+ function parseWebPushSubscription(params) {
270
+ if (params.subscription) return params.subscription;
271
+ try {
272
+ const parsed = JSON.parse(params.token);
273
+ if (typeof parsed?.endpoint === "string" && typeof parsed?.keys === "object" && parsed.keys !== null) {
274
+ const keys = parsed.keys;
275
+ if (typeof keys.p256dh === "string" && typeof keys.auth === "string") {
276
+ return {
277
+ endpoint: parsed.endpoint,
278
+ keys: {
279
+ p256dh: keys.p256dh,
280
+ auth: keys.auth
281
+ }
282
+ };
283
+ }
284
+ }
285
+ } catch {
286
+ if (params.token.startsWith("http://") || params.token.startsWith("https://")) {
287
+ return void 0;
288
+ }
289
+ }
290
+ return void 0;
291
+ }
292
+ __name(parseWebPushSubscription, "parseWebPushSubscription");
293
+ function buildVapidJwt(params) {
294
+ const header = {
295
+ alg: "ES256",
296
+ typ: "JWT"
297
+ };
298
+ const now = Math.floor(Date.now() / 1e3);
299
+ const exp = now + (params.expirationSeconds ?? 12 * 3600);
300
+ const payload = {
301
+ aud: params.audience,
302
+ exp,
303
+ sub: params.subject
304
+ };
305
+ const encodedHeader = Buffer.from(JSON.stringify(header)).toString("base64url");
306
+ const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");
307
+ const unsignedToken = `${encodedHeader}.${encodedPayload}`;
308
+ const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, "base64url");
309
+ const privKeyBytes = Buffer.from(params.privateKeyBase64Url, "base64url");
310
+ const keyObject = import_node_crypto.default.createPrivateKey({
311
+ key: {
312
+ kty: "EC",
313
+ crv: "P-256",
314
+ x: pubKeyBytes.subarray(1, 33).toString("base64url"),
315
+ y: pubKeyBytes.subarray(33, 65).toString("base64url"),
316
+ d: privKeyBytes.toString("base64url")
317
+ },
318
+ format: "jwk"
319
+ });
320
+ const signer = import_node_crypto.default.createSign("SHA256");
321
+ signer.update(unsignedToken);
322
+ const signature = signer.sign({
323
+ key: keyObject,
324
+ dsaEncoding: "ieee-p1363"
325
+ }).toString("base64url");
326
+ return `${unsignedToken}.${signature}`;
327
+ }
328
+ __name(buildVapidJwt, "buildVapidJwt");
329
+ function encryptPayloadRfc8291(payloadText, subscription) {
330
+ const clientPub = Buffer.from(subscription.keys.p256dh, "base64url");
331
+ const clientAuth = Buffer.from(subscription.keys.auth, "base64url");
332
+ const serverEcdh = import_node_crypto.default.createECDH("prime256v1");
333
+ serverEcdh.generateKeys();
334
+ const serverPub = serverEcdh.getPublicKey();
335
+ const sharedSecret = serverEcdh.computeSecret(clientPub);
336
+ const authInfo = Buffer.concat([
337
+ Buffer.from("WebPush: info\0"),
338
+ clientPub,
339
+ serverPub
340
+ ]);
341
+ const ikm = import_node_crypto.default.hkdfSync("sha256", sharedSecret, clientAuth, authInfo, 32);
342
+ const salt = import_node_crypto.default.randomBytes(16);
343
+ const cekInfo = Buffer.from("Content-Encoding: aes128gcm\0");
344
+ const cek = import_node_crypto.default.hkdfSync("sha256", Buffer.from(ikm), salt, cekInfo, 16);
345
+ const nonceInfo = Buffer.from("Content-Encoding: nonce\0");
346
+ const nonce = import_node_crypto.default.hkdfSync("sha256", Buffer.from(ikm), salt, nonceInfo, 12);
347
+ const cipher = import_node_crypto.default.createCipheriv("aes-128-gcm", Buffer.from(cek), Buffer.from(nonce));
348
+ const plaintext = Buffer.concat([
349
+ Buffer.from(payloadText, "utf-8"),
350
+ Buffer.from([
351
+ 2
352
+ ])
353
+ ]);
354
+ const encrypted = Buffer.concat([
355
+ cipher.update(plaintext),
356
+ cipher.final(),
357
+ cipher.getAuthTag()
358
+ ]);
359
+ const recordHeader = Buffer.concat([
360
+ salt,
361
+ Buffer.from([
362
+ 0,
363
+ 0,
364
+ 16,
365
+ 0
366
+ ]),
367
+ Buffer.from([
368
+ serverPub.length
369
+ ]),
370
+ serverPub
371
+ ]);
372
+ const fullBody = Buffer.concat([
373
+ recordHeader,
374
+ encrypted
375
+ ]);
376
+ return {
377
+ body: fullBody,
378
+ headers: {
379
+ "Content-Type": "application/octet-stream",
380
+ "Content-Encoding": "aes128gcm"
381
+ }
382
+ };
383
+ }
384
+ __name(encryptPayloadRfc8291, "encryptPayloadRfc8291");
385
+ function createWebPushProvider(config = {}) {
386
+ if (!config.vapidKeys) {
387
+ throw new import_notification_contracts3.ConfigMissingError("vapidKeys");
388
+ }
389
+ const { vapidKeys } = config;
390
+ const fetchImpl = config.fetchImpl ?? fetch;
391
+ const defaultTtl = config.defaultTtlSeconds ?? 86400;
392
+ return {
393
+ driver: import_notification_contracts3.PUSH_DRIVER.WEBPUSH,
394
+ async send(params) {
395
+ const subscription = parseWebPushSubscription(params);
396
+ if (!subscription) {
397
+ return {
398
+ outcome: "permanent",
399
+ errorCode: "webpush_subscription_invalid_or_missing_keys"
400
+ };
401
+ }
402
+ let audience;
403
+ try {
404
+ const url = new URL(subscription.endpoint);
405
+ audience = `${url.protocol}//${url.host}`;
406
+ } catch {
407
+ return {
408
+ outcome: "invalid_target",
409
+ errorCode: "invalid_endpoint_url"
410
+ };
411
+ }
412
+ const jwt = buildVapidJwt({
413
+ audience,
414
+ subject: vapidKeys.subject,
415
+ publicKeyBase64Url: vapidKeys.publicKey,
416
+ privateKeyBase64Url: vapidKeys.privateKey
417
+ });
418
+ const payload = JSON.stringify({
419
+ title: params.title,
420
+ body: params.body,
421
+ badge: params.badge,
422
+ data: params.data
423
+ });
424
+ const encrypted = encryptPayloadRfc8291(payload, subscription);
425
+ try {
426
+ const response = await fetchImpl(subscription.endpoint, {
427
+ method: "POST",
428
+ headers: {
429
+ ...encrypted.headers,
430
+ TTL: String(defaultTtl),
431
+ Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`
432
+ },
433
+ body: Buffer.from(encrypted.body)
434
+ });
435
+ if (response.status === 201 || response.status === 200 || response.status === 204) {
436
+ const location = response.headers.get("location") ?? void 0;
437
+ return {
438
+ outcome: "sent",
439
+ providerMessageId: location
440
+ };
441
+ }
442
+ if (response.status === 404 || response.status === 410) {
443
+ return {
444
+ outcome: "invalid_target",
445
+ errorCode: `webpush_${response.status}_gone`
446
+ };
447
+ }
448
+ if (response.status === 429) {
449
+ const retryHeader = response.headers.get("retry-after");
450
+ const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60;
451
+ return {
452
+ outcome: "retriable",
453
+ errorCode: "webpush_rate_limit",
454
+ retryAfterSeconds
455
+ };
456
+ }
457
+ if (response.status >= 500) {
458
+ return {
459
+ outcome: "retriable",
460
+ errorCode: `webpush_server_${response.status}`
461
+ };
462
+ }
463
+ return {
464
+ outcome: "permanent",
465
+ errorCode: `webpush_status_${response.status}`
466
+ };
467
+ } catch (err) {
468
+ return {
469
+ outcome: "retriable",
470
+ errorCode: err instanceof Error ? err.message : "webpush_network_error"
471
+ };
472
+ }
473
+ }
474
+ };
475
+ }
476
+ __name(createWebPushProvider, "createWebPushProvider");
477
+
478
+ // src/PushProviderFactory.ts
479
+ var import_notification_contracts4 = require("@adatechnology/notification-contracts");
252
480
  function createPushProvider(params) {
253
- if (params.driver === import_notification_contracts3.PUSH_DRIVER.EXPO) return createExpoPushProvider(params);
254
- if (params.driver === import_notification_contracts3.PUSH_DRIVER.FCM) return createFcmPushProvider(params);
481
+ if (params.driver === import_notification_contracts4.PUSH_DRIVER.EXPO) return createExpoPushProvider(params);
482
+ if (params.driver === import_notification_contracts4.PUSH_DRIVER.FCM) return createFcmPushProvider(params);
483
+ if (params.driver === import_notification_contracts4.PUSH_DRIVER.WEBPUSH) return createWebPushProvider(params);
255
484
  const _exhaustive = params;
256
485
  throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
257
486
  }
258
487
  __name(createPushProvider, "createPushProvider");
259
488
  // Annotate the CommonJS export names for ESM import in node:
260
489
  0 && (module.exports = {
490
+ buildVapidJwt,
261
491
  createExpoPushProvider,
262
492
  createFcmPushProvider,
263
493
  createPushProvider,
494
+ createWebPushProvider,
495
+ encryptPayloadRfc8291,
496
+ generateVapidKeys,
264
497
  isFcmError,
265
498
  sendExpoPushBatch
266
499
  });
@@ -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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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 // Importacao dinamica indireta para que bundlers (Bun, esbuild) nao falhem na analise\n // estatica quando firebase-admin nao estiver instalado (ja que e dependencia opcional).\n const pkg = 'firebase-admin'\n const admin = (await import(pkg)) as typeof 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,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;I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;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","pkg","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
@@ -174,7 +174,8 @@ function buildFcmMessage(params) {
174
174
  __name(buildFcmMessage, "buildFcmMessage");
175
175
  async function initFirebaseMessaging(config) {
176
176
  if (!config.serviceAccountJson) throw new ConfigMissingError("serviceAccountJson");
177
- const admin = await import("firebase-admin");
177
+ const pkg = "firebase-admin";
178
+ const admin = await import(pkg);
178
179
  const appName = config.appName ?? "adatechnology-notification-push";
179
180
  const existingApp = admin.apps.find((app2) => app2?.name === appName);
180
181
  const app = existingApp ?? admin.initializeApp({
@@ -209,19 +210,247 @@ function createFcmPushProvider(config = {}) {
209
210
  }
210
211
  __name(createFcmPushProvider, "createFcmPushProvider");
211
212
 
213
+ // src/WebPushProvider.ts
214
+ import crypto from "crypto";
215
+ import { ConfigMissingError as ConfigMissingError2, PUSH_DRIVER as PUSH_DRIVER3 } from "@adatechnology/notification-contracts";
216
+ function generateVapidKeys() {
217
+ const ecdh = crypto.createECDH("prime256v1");
218
+ ecdh.generateKeys();
219
+ const publicKey = ecdh.getPublicKey().toString("base64url");
220
+ const privateKey = ecdh.getPrivateKey().toString("base64url");
221
+ return {
222
+ publicKey,
223
+ privateKey
224
+ };
225
+ }
226
+ __name(generateVapidKeys, "generateVapidKeys");
227
+ function parseWebPushSubscription(params) {
228
+ if (params.subscription) return params.subscription;
229
+ try {
230
+ const parsed = JSON.parse(params.token);
231
+ if (typeof parsed?.endpoint === "string" && typeof parsed?.keys === "object" && parsed.keys !== null) {
232
+ const keys = parsed.keys;
233
+ if (typeof keys.p256dh === "string" && typeof keys.auth === "string") {
234
+ return {
235
+ endpoint: parsed.endpoint,
236
+ keys: {
237
+ p256dh: keys.p256dh,
238
+ auth: keys.auth
239
+ }
240
+ };
241
+ }
242
+ }
243
+ } catch {
244
+ if (params.token.startsWith("http://") || params.token.startsWith("https://")) {
245
+ return void 0;
246
+ }
247
+ }
248
+ return void 0;
249
+ }
250
+ __name(parseWebPushSubscription, "parseWebPushSubscription");
251
+ function buildVapidJwt(params) {
252
+ const header = {
253
+ alg: "ES256",
254
+ typ: "JWT"
255
+ };
256
+ const now = Math.floor(Date.now() / 1e3);
257
+ const exp = now + (params.expirationSeconds ?? 12 * 3600);
258
+ const payload = {
259
+ aud: params.audience,
260
+ exp,
261
+ sub: params.subject
262
+ };
263
+ const encodedHeader = Buffer.from(JSON.stringify(header)).toString("base64url");
264
+ const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");
265
+ const unsignedToken = `${encodedHeader}.${encodedPayload}`;
266
+ const pubKeyBytes = Buffer.from(params.publicKeyBase64Url, "base64url");
267
+ const privKeyBytes = Buffer.from(params.privateKeyBase64Url, "base64url");
268
+ const keyObject = crypto.createPrivateKey({
269
+ key: {
270
+ kty: "EC",
271
+ crv: "P-256",
272
+ x: pubKeyBytes.subarray(1, 33).toString("base64url"),
273
+ y: pubKeyBytes.subarray(33, 65).toString("base64url"),
274
+ d: privKeyBytes.toString("base64url")
275
+ },
276
+ format: "jwk"
277
+ });
278
+ const signer = crypto.createSign("SHA256");
279
+ signer.update(unsignedToken);
280
+ const signature = signer.sign({
281
+ key: keyObject,
282
+ dsaEncoding: "ieee-p1363"
283
+ }).toString("base64url");
284
+ return `${unsignedToken}.${signature}`;
285
+ }
286
+ __name(buildVapidJwt, "buildVapidJwt");
287
+ function encryptPayloadRfc8291(payloadText, subscription) {
288
+ const clientPub = Buffer.from(subscription.keys.p256dh, "base64url");
289
+ const clientAuth = Buffer.from(subscription.keys.auth, "base64url");
290
+ const serverEcdh = crypto.createECDH("prime256v1");
291
+ serverEcdh.generateKeys();
292
+ const serverPub = serverEcdh.getPublicKey();
293
+ const sharedSecret = serverEcdh.computeSecret(clientPub);
294
+ const authInfo = Buffer.concat([
295
+ Buffer.from("WebPush: info\0"),
296
+ clientPub,
297
+ serverPub
298
+ ]);
299
+ const ikm = crypto.hkdfSync("sha256", sharedSecret, clientAuth, authInfo, 32);
300
+ const salt = crypto.randomBytes(16);
301
+ const cekInfo = Buffer.from("Content-Encoding: aes128gcm\0");
302
+ const cek = crypto.hkdfSync("sha256", Buffer.from(ikm), salt, cekInfo, 16);
303
+ const nonceInfo = Buffer.from("Content-Encoding: nonce\0");
304
+ const nonce = crypto.hkdfSync("sha256", Buffer.from(ikm), salt, nonceInfo, 12);
305
+ const cipher = crypto.createCipheriv("aes-128-gcm", Buffer.from(cek), Buffer.from(nonce));
306
+ const plaintext = Buffer.concat([
307
+ Buffer.from(payloadText, "utf-8"),
308
+ Buffer.from([
309
+ 2
310
+ ])
311
+ ]);
312
+ const encrypted = Buffer.concat([
313
+ cipher.update(plaintext),
314
+ cipher.final(),
315
+ cipher.getAuthTag()
316
+ ]);
317
+ const recordHeader = Buffer.concat([
318
+ salt,
319
+ Buffer.from([
320
+ 0,
321
+ 0,
322
+ 16,
323
+ 0
324
+ ]),
325
+ Buffer.from([
326
+ serverPub.length
327
+ ]),
328
+ serverPub
329
+ ]);
330
+ const fullBody = Buffer.concat([
331
+ recordHeader,
332
+ encrypted
333
+ ]);
334
+ return {
335
+ body: fullBody,
336
+ headers: {
337
+ "Content-Type": "application/octet-stream",
338
+ "Content-Encoding": "aes128gcm"
339
+ }
340
+ };
341
+ }
342
+ __name(encryptPayloadRfc8291, "encryptPayloadRfc8291");
343
+ function createWebPushProvider(config = {}) {
344
+ if (!config.vapidKeys) {
345
+ throw new ConfigMissingError2("vapidKeys");
346
+ }
347
+ const { vapidKeys } = config;
348
+ const fetchImpl = config.fetchImpl ?? fetch;
349
+ const defaultTtl = config.defaultTtlSeconds ?? 86400;
350
+ return {
351
+ driver: PUSH_DRIVER3.WEBPUSH,
352
+ async send(params) {
353
+ const subscription = parseWebPushSubscription(params);
354
+ if (!subscription) {
355
+ return {
356
+ outcome: "permanent",
357
+ errorCode: "webpush_subscription_invalid_or_missing_keys"
358
+ };
359
+ }
360
+ let audience;
361
+ try {
362
+ const url = new URL(subscription.endpoint);
363
+ audience = `${url.protocol}//${url.host}`;
364
+ } catch {
365
+ return {
366
+ outcome: "invalid_target",
367
+ errorCode: "invalid_endpoint_url"
368
+ };
369
+ }
370
+ const jwt = buildVapidJwt({
371
+ audience,
372
+ subject: vapidKeys.subject,
373
+ publicKeyBase64Url: vapidKeys.publicKey,
374
+ privateKeyBase64Url: vapidKeys.privateKey
375
+ });
376
+ const payload = JSON.stringify({
377
+ title: params.title,
378
+ body: params.body,
379
+ badge: params.badge,
380
+ data: params.data
381
+ });
382
+ const encrypted = encryptPayloadRfc8291(payload, subscription);
383
+ try {
384
+ const response = await fetchImpl(subscription.endpoint, {
385
+ method: "POST",
386
+ headers: {
387
+ ...encrypted.headers,
388
+ TTL: String(defaultTtl),
389
+ Authorization: `vapid t=${jwt}, k=${vapidKeys.publicKey}`
390
+ },
391
+ body: Buffer.from(encrypted.body)
392
+ });
393
+ if (response.status === 201 || response.status === 200 || response.status === 204) {
394
+ const location = response.headers.get("location") ?? void 0;
395
+ return {
396
+ outcome: "sent",
397
+ providerMessageId: location
398
+ };
399
+ }
400
+ if (response.status === 404 || response.status === 410) {
401
+ return {
402
+ outcome: "invalid_target",
403
+ errorCode: `webpush_${response.status}_gone`
404
+ };
405
+ }
406
+ if (response.status === 429) {
407
+ const retryHeader = response.headers.get("retry-after");
408
+ const retryAfterSeconds = retryHeader ? parseInt(retryHeader, 10) || 60 : 60;
409
+ return {
410
+ outcome: "retriable",
411
+ errorCode: "webpush_rate_limit",
412
+ retryAfterSeconds
413
+ };
414
+ }
415
+ if (response.status >= 500) {
416
+ return {
417
+ outcome: "retriable",
418
+ errorCode: `webpush_server_${response.status}`
419
+ };
420
+ }
421
+ return {
422
+ outcome: "permanent",
423
+ errorCode: `webpush_status_${response.status}`
424
+ };
425
+ } catch (err) {
426
+ return {
427
+ outcome: "retriable",
428
+ errorCode: err instanceof Error ? err.message : "webpush_network_error"
429
+ };
430
+ }
431
+ }
432
+ };
433
+ }
434
+ __name(createWebPushProvider, "createWebPushProvider");
435
+
212
436
  // src/PushProviderFactory.ts
213
- import { PUSH_DRIVER as PUSH_DRIVER3 } from "@adatechnology/notification-contracts";
437
+ import { PUSH_DRIVER as PUSH_DRIVER4 } from "@adatechnology/notification-contracts";
214
438
  function createPushProvider(params) {
215
- if (params.driver === PUSH_DRIVER3.EXPO) return createExpoPushProvider(params);
216
- if (params.driver === PUSH_DRIVER3.FCM) return createFcmPushProvider(params);
439
+ if (params.driver === PUSH_DRIVER4.EXPO) return createExpoPushProvider(params);
440
+ if (params.driver === PUSH_DRIVER4.FCM) return createFcmPushProvider(params);
441
+ if (params.driver === PUSH_DRIVER4.WEBPUSH) return createWebPushProvider(params);
217
442
  const _exhaustive = params;
218
443
  throw new Error(`Driver de push desconhecido: ${String(_exhaustive.driver)}`);
219
444
  }
220
445
  __name(createPushProvider, "createPushProvider");
221
446
  export {
447
+ buildVapidJwt,
222
448
  createExpoPushProvider,
223
449
  createFcmPushProvider,
224
450
  createPushProvider,
451
+ createWebPushProvider,
452
+ encryptPayloadRfc8291,
453
+ generateVapidKeys,
225
454
  isFcmError,
226
455
  sendExpoPushBatch
227
456
  };
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;IA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B,SAASY,eAAAA,oBAAmB;AAUrB,SAASC,mBAAmBC,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 // Importacao dinamica indireta para que bundlers (Bun, esbuild) nao falhem na analise\n // estatica quando firebase-admin nao estiver instalado (ja que e dependencia opcional).\n const pkg = 'firebase-admin'\n const admin = (await import(pkg)) as typeof 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,MA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icket","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","pkg","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.1.3",
3
+ "version": "0.2.1",
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.3.0"
24
+ "@adatechnology/notification-contracts": "0.5.0"
25
25
  },
26
26
  "peerDependencies": {
27
27
  "firebase-admin": ">=12 <14"