apns.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import {
  2. connect,
  3. constants as http2Constants,
  4. type ClientHttp2Session,
  5. type IncomingHttpHeaders,
  6. type OutgoingHttpHeaders,
  7. } from 'node:http2'
  8. import {
  9. createPrivateKey,
  10. randomUUID,
  11. sign,
  12. type KeyObject,
  13. } from 'node:crypto'
  14. import { readFileSync } from 'node:fs'
  15. import type { APNsProviderConfig } from './config.js'
  16. import { notificationPlainText } from './notificationText.js'
  17. export type APNsEnvironment = 'development' | 'production'
  18. export interface APNsRequest {
  19. deviceToken: string
  20. environment: APNsEnvironment
  21. payload: Record<string, unknown>
  22. apnsId?: string
  23. collapseId?: string
  24. expiration?: number
  25. priority?: 5 | 10
  26. pushType?: 'alert' | 'background'
  27. }
  28. export interface APNsTransportResponse {
  29. status: number
  30. headers?: IncomingHttpHeaders | Record<string, string | string[] | undefined>
  31. body?: string
  32. }
  33. export interface APNsTransport {
  34. send(endpoint: URL, headers: OutgoingHttpHeaders, body: Uint8Array): Promise<APNsTransportResponse>
  35. close?(): void
  36. }
  37. export type APNsDisposition = 'success' | 'retry' | 'unregister' | 'configuration' | 'failed'
  38. export interface APNsSendResult {
  39. disposition: APNsDisposition
  40. status: number
  41. reason?: string
  42. apnsId?: string
  43. timestamp?: number
  44. retryAfterMs?: number
  45. }
  46. export interface APNsProviderOptions {
  47. transport?: APNsTransport
  48. now?: () => number
  49. }
  50. export const APNS_DEVELOPMENT_ENDPOINT = new URL('https://api.sandbox.push.apple.com')
  51. export const APNS_PRODUCTION_ENDPOINT = new URL('https://api.push.apple.com')
  52. export const APNS_MAX_PAYLOAD_BYTES = 4_096
  53. const TOKEN_RE = /^(?:[a-fA-F0-9]{2}){16,256}$/
  54. const PROVIDER_TOKEN_LIFETIME_MS = 50 * 60 * 1_000
  55. const TOKEN_CONFIGURATION_REASONS = new Set([
  56. 'ExpiredProviderToken',
  57. 'InvalidProviderToken',
  58. 'MissingProviderToken',
  59. 'BadTopic',
  60. 'TopicDisallowed',
  61. ])
  62. const UNREGISTER_REASONS = new Set([
  63. 'BadDeviceToken',
  64. 'DeviceTokenNotForTopic',
  65. 'Unregistered',
  66. ])
  67. function sanitizedPayload(payload: Record<string, unknown>): Record<string, unknown> {
  68. const aps = payload.aps
  69. if (!aps || typeof aps !== 'object' || Array.isArray(aps)) return payload
  70. const alert = (aps as Record<string, unknown>).alert
  71. if (!alert || typeof alert !== 'object' || Array.isArray(alert)) return payload
  72. const record = alert as Record<string, unknown>
  73. return {
  74. ...payload,
  75. aps: {
  76. ...(aps as Record<string, unknown>),
  77. alert: {
  78. ...record,
  79. ...(typeof record.title === 'string' ? {
  80. title: notificationPlainText(record.title, { fallback: '新消息', maximum: 120 }),
  81. } : {}),
  82. ...(typeof record.body === 'string' ? {
  83. body: notificationPlainText(record.body, { fallback: '请打开夭夭查看详情', maximum: 180 }),
  84. } : {}),
  85. },
  86. },
  87. }
  88. }
  89. function encodedJSON(value: unknown): string {
  90. return Buffer.from(JSON.stringify(value), 'utf8').toString('base64url')
  91. }
  92. export function createAPNsProviderToken(
  93. config: Pick<APNsProviderConfig, 'keyFile' | 'keyId' | 'teamId'>,
  94. now = Date.now(),
  95. suppliedKey?: KeyObject,
  96. ): string {
  97. const key = suppliedKey ?? createPrivateKey(readFileSync(config.keyFile))
  98. const header = encodedJSON({ alg: 'ES256', kid: config.keyId })
  99. const claims = encodedJSON({ iss: config.teamId, iat: Math.floor(now / 1_000) })
  100. const signingInput = `${header}.${claims}`
  101. const signature = sign('sha256', Buffer.from(signingInput, 'ascii'), {
  102. key,
  103. dsaEncoding: 'ieee-p1363',
  104. }).toString('base64url')
  105. return `${signingInput}.${signature}`
  106. }
  107. function firstHeader(
  108. headers: APNsTransportResponse['headers'],
  109. name: string,
  110. ): string | undefined {
  111. const value = headers?.[name]
  112. if (Array.isArray(value)) return value[0]
  113. if (typeof value === 'string' || typeof value === 'number') return String(value)
  114. return undefined
  115. }
  116. function responseReason(body: string | undefined): { reason?: string; timestamp?: number } {
  117. if (!body) return {}
  118. try {
  119. const value = JSON.parse(body) as { reason?: unknown; timestamp?: unknown }
  120. return {
  121. ...(typeof value.reason === 'string' ? { reason: value.reason } : {}),
  122. ...(typeof value.timestamp === 'number' ? { timestamp: value.timestamp } : {}),
  123. }
  124. } catch {
  125. return { reason: body.slice(0, 200) }
  126. }
  127. }
  128. function retryAfterMilliseconds(value: string | undefined, now: number): number | undefined {
  129. if (!value) return undefined
  130. const seconds = Number(value)
  131. if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds * 1_000)
  132. const at = Date.parse(value)
  133. if (Number.isNaN(at)) return undefined
  134. return Math.max(0, at - now)
  135. }
  136. export function classifyAPNsResponse(
  137. response: APNsTransportResponse,
  138. now = Date.now(),
  139. ): APNsSendResult {
  140. const { reason, timestamp } = responseReason(response.body)
  141. const apnsId = firstHeader(response.headers, 'apns-id')
  142. const common = {
  143. status: response.status,
  144. ...(reason ? { reason } : {}),
  145. ...(apnsId ? { apnsId } : {}),
  146. ...(timestamp !== undefined ? { timestamp } : {}),
  147. }
  148. if (response.status === 0) return { disposition: 'retry', ...common }
  149. if (response.status === 200) return { disposition: 'success', ...common }
  150. if (response.status === 410 || (reason && UNREGISTER_REASONS.has(reason))) {
  151. return { disposition: 'unregister', ...common }
  152. }
  153. if (response.status === 429 || response.status >= 500) {
  154. const retryAfterMs = retryAfterMilliseconds(firstHeader(response.headers, 'retry-after'), now)
  155. return { disposition: 'retry', ...common, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) }
  156. }
  157. if (response.status === 403 || (reason && TOKEN_CONFIGURATION_REASONS.has(reason))) {
  158. return { disposition: 'configuration', ...common }
  159. }
  160. if (response.status === 400) return { disposition: 'failed', ...common }
  161. return { disposition: 'failed', ...common }
  162. }
  163. export class NodeHttp2APNsTransport implements APNsTransport {
  164. private readonly sessions = new Map<string, ClientHttp2Session>()
  165. constructor(readonly timeoutMilliseconds = 15_000) {}
  166. private session(endpoint: URL): ClientHttp2Session {
  167. const origin = endpoint.origin
  168. const existing = this.sessions.get(origin)
  169. if (existing && !existing.closed && !existing.destroyed) return existing
  170. const session = connect(origin)
  171. this.sessions.set(origin, session)
  172. const discard = () => {
  173. if (this.sessions.get(origin) === session) this.sessions.delete(origin)
  174. }
  175. session.once('close', discard)
  176. session.once('goaway', discard)
  177. session.on('error', discard)
  178. return session
  179. }
  180. send(endpoint: URL, headers: OutgoingHttpHeaders, body: Uint8Array): Promise<APNsTransportResponse> {
  181. return new Promise((resolve, reject) => {
  182. const stream = this.session(endpoint).request(headers)
  183. let settled = false
  184. const settle = <T>(finish: (value: T) => void, value: T) => {
  185. if (settled) return
  186. settled = true
  187. clearTimeout(timeout)
  188. finish(value)
  189. }
  190. const timeout = setTimeout(() => {
  191. stream.close(http2Constants.NGHTTP2_CANCEL)
  192. settle(reject, new Error('APNs request timed out'))
  193. }, this.timeoutMilliseconds)
  194. timeout.unref()
  195. let responseHeaders: IncomingHttpHeaders | undefined
  196. const chunks: Buffer[] = []
  197. let size = 0
  198. stream.once('response', headersValue => { responseHeaders = headersValue })
  199. stream.on('data', (chunk: Buffer | string) => {
  200. const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
  201. size += buffer.length
  202. if (size <= 64 * 1_024) chunks.push(buffer)
  203. })
  204. stream.once('end', () => {
  205. const status = Number(responseHeaders?.[http2Constants.HTTP2_HEADER_STATUS] ?? 0)
  206. settle(resolve, { status, headers: responseHeaders, body: Buffer.concat(chunks).toString('utf8') })
  207. })
  208. stream.once('error', error => settle(reject, error))
  209. stream.end(body)
  210. })
  211. }
  212. close(): void {
  213. for (const session of this.sessions.values()) session.destroy()
  214. this.sessions.clear()
  215. }
  216. }
  217. export class APNsProvider {
  218. private readonly transport: APNsTransport
  219. private readonly now: () => number
  220. private key?: KeyObject
  221. private token?: { value: string; createdAt: number }
  222. constructor(
  223. readonly config: APNsProviderConfig,
  224. options: APNsProviderOptions = {},
  225. ) {
  226. this.transport = options.transport ?? new NodeHttp2APNsTransport()
  227. this.now = options.now ?? Date.now
  228. }
  229. private authorizationToken(): string {
  230. const now = this.now()
  231. if (this.token && now - this.token.createdAt < PROVIDER_TOKEN_LIFETIME_MS) return this.token.value
  232. this.key ??= createPrivateKey(readFileSync(this.config.keyFile))
  233. const value = createAPNsProviderToken(this.config, now, this.key)
  234. this.token = { value, createdAt: now }
  235. return value
  236. }
  237. async send(request: APNsRequest): Promise<APNsSendResult> {
  238. const environments = this.config.environments ?? ['development', 'production']
  239. if (!environments.includes(request.environment)) {
  240. return { disposition: 'configuration', status: 0, reason: 'EnvironmentNotConfigured' }
  241. }
  242. if (!TOKEN_RE.test(request.deviceToken)) {
  243. return { disposition: 'unregister', status: 0, reason: 'BadDeviceToken' }
  244. }
  245. const body = Buffer.from(JSON.stringify(sanitizedPayload(request.payload)), 'utf8')
  246. if (body.length > APNS_MAX_PAYLOAD_BYTES) {
  247. return { disposition: 'failed', status: 0, reason: 'PayloadTooLarge' }
  248. }
  249. if (request.collapseId && Buffer.byteLength(request.collapseId, 'utf8') > 64) {
  250. return { disposition: 'failed', status: 0, reason: 'BadCollapseId' }
  251. }
  252. let authorization: string
  253. try {
  254. authorization = this.authorizationToken()
  255. } catch (cause) {
  256. return {
  257. disposition: 'configuration',
  258. status: 0,
  259. reason: cause instanceof Error ? cause.message : 'Unable to load APNs provider key',
  260. }
  261. }
  262. const endpoint = request.environment === 'development'
  263. ? APNS_DEVELOPMENT_ENDPOINT
  264. : APNS_PRODUCTION_ENDPOINT
  265. const apnsId = request.apnsId ?? randomUUID()
  266. const headers: OutgoingHttpHeaders = {
  267. [http2Constants.HTTP2_HEADER_METHOD]: 'POST',
  268. [http2Constants.HTTP2_HEADER_PATH]: `/3/device/${request.deviceToken.toLowerCase()}`,
  269. authorization: `bearer ${authorization}`,
  270. 'content-type': 'application/json',
  271. 'apns-topic': this.config.topic,
  272. 'apns-push-type': request.pushType ?? 'alert',
  273. 'apns-priority': String(request.priority ?? 10),
  274. 'apns-expiration': String(request.expiration ?? 0),
  275. 'apns-id': apnsId,
  276. ...(request.collapseId ? { 'apns-collapse-id': request.collapseId } : {}),
  277. }
  278. try {
  279. const result = classifyAPNsResponse(await this.transport.send(endpoint, headers, body), this.now())
  280. if (result.disposition === 'configuration') this.token = undefined
  281. return result
  282. } catch (cause) {
  283. return {
  284. disposition: 'retry',
  285. status: 0,
  286. reason: cause instanceof Error ? cause.message : 'APNs connection failed',
  287. }
  288. }
  289. }
  290. close(): void {
  291. this.transport.close?.()
  292. }
  293. }