@stacksjs/push 0.75.124 → 0.75.127

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.
@@ -0,0 +1,23 @@
1
+ import type { PushResult } from '@stacksjs/types';
2
+ export declare function configure(options: APNSConfig): void;
3
+ export declare function resetConfiguration(): void;
4
+ export declare function buildProviderToken(teamId: string, keyId: string, privateKey: string, now?: unknown): string;
5
+ export declare function buildPayload(message: APNSMessage): string;
6
+ /** Apple device tokens come from the native bridge, independently of Firebase. */
7
+ export declare function send(to: string | string[], message: APNSMessage): Promise<PushResult>;
8
+ export declare interface APNSConfig {
9
+ teamId?: string
10
+ keyId?: string
11
+ privateKey?: string
12
+ topic?: string
13
+ sandbox?: boolean
14
+ }
15
+ export declare interface APNSMessage {
16
+ title?: string
17
+ body: string
18
+ data?: Record<string, unknown>
19
+ badge?: number
20
+ sound?: 'default' | null
21
+ priority?: 'high' | 'normal' | 'default'
22
+ collapseId?: string
23
+ }
@@ -1,3 +1,4 @@
1
1
  export * as expo from './expo';
2
2
  export * as fcm from './fcm';
3
+ export * as apns from './apns';
3
4
  export * from './web-push';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import * as apns from './drivers/apns';
1
2
  import * as expo from './drivers/expo';
2
3
  import * as fcm from './drivers/fcm';
3
4
  import type { PushResult } from '@stacksjs/types';
@@ -7,6 +8,7 @@ export type {
7
8
  WebPushResult,
8
9
  WebPushSubscription,
9
10
  } from './drivers/web-push';
11
+ export type { APNSConfig, APNSMessage } from './drivers/apns';
10
12
  /**
11
13
  * Send a push notification using the specified driver
12
14
  */
@@ -23,6 +25,7 @@ export declare function configureFCM(config: fcm.FCMConfig): void;
23
25
  * Optional: `config/services.ts` is read when nothing is configured here.
24
26
  */
25
27
  export declare function configureExpo(config: expo.ExpoConfig): void;
28
+ export declare function configureAPNS(config: apns.APNSConfig): void;
26
29
  export declare interface PushNotification {
27
30
  title?: string
28
31
  body: string
@@ -30,11 +33,12 @@ export declare interface PushNotification {
30
33
  badge?: number
31
34
  sound?: 'default' | null
32
35
  priority?: 'high' | 'normal' | 'default'
36
+ collapseId?: string
33
37
  }
34
38
  export declare interface SendOptions {
35
39
  driver?: PushDriver
36
40
  }
37
- export type PushDriver = 'expo' | 'fcm';
41
+ export type PushDriver = 'expo' | 'fcm' | 'apns';
38
42
  export * from './drivers/index';
39
43
  /*
40
44
  * Named rather than `export * from './drivers/index'`.
@@ -51,4 +55,4 @@ export {
51
55
  generateVapidKeys,
52
56
  sendWebPush,
53
57
  } from './drivers/web-push';
54
- export { expo, fcm };
58
+ export { expo, fcm, apns };
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  // @bun
2
- var re=Object.defineProperty;var se=(e)=>e;function ne(e,t){this[e]=se.bind(null,t)}var F=(e,t)=>{for(var r in t)re(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ne.bind(t,r)})};var U={};F(U,{Send:()=>v,configure:()=>E,default:()=>ce,getReceipts:()=>N,isExpoPushToken:()=>S,resetConfiguration:()=>ie,resolveAccessToken:()=>O,send:()=>v,sendBatch:()=>W});var q={};F(q,{Send:()=>h,buildServiceAccountAssertion:()=>V,clearAccessTokens:()=>pe,configure:()=>k,default:()=>de,normalizePrivateKey:()=>J,resetConfiguration:()=>ae,resolveConfig:()=>I,send:()=>h,sendMulticast:()=>T,sendToTopic:()=>L,subscribeToTopic:()=>X,unsubscribeFromTopic:()=>Y});import{log as m}from"@stacksjs/cli";async function w(){let{awaitConfig:e}=await import("@stacksjs/config");return(await e()).services??{}}function g(e){let t=e?.trim();return t?t:void 0}var oe="https://exp.host/--/api/v2/push/send",b={};function E(e){b={...b,...e}}function ie(){b={}}async function O(){if(g(b.accessToken))return g(b.accessToken);try{return g((await w()).expo?.accessToken)}catch(e){m.debug(`Expo: could not read config/services.ts: ${e instanceof Error?e.message:String(e)}`);return}}async function B(e={}){let t={Accept:"application/json","Content-Type":"application/json",...e},r=await O();if(r)t.Authorization=`Bearer ${r}`;return t}function S(e){return/^Expo(?:nent)?PushToken\[.+\]$/.test(e)||/^[a-zA-Z0-9-_]+$/.test(e)}async function v(e){let t=Array.isArray(e.to)?e.to:[e.to],r=t.filter((s)=>!S(s));if(r.length>0)m.warn(`Invalid Expo push tokens found: ${r.join(", ")}`);let n=t.filter(S);if(n.length===0)return{success:!1,provider:"expo",message:"No valid Expo push tokens provided"};try{let s=n.map((a)=>({to:a,title:e.title,body:e.body,data:e.data,sound:e.sound??"default",badge:e.badge,channelId:e.channelId,priority:e.priority??"high",ttl:e.ttl})),i=4096;for(let a of s){let f=new TextEncoder().encode(JSON.stringify(a)).length;if(f>4096)return{success:!1,provider:"expo",message:`Expo message payload (${f} bytes) exceeds 4 KiB per-message limit`}}let o=await fetch(oe,{method:"POST",headers:await B({"Accept-Encoding":"gzip, deflate"}),body:JSON.stringify(s)});if(!o.ok){let a=await o.text();return m.error(`Expo push failed: ${a}`),{success:!1,provider:"expo",message:`HTTP ${o.status}: ${a}`}}let p=(await o.json()).data,d=p.filter((a)=>a.status==="error");if(d.length>0)m.warn(`Some push notifications failed: ${JSON.stringify(d)}`);let y=p.filter((a)=>a.status==="ok").length;return m.info(`Expo push sent: ${y}/${p.length} successful`),{success:d.length===0,provider:"expo",message:`Sent ${y}/${p.length} notifications`,messageId:p.find((a)=>a.id)?.id,data:{tickets:p}}}catch(s){let i=s instanceof Error?s:Error(String(s));return m.error(`Expo push error: ${i.message}`),{success:!1,provider:"expo",message:i.message}}}async function N(e){let t=await fetch("https://exp.host/--/api/v2/push/getReceipts",{method:"POST",headers:await B(),body:JSON.stringify({ids:e})});if(!t.ok)throw Error(`Failed to get receipts: ${t.status}`);return(await t.json()).data}async function W(e,t=100){let r=[];for(let n=0;n<e.length;n+=t){let s=e.slice(n,n+t),i=await Promise.all(s.map((o)=>v(o)));r.push(...i)}return r}var ce={send:v,sendBatch:W,getReceipts:N,isExpoPushToken:S,configure:E};import{log as P}from"@stacksjs/cli";var D="https://fcm.googleapis.com/v1/projects",l={};function k(e){l={...l,...e}}function ae(){l={},C.clear()}function J(e){return e.includes("\\n")?e.replace(/\\n/g,`
3
- `):e}async function I(){if(l.projectId&&l.serviceAccount)return l;let e={};try{e=await w()}catch(s){P.debug(`FCM: could not read config/services.ts: ${s instanceof Error?s.message:String(s)}`)}let t=e.fcm??{},r=g(t.clientEmail),n=g(t.privateKey);return{projectId:l.projectId??g(t.projectId),serviceAccount:l.serviceAccount??(r&&n?{clientEmail:r,privateKey:J(n)}:void 0)}}function K(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function V(e,t,r){let n={alg:"RS256",typ:"JWT"},s={iss:e,scope:"https://www.googleapis.com/auth/firebase.messaging",aud:"https://oauth2.googleapis.com/token",iat:r,exp:r+3600},i=new TextEncoder,o=K(JSON.stringify(n)),c=K(JSON.stringify(s)),p=`${o}.${c}`,d=t.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,""),y=Uint8Array.from(atob(d),(M)=>M.charCodeAt(0)),a=await crypto.subtle.importKey("pkcs8",y,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]),f=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",a,i.encode(p)),A=K(String.fromCharCode(...new Uint8Array(f)));return`${o}.${c}.${A}`}var C=new Map,ue=60000;function pe(){C.clear()}async function H(e){if(!e.serviceAccount)throw Error("Service account not configured for FCM v1 API");let{clientEmail:t,privateKey:r}=e.serviceAccount,n=C.get(t);if(n&&n.expiresAt-ue>Date.now())return n.token;let s=await V(t,r,Math.floor(Date.now()/1000)),i=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${s}`});if(!i.ok)throw Error(`Failed to get access token: ${i.status}`);let o=await i.json(),c=Number(o.expires_in);return C.set(t,{token:o.access_token,expiresAt:Date.now()+(Number.isFinite(c)&&c>0?c:3600)*1000}),o.access_token}async function h(e){let t=await I();if(!t.serviceAccount||!t.projectId)return{success:!1,provider:"fcm",message:"FCM service account and projectId not configured - set FCM_PROJECT_ID, FCM_CLIENT_EMAIL and FCM_PRIVATE_KEY, or call configureFCM()"};try{let r=await H(t),n=`${D}/${t.projectId}/messages:send`,s={message:{notification:e.notification,data:e.data,android:{priority:e.priority??"high",ttl:e.ttl?`${e.ttl}s`:void 0,collapseKey:e.collapseKey},apns:{headers:{"apns-priority":e.priority==="high"?"10":"5"}}}};if(e.to)s.message.token=e.to;else if(e.topic)s.message.topic=e.topic;else if(e.condition)s.message.condition=e.condition;let i=await fetch(n,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){let c=await i.text();return P.error(`FCM v1 push failed: ${c}`),{success:!1,provider:"fcm",message:`HTTP ${i.status}: ${c}`}}let o=await i.json();return P.info(`FCM v1 push sent: ${o.name}`),{success:!0,provider:"fcm",message:"Notification sent successfully",messageId:o.name}}catch(r){let n=r instanceof Error?r:Error(String(r));return P.error(`FCM v1 push error: ${n.message}`),{success:!1,provider:"fcm",message:n.message}}}async function T(e,t){return Promise.all(e.map((r)=>h({...t,to:r})))}async function L(e,t){return h({...t,topic:e})}async function z(e,t,r,n){let s=await H(e),i=`${D}/${e.projectId}/registrations/${encodeURIComponent(t)}/topicSubscriptions`,o=n?`${i}?topic_name=${encodeURIComponent(r)}`:`${i}/${encodeURIComponent(r)}`,c=await fetch(o,{method:n?"POST":"DELETE",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:"{}"});if(c.ok||n&&c.status===409)return!0;return P.error(`FCM topic ${n?"subscribe":"unsubscribe"} failed for topic ${r}: HTTP ${c.status}`),!1}async function G(e){let t=await I();if(!t.serviceAccount||!t.projectId)throw Error(`FCM service account and projectId required for ${e}`);return t}async function X(e,t){let r=await G("topic subscription");return(await Promise.all(e.map((s)=>z(r,s,t,!0)))).every(Boolean)}async function Y(e,t){let r=await G("topic unsubscription");return(await Promise.all(e.map((s)=>z(r,s,t,!1)))).every(Boolean)}var de={send:h,sendMulticast:T,sendToTopic:L,subscribeToTopic:X,unsubscribeFromTopic:Y,configure:k};import{Buffer as u}from"buffer";import{createCipheriv as fe,createECDH as ge,createHmac as Z,createPrivateKey as le,createSign as ye,generateKeyPairSync as me,randomBytes as he}from"crypto";var Q="prime256v1";function x(e){return e.toString("base64url")}function R(e){return u.from(e,"base64url")}function xe(){let{publicKey:e,privateKey:t}=me("ec",{namedCurve:Q}),r=e.export({type:"spki",format:"der"}),n=t.export({format:"jwk"});return{publicKey:x(r.subarray(r.length-65)),privateKey:String(n.d)}}function be(e){let t=new URL(e);return`${t.protocol}//${t.host}`}function ee(e){let r=Math.floor(e.nowSeconds??Date.now()/1000)+Math.min(e.expiresInSeconds??43200,86400),n=x(u.from(JSON.stringify({typ:"JWT",alg:"ES256"}))),s=x(u.from(JSON.stringify({aud:be(e.endpoint),exp:r,sub:e.subject}))),i=`${n}.${s}`,o=le({key:{kty:"EC",crv:"P-256",d:e.vapid.privateKey,x:x(R(e.vapid.publicKey).subarray(1,33)),y:x(R(e.vapid.publicKey).subarray(33,65))},format:"jwk"}),c=ye("SHA256");c.update(i);let p=c.sign({key:o,dsaEncoding:"ieee-p1363"});return{Authorization:`vapid t=${i}.${x(p)}, k=${e.vapid.publicKey}`,"Crypto-Key":`p256ecdsa=${e.vapid.publicKey}`}}function j(e,t,r,n){let s=Z("sha256",e).update(t).digest();return Z("sha256",s).update(u.concat([r,u.from([1])])).digest().subarray(0,n)}function te(e,t,r=he(16)){let n=R(e.keys.p256dh),s=R(e.keys.auth),i=ge(Q);i.generateKeys();let o=i.getPublicKey(),c=i.computeSecret(n),p=u.concat([u.from("WebPush: info\x00"),n,o]),d=j(s,c,p,32),y=j(r,d,u.from("Content-Encoding: aes128gcm\x00"),16),a=j(r,d,u.from("Content-Encoding: nonce\x00"),12),f=fe("aes-128-gcm",y,a),A=u.concat([u.from(t,"utf8"),u.from([2])]),M=u.concat([f.update(A),f.final(),f.getAuthTag()]),_=u.alloc(4);return _.writeUInt32BE(4096,0),u.concat([r,_,u.from([o.length]),o,M])}async function ve(e){let{subscription:t,vapid:r,subject:n}=e;if(!t?.endpoint)return{success:!1,status:0,expired:!1,error:"no endpoint"};let s={...ee({endpoint:t.endpoint,vapid:r,subject:n}),TTL:String(e.ttl??86400),Urgency:e.urgency??"normal"};if(e.topic)s.Topic=e.topic;let i;if(e.payload){if(!t.keys?.p256dh||!t.keys?.auth)return{success:!1,status:0,expired:!0,error:"subscription has no keys"};i=te(t,e.payload),s["Content-Encoding"]="aes128gcm",s["Content-Type"]="application/octet-stream",s["Content-Length"]=String(i.length)}try{let o=await fetch(t.endpoint,{method:"POST",headers:s,body:i?new Uint8Array(i):void 0}),c=o.status===404||o.status===410;if(o.status>=200&&o.status<300)return{success:!0,status:o.status,expired:!1};return{success:!1,status:o.status,expired:c,error:(await o.text().catch(()=>"")).slice(0,500)||`push service answered ${o.status}`}}catch(o){return{success:!1,status:0,expired:!1,error:o instanceof Error?o.message:String(o)}}}async function Ae(e,t,r={}){let n=r.driver??"expo";if(n==="expo")return v({to:e,title:t.title,body:t.body,data:t.data,badge:t.badge,sound:t.sound,priority:t.priority});if(n==="fcm"){let s=Array.isArray(e)?e:[e];if(s.length===1)return h({to:s[0],notification:{title:t.title??"",body:t.body},data:t.data,priority:t.priority==="default"?"normal":t.priority});let i=await T(s,{notification:{title:t.title??"",body:t.body},data:t.data,priority:t.priority==="default"?"normal":t.priority});return{success:i.every((c)=>c.success),provider:"fcm",message:`Sent to ${i.filter((c)=>c.success).length}/${i.length} devices`}}return{success:!1,provider:n,message:`Unknown push driver: ${n}`}}function Me(e){k(e)}function Ke(e){E(e)}export{ee as buildVapidHeaders,Ke as configureExpo,Me as configureFCM,te as encryptPayload,U as expo,q as fcm,xe as generateVapidKeys,Ae as send,ve as sendWebPush};
2
+ var me=Object.defineProperty;var he=(e)=>e;function be(e,t){this[e]=he.bind(null,t)}var B=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0,configurable:!0,set:be.bind(t,r)})};var Y={};B(Y,{Send:()=>I,configure:()=>N,default:()=>Pe,getReceipts:()=>G,isExpoPushToken:()=>K,resetConfiguration:()=>ve,resolveAccessToken:()=>z,send:()=>I,sendBatch:()=>X});var ae={};B(ae,{Send:()=>E,buildServiceAccountAssertion:()=>ee,clearAccessTokens:()=>ke,configure:()=>O,default:()=>Ee,normalizePrivateKey:()=>Q,resetConfiguration:()=>Se,resolveConfig:()=>D,send:()=>E,sendMulticast:()=>_,sendToTopic:()=>re,subscribeToTopic:()=>oe,unsubscribeFromTopic:()=>ie});var pe={};B(pe,{buildPayload:()=>ue,buildProviderToken:()=>ce,configure:()=>W,resetConfiguration:()=>Ie,send:()=>U});import{log as k}from"@stacksjs/cli";async function w(){let{awaitConfig:e}=await import("@stacksjs/config");return(await e()).services??{}}function p(e){let t=e?.trim();return t?t:void 0}var xe="https://exp.host/--/api/v2/push/send",T={};function N(e){T={...T,...e}}function ve(){T={}}async function z(){if(p(T.accessToken))return p(T.accessToken);try{return p((await w()).expo?.accessToken)}catch(e){k.debug(`Expo: could not read config/services.ts: ${e instanceof Error?e.message:String(e)}`);return}}async function q(e={}){let t={Accept:"application/json","Content-Type":"application/json",...e},r=await z();if(r)t.Authorization=`Bearer ${r}`;return t}function K(e){return/^Expo(?:nent)?PushToken\[.+\]$/.test(e)||/^[a-zA-Z0-9-_]+$/.test(e)}async function I(e){let t=Array.isArray(e.to)?e.to:[e.to],r=t.filter((n)=>!K(n));if(r.length>0)k.warn(`Invalid Expo push tokens found: ${r.join(", ")}`);let s=t.filter(K);if(s.length===0)return{success:!1,provider:"expo",message:"No valid Expo push tokens provided"};try{let n=s.map((u)=>({to:u,title:e.title,body:e.body,data:e.data,sound:e.sound??"default",badge:e.badge,channelId:e.channelId,priority:e.priority??"high",ttl:e.ttl})),i=4096;for(let u of n){let l=new TextEncoder().encode(JSON.stringify(u)).length;if(l>4096)return{success:!1,provider:"expo",message:`Expo message payload (${l} bytes) exceeds 4 KiB per-message limit`}}let o=await fetch(xe,{method:"POST",headers:await q({"Accept-Encoding":"gzip, deflate"}),body:JSON.stringify(n)});if(!o.ok){let u=await o.text();return k.error(`Expo push failed: ${u}`),{success:!1,provider:"expo",message:`HTTP ${o.status}: ${u}`}}let c=(await o.json()).data,f=c.filter((u)=>u.status==="error");if(f.length>0)k.warn(`Some push notifications failed: ${JSON.stringify(f)}`);let g=c.filter((u)=>u.status==="ok").length;return k.info(`Expo push sent: ${g}/${c.length} successful`),{success:f.length===0,provider:"expo",message:`Sent ${g}/${c.length} notifications`,messageId:c.find((u)=>u.id)?.id,data:{tickets:c}}}catch(n){let i=n instanceof Error?n:Error(String(n));return k.error(`Expo push error: ${i.message}`),{success:!1,provider:"expo",message:i.message}}}async function G(e){let t=await fetch("https://exp.host/--/api/v2/push/getReceipts",{method:"POST",headers:await q(),body:JSON.stringify({ids:e})});if(!t.ok)throw Error(`Failed to get receipts: ${t.status}`);return(await t.json()).data}async function X(e,t=100){let r=[];for(let s=0;s<e.length;s+=t){let n=e.slice(s,s+t),i=await Promise.all(n.map((o)=>I(o)));r.push(...i)}return r}var Pe={send:I,sendBatch:X,getReceipts:G,isExpoPushToken:K,configure:N};import{log as R}from"@stacksjs/cli";var Z="https://fcm.googleapis.com/v1/projects",m={};function O(e){m={...m,...e}}function Se(){m={},j.clear()}function Q(e){return e.includes("\\n")?e.replace(/\\n/g,`
3
+ `):e}async function D(){if(m.projectId&&m.serviceAccount)return m;let e={};try{e=await w()}catch(n){R.debug(`FCM: could not read config/services.ts: ${n instanceof Error?n.message:String(n)}`)}let t=e.fcm??{},r=p(t.clientEmail),s=p(t.privateKey);return{projectId:m.projectId??p(t.projectId),serviceAccount:m.serviceAccount??(r&&s?{clientEmail:r,privateKey:Q(s)}:void 0)}}function J(e){return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ee(e,t,r){let s={alg:"RS256",typ:"JWT"},n={iss:e,scope:"https://www.googleapis.com/auth/firebase.messaging",aud:"https://oauth2.googleapis.com/token",iat:r,exp:r+3600},i=new TextEncoder,o=J(JSON.stringify(s)),a=J(JSON.stringify(n)),c=`${o}.${a}`,f=t.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,""),g=Uint8Array.from(atob(f),(P)=>P.charCodeAt(0)),u=await crypto.subtle.importKey("pkcs8",g,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"]),l=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",u,i.encode(c)),b=J(String.fromCharCode(...new Uint8Array(l)));return`${o}.${a}.${b}`}var j=new Map,we=60000;function ke(){j.clear()}async function te(e){if(!e.serviceAccount)throw Error("Service account not configured for FCM v1 API");let{clientEmail:t,privateKey:r}=e.serviceAccount,s=j.get(t);if(s&&s.expiresAt-we>Date.now())return s.token;let n=await ee(t,r,Math.floor(Date.now()/1000)),i=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=${n}`});if(!i.ok)throw Error(`Failed to get access token: ${i.status}`);let o=await i.json(),a=Number(o.expires_in);return j.set(t,{token:o.access_token,expiresAt:Date.now()+(Number.isFinite(a)&&a>0?a:3600)*1000}),o.access_token}async function E(e){let t=await D();if(!t.serviceAccount||!t.projectId)return{success:!1,provider:"fcm",message:"FCM service account and projectId not configured - set FCM_PROJECT_ID, FCM_CLIENT_EMAIL and FCM_PRIVATE_KEY, or call configureFCM()"};try{let r=await te(t),s=`${Z}/${t.projectId}/messages:send`,n={message:{notification:e.notification,data:e.data,android:{priority:e.priority??"high",ttl:e.ttl?`${e.ttl}s`:void 0,collapseKey:e.collapseKey},apns:{headers:{"apns-priority":e.priority==="high"?"10":"5"}}}};if(e.to)n.message.token=e.to;else if(e.topic)n.message.topic=e.topic;else if(e.condition)n.message.condition=e.condition;let i=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok){let a=await i.text();return R.error(`FCM v1 push failed: ${a}`),{success:!1,provider:"fcm",message:`HTTP ${i.status}: ${a}`}}let o=await i.json();return R.info(`FCM v1 push sent: ${o.name}`),{success:!0,provider:"fcm",message:"Notification sent successfully",messageId:o.name}}catch(r){let s=r instanceof Error?r:Error(String(r));return R.error(`FCM v1 push error: ${s.message}`),{success:!1,provider:"fcm",message:s.message}}}async function _(e,t){return Promise.all(e.map((r)=>E({...t,to:r})))}async function re(e,t){return E({...t,topic:e})}async function se(e,t,r,s){let n=await te(e),i=`${Z}/${e.projectId}/registrations/${encodeURIComponent(t)}/topicSubscriptions`,o=s?`${i}?topic_name=${encodeURIComponent(r)}`:`${i}/${encodeURIComponent(r)}`,a=await fetch(o,{method:s?"POST":"DELETE",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:"{}"});if(a.ok||s&&a.status===409)return!0;return R.error(`FCM topic ${s?"subscribe":"unsubscribe"} failed for topic ${r}: HTTP ${a.status}`),!1}async function ne(e){let t=await D();if(!t.serviceAccount||!t.projectId)throw Error(`FCM service account and projectId required for ${e}`);return t}async function oe(e,t){let r=await ne("topic subscription");return(await Promise.all(e.map((n)=>se(r,n,t,!0)))).every(Boolean)}async function ie(e,t){let r=await ne("topic unsubscription");return(await Promise.all(e.map((n)=>se(r,n,t,!1)))).every(Boolean)}var Ee={send:E,sendMulticast:_,sendToTopic:re,subscribeToTopic:oe,unsubscribeFromTopic:ie,configure:O};import{createPrivateKey as Ce,sign as Ae}from"crypto";import Te,{constants as $e}from"http2";var v={},h;function W(e){v={...e},h=void 0}function Ie(){v={},h=void 0}function ce(e,t,r,s=Math.floor(Date.now()/1000)){let n=Buffer.from(JSON.stringify({alg:"ES256",kid:t})).toString("base64url"),i=Buffer.from(JSON.stringify({iss:e,iat:s})).toString("base64url"),o=`${n}.${i}`,a=Ce(r.replace(/\\n/g,`
4
+ `));if(a.asymmetricKeyType!=="ec"||a.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw Error("APNs requires an ES256 P-256 signing key");return`${o}.${Ae("sha256",Buffer.from(o),{key:a,dsaEncoding:"ieee-p1363"}).toString("base64url")}`}function ue(e){let t=JSON.stringify({...e.data,aps:{alert:{title:e.title??"",body:e.body},...e.sound!==null?{sound:e.sound??"default"}:{},...e.badge!==void 0?{badge:e.badge}:{}}});if(Buffer.byteLength(t)>4096)throw Error("APNs notification exceeds 4096 bytes");return t}async function U(e,t){let r=Array.isArray(e)?e:[e];if(!r.length||r.some((c)=>!/^[a-f\d]{64}$/i.test(c)))return{success:!1,provider:"apns",message:"A valid Apple device token is required"};let s=(await w()).apns,n=p(v.teamId)??p(s?.teamId),i=p(v.keyId)??p(s?.keyId),o=p(v.privateKey)??p(s?.privateKey),a=p(v.topic)??p(s?.topic);if(!n||!i||!o||!a)return{success:!1,provider:"apns",message:"APNs requires teamId, keyId, privateKey and topic"};try{let c=ue(t),f=Math.floor(Date.now()/1000),g=`${n}:${i}:${o}`;if(!h||h.identity!==g||f-h.issuedAt>=3000||f<h.issuedAt)h={identity:g,token:ce(n,i,o,f),issuedAt:f};let u=h.token,l=Te.connect(v.sandbox??s?.sandbox?"https://api.sandbox.push.apple.com":"https://api.push.apple.com");l.on("error",()=>{});try{let b=await Promise.all(r.map((S)=>new Promise((M)=>{let y=l.request({":method":"POST",":path":`/3/device/${S}`,authorization:`bearer ${u}`,"apns-topic":a,"apns-push-type":"alert","apns-priority":t.priority==="normal"?"5":"10","content-type":"application/json",...t.collapseId?{"apns-collapse-id":t.collapseId}:{}}),A=0,H="",L;y.setEncoding("utf8");let ye=setTimeout(()=>{y.close($e.NGHTTP2_CANCEL),M({success:!1,status:0,reason:"Timeout"})},15000);y.on("close",()=>{clearTimeout(ye),M({success:!1,status:A,reason:"TransportClosed"})}),y.on("response",(x)=>{A=Number(x[":status"]),L=String(x["apns-id"]??"")||void 0}),y.on("data",(x)=>{H+=x}),y.on("error",()=>M({success:!1,status:A,reason:"TransportError"})),y.on("end",()=>{let x;try{x=JSON.parse(H).reason}catch{}M({success:A===200,status:A,reason:x,messageId:L})}),y.end(c)}))),P=b.filter((S)=>S.success).length;return{success:P===r.length,provider:"apns",message:`Apple accepted ${P}/${r.length} notifications`,messageId:b[0]?.messageId,data:{results:b}}}finally{l.destroy()}}catch(c){return{success:!1,provider:"apns",message:c instanceof Error?c.message:"APNs delivery failed"}}}import{Buffer as d}from"buffer";import{createCipheriv as Re,createECDH as Me,createHmac as de,createPrivateKey as Ke,createSign as Ne,generateKeyPairSync as je,randomBytes as Oe}from"crypto";var fe="prime256v1";function C(e){return e.toString("base64url")}function F(e){return d.from(e,"base64url")}function _e(){let{publicKey:e,privateKey:t}=je("ec",{namedCurve:fe}),r=e.export({type:"spki",format:"der"}),s=t.export({format:"jwk"});return{publicKey:C(r.subarray(r.length-65)),privateKey:String(s.d)}}function Fe(e){let t=new URL(e);return`${t.protocol}//${t.host}`}function le(e){let r=Math.floor(e.nowSeconds??Date.now()/1000)+Math.min(e.expiresInSeconds??43200,86400),s=C(d.from(JSON.stringify({typ:"JWT",alg:"ES256"}))),n=C(d.from(JSON.stringify({aud:Fe(e.endpoint),exp:r,sub:e.subject}))),i=`${s}.${n}`,o=Ke({key:{kty:"EC",crv:"P-256",d:e.vapid.privateKey,x:C(F(e.vapid.publicKey).subarray(1,33)),y:C(F(e.vapid.publicKey).subarray(33,65))},format:"jwk"}),a=Ne("SHA256");a.update(i);let c=a.sign({key:o,dsaEncoding:"ieee-p1363"});return{Authorization:`vapid t=${i}.${C(c)}, k=${e.vapid.publicKey}`,"Crypto-Key":`p256ecdsa=${e.vapid.publicKey}`}}function V(e,t,r,s){let n=de("sha256",e).update(t).digest();return de("sha256",n).update(d.concat([r,d.from([1])])).digest().subarray(0,s)}function ge(e,t,r=Oe(16)){let s=F(e.keys.p256dh),n=F(e.keys.auth),i=Me(fe);i.generateKeys();let o=i.getPublicKey(),a=i.computeSecret(s),c=d.concat([d.from("WebPush: info\x00"),s,o]),f=V(n,a,c,32),g=V(r,f,d.from("Content-Encoding: aes128gcm\x00"),16),u=V(r,f,d.from("Content-Encoding: nonce\x00"),12),l=Re("aes-128-gcm",g,u),b=d.concat([d.from(t,"utf8"),d.from([2])]),P=d.concat([l.update(b),l.final(),l.getAuthTag()]),S=d.alloc(4);return S.writeUInt32BE(4096,0),d.concat([r,S,d.from([o.length]),o,P])}async function Be(e){let{subscription:t,vapid:r,subject:s}=e;if(!t?.endpoint)return{success:!1,status:0,expired:!1,error:"no endpoint"};let n={...le({endpoint:t.endpoint,vapid:r,subject:s}),TTL:String(e.ttl??86400),Urgency:e.urgency??"normal"};if(e.topic)n.Topic=e.topic;let i;if(e.payload){if(!t.keys?.p256dh||!t.keys?.auth)return{success:!1,status:0,expired:!0,error:"subscription has no keys"};i=ge(t,e.payload),n["Content-Encoding"]="aes128gcm",n["Content-Type"]="application/octet-stream",n["Content-Length"]=String(i.length)}try{let o=await fetch(t.endpoint,{method:"POST",headers:n,body:i?new Uint8Array(i):void 0}),a=o.status===404||o.status===410;if(o.status>=200&&o.status<300)return{success:!0,status:o.status,expired:!1};return{success:!1,status:o.status,expired:a,error:(await o.text().catch(()=>"")).slice(0,500)||`push service answered ${o.status}`}}catch(o){return{success:!1,status:0,expired:!1,error:o instanceof Error?o.message:String(o)}}}async function Ze(e,t,r={}){let s=r.driver??"expo";if(s==="apns")return U(e,t);if(s==="expo")return I({to:e,title:t.title,body:t.body,data:t.data,badge:t.badge,sound:t.sound,priority:t.priority});if(s==="fcm"){let n=Array.isArray(e)?e:[e];if(n.length===1)return E({to:n[0],notification:{title:t.title??"",body:t.body},data:t.data,priority:t.priority==="default"?"normal":t.priority});let i=await _(n,{notification:{title:t.title??"",body:t.body},data:t.data,priority:t.priority==="default"?"normal":t.priority});return{success:i.every((a)=>a.success),provider:"fcm",message:`Sent to ${i.filter((a)=>a.success).length}/${i.length} devices`}}return{success:!1,provider:s,message:`Unknown push driver: ${s}`}}function Qe(e){O(e)}function et(e){N(e)}function tt(e){W(e)}export{pe as apns,le as buildVapidHeaders,tt as configureAPNS,et as configureExpo,Qe as configureFCM,ge as encryptPayload,Y as expo,ae as fcm,_e as generateVapidKeys,Ze as send,Be as sendWebPush};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/push",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.124",
5
+ "version": "0.75.127",
6
6
  "description": "The Stacks Push integration",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -56,11 +56,11 @@
56
56
  "prepublishOnly": "bun run build"
57
57
  },
58
58
  "dependencies": {
59
- "@stacksjs/cli": "0.75.124",
60
- "@stacksjs/config": "0.75.124"
59
+ "@stacksjs/cli": "0.75.127",
60
+ "@stacksjs/config": "0.75.127"
61
61
  },
62
62
  "devDependencies": {
63
- "@stacksjs/error-handling": "0.75.124",
63
+ "@stacksjs/error-handling": "0.75.127",
64
64
  "better-dx": "^0.2.24"
65
65
  }
66
66
  }