Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119/** * Minimal APNs client: token-based auth (ES256 JWT) over HTTP/2, no dependencies. * Without APNS_* env vars it runs in dry-run mode and just logs what it would send. */import { connect, type ClientHttp2Session } from 'node:http2'import { createPrivateKey, sign, type KeyObject } from 'node:crypto'import { devices, type Device, type PushEnv } from './db.ts'import { fcmEnabled, sendFcm } from './fcm.ts'
const KEY_ID = process.env.APNS_KEY_IDconst TEAM_ID = process.env.APNS_TEAM_IDconst TOPIC = process.env.APNS_TOPIC ?? 'dev.mozzius.juno'const PRIVATE_KEY = process.env.APNS_PRIVATE_KEY
export const apnsEnabled = Boolean(KEY_ID && TEAM_ID && PRIVATE_KEY)const key: KeyObject | undefined = apnsEnabled ? createPrivateKey(PRIVATE_KEY!.replace(/\\n/g, '\n')) : undefined
const HOSTS: Record<Exclude<PushEnv, 'fcm'>, string> = { production: 'https://api.push.apple.com', sandbox: 'https://api.sandbox.push.apple.com',}
// Apple wants the provider token refreshed every 20–60 minutes.let jwt: { token: string; at: number } | undefinedfunction providerToken() { if (jwt && Date.now() - jwt.at < 45 * 60_000) return jwt.token const b64 = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url') const unsigned = `${b64({ alg: 'ES256', kid: KEY_ID })}.${b64({ iss: TEAM_ID, iat: Math.floor(Date.now() / 1000) })}` const signature = sign('sha256', Buffer.from(unsigned), { key: key!, dsaEncoding: 'ieee-p1363' }).toString('base64url') jwt = { token: `${unsigned}.${signature}`, at: Date.now() } return jwt.token}
const sessions = new Map<Exclude<PushEnv, 'fcm'>, ClientHttp2Session>()function session(env: Exclude<PushEnv, 'fcm'>) { const existing = sessions.get(env) if (existing && !existing.closed && !existing.destroyed) return existing const s = connect(HOSTS[env]) s.on('error', () => sessions.delete(env)) s.on('close', () => sessions.delete(env)) sessions.set(env, s) return s}
export type Push = { title: string body: string /** Groups notifications for the same event together. */ threadId?: string /** Opened on tap, e.g. { eventUri } or { actor }. */ data?: Record<string, string>}
function sendOne(device: Device, push: Push): Promise<void> { const payload = JSON.stringify({ aps: { alert: { title: push.title, body: push.body }, sound: 'default', 'thread-id': push.threadId, 'mutable-content': 1, }, ...push.data, }) return new Promise((resolve) => { const req = session(device.env as Exclude<PushEnv, 'fcm'>).request({ ':method': 'POST', ':path': `/3/device/${device.token}`, authorization: `bearer ${providerToken()}`, 'apns-topic': TOPIC, 'apns-push-type': 'alert', 'apns-priority': '10', 'content-type': 'application/json', }) let status = 0 let body = '' req.on('response', (h) => (status = Number(h[':status']))) req.setEncoding('utf8') req.on('data', (d) => (body += d)) req.on('end', () => { if (status !== 200) { const reason = (() => { try { return JSON.parse(body).reason as string } catch { return body } })() // Dead tokens: the app was deleted or the token rotated. if (status === 410 || reason === 'BadDeviceToken' || reason === 'Unregistered') devices.remove(device.token) else console.warn('apns', status, reason) } resolve() }) req.on('error', (err) => { console.warn('apns request failed', err.message) resolve() }) req.end(payload) })}
/** Push to every device a user has: iOS through APNs, Android through FCM. */export async function pushTo(did: string, original: Push) { const targets = devices.forDid(did) if (!targets.length) return // Which account it's for: a phone can be signed into several, and a tap switches to this one. const push: Push = { ...original, data: { ...original.data, did } } const ios = targets.filter((d) => d.env !== 'fcm') const android = targets.filter((d) => d.env === 'fcm') const dryRun = [...(apnsEnabled ? [] : ios), ...(fcmEnabled ? [] : android)] if (dryRun.length) { console.log(`[push:dry-run] → ${did} (${dryRun.map((d) => d.env).join(', ')}): ${push.title} — ${push.body}`) } await Promise.all([ ...(apnsEnabled ? ios.map((d) => sendOne(d, push)) : []), fcmEnabled && android.length ? sendFcm(android, push) : Promise.resolve(), ])}