What this thread does
Sign the APNs provider JWT with WebCrypto ES256, encrypt stored device tokens with a separate AES-GCM key, and gate alert delivery on native authorization and app preferences.
Do first: enable Xcode's Push Notifications capability and provision the signed app, then keep the APNs .p8 key and a separate random 32-byte storage key in Worker secret bindings. (registration, secrets)
1. Build the provider JWT
Use alg: ES256 and the Apple key ID in the header, and your developer Team ID plus integer Unix seconds in iss/iat. Select a key allowed for the APNs environment and topic. Reuse the JWT and coordinate refresh across senders: Apple specifies a 20–60 minute interval, rather than a new JWT per push. Per-isolate caching alone is not a global refresh policy. (Apple authentication)
Workers exposes ECDSA signing and AES-GCM. This illustrative signer imports PKCS#8 PEM bytes and signs the encoded header and claims. WebCrypto ECDSA produces fixed-width r || s; ES256 JWS needs 64 bytes, not an ASN.1 DER signature. (Workers crypto, WebCrypto ECDSA, JWA §3.4)
const utf8 = new TextEncoder();
const b64u = bytes =>
btoa(String.fromCharCode(...bytes))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
async function providerJWT(pem, keyId, teamId) {
const base64 = pem.replace(/-----[^-]+-----/g, "")
.replace(/\s/g, "");
const der = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
const key = await crypto.subtle.importKey(
"pkcs8", der, { name: "ECDSA", namedCurve: "P-256" },
false, ["sign"]
);
const header = b64u(utf8.encode(JSON.stringify({
alg: "ES256", kid: keyId
})));
const claims = b64u(utf8.encode(JSON.stringify({
iss: teamId, iat: Math.floor(Date.now() / 1000)
})));
const input = header + "." + claims;
const sig = new Uint8Array(await crypto.subtle.sign(
{ name: "ECDSA", hash: "SHA-256" }, key, utf8.encode(input)
));
if (sig.length !== 64) throw new Error("Unexpected ES256 signature size");
return input + "." + b64u(sig);
}
Pass the cached result as authorization: bearer <jwt> in the APNs POST; the device token goes in /3/device/<token>. Signing establishes neither outbound HTTP/2 nor notification permission. (request contract)
2. Encrypt device tokens at rest
Apple directs providers to store device tokens securely and associate them with accounts. This is an application storage design, not an APNs wire format: authenticate registration, derive the owner from the server session, and restrict app/environment values to those your endpoint serves. (registration guidance)
For this storage design, use a persistent, separately managed AES-256 key, not one derived from .p8 or regenerated per request. Bind ciphertext to owner, installation, bundle ID and environment with authenticated additional data (AAD). Store {version, keyVersion, iv, ciphertextAndTag} with the registration. WebCrypto appends the tag to ciphertext. (Workers crypto, GCM operations)
async function sealToken(token, keyBytes, binding) {
if (keyBytes.length !== 32) throw new Error("Expected 32 key bytes");
const key = await crypto.subtle.importKey(
"raw", keyBytes, "AES-GCM", false, ["encrypt", "decrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const aad = utf8.encode(JSON.stringify([
"apns-device-v1", binding.ownerId, binding.installationId,
binding.bundleId, binding.environment
]));
const ciphertextAndTag = new Uint8Array(await crypto.subtle.encrypt(
{ name: "AES-GCM", iv, additionalData: aad, tagLength: 128 },
key, utf8.encode(token)
));
return { iv, ciphertextAndTag };
}
Encode these binary fields for storage. Never reuse an IV with the same key: enforce a per-key usage budget and uniqueness for stored (keyVersion, iv) pairs; on collision, regenerate and re-encrypt. GCM security depends on IV non-repetition. (NIST guidance)
For reads, select the key version, reconstruct identical AAD from the authorized registration context, and call crypto.subtle.decrypt with the same IV, AAD and tag length. Reject authentication failures. Retain old keys until records are re-encrypted; key loss prevents recovery. Keep keys outside token records and plaintext tokens out of logs. These are storage safeguards based on authenticated decryption and Worker secrets.
3. Separate entitlement, registration and authorization
- Enable the App ID's push service and signed app's
aps-environmententitlement. CallUIApplication.shared.registerForRemoteNotifications()and send the token fromapplication(_:didRegisterForRemoteNotificationsWithDeviceToken:)over authenticated TLS. Refresh it at launch rather than treating a locally cached token as permanent. (Apple registration) - Request
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])in context and read current notification settings. A token is an address, not evidence of permission. Provisional authorization permits quiet delivery, not full alerts. (Apple permissions) - As application policy, keep authorization observations separate from account/installation preferences, refresh observations when the app returns, and check server opt-outs before dispatch. A client report is a snapshot; iOS controls presentation and users can change settings. A server cannot grant OS permission. (permission model)
Diagnostic: InvalidProviderToken
Check kid/Team ID/key scope, current iat, and the 64-byte signature before rotating device tokens. ExpiredProviderToken needs a fresh JWT; TooManyProviderTokenUpdates calls for reuse and coordinated refresh. (Apple responses)
Token refresh and storage limits
dekoziri, August 2020 distinguishes provider from device tokens: “Make sure you are not generating a new provider token for each request.” In that thread, andrew804 (September 2017) and mohanganesh413 (March 2024) report TooManyProviderTokenUpdates. Encryption at rest cannot protect tokens from a sender holding the decryption key.
Not for: Safari/VAPID Web Push, App Store Server API JWTs, or overriding denied notification permission.
Started from a post by @editor, packaged by the editor. Original post