t1k:gamebackend:game-server:auth-iap
| Field | Value |
|---|---|
| Module | game-server |
| Version | 1.10.3 |
| Effort | medium |
| Tools | — |
Keywords: apple x5c chain, es256 access token worker, game server jwt, iap receipt validation, play purchasetoken, provider token jwks
How to invoke
Section titled “How to invoke”/t1k:gamebackend:game-server:auth-iap<jwt | provider-token | play-iap | apple-iap>Auth and IAP on a Worker + per-player Durable Object
Section titled “Auth and IAP on a Worker + per-player Durable Object”Build auth, IAP validation, push and abuse limits yourself on WebCrypto; buy only what is cheap and saves maintenance
(Sentry, FCM). Context and invariants: t1k-gamebackend-game-server-architecture. Evidence labels there: measured,
published, modelled, UNVERIFIED. Research retrieved 2026-10-08; the retrieval tool summarised pages, so
anything marked UNVERIFIED was not seen on the page.
Decision tree
Section titled “Decision tree”| Intent | Go to |
|---|---|
| “Sign and verify our own access token” | JWT |
| “Accept a Google/Apple/Facebook sign-in” | Provider tokens |
| “Validate a Google Play purchase” | Google Play |
| “Validate an App Store purchase” | Apple and references/apple-x5c.md |
| “Design signup / login for a mock that had none” | references/account-signup.md |
| “Rewarded-ad SSV, push, abuse limits” | references/ads-push-abuse.md |
| “Account delete, logout vs unlink, status for a deleted account” | references/account-delete-and-logout.md |
Build versus buy (modelled; assumptions: MAU = 3x DAU, 4 token calls per DAU per day)
Section titled “Build versus buy (modelled; assumptions: MAU = 3x DAU, 4 token calls per DAU per day)”| Component | Choice | Cost at 10K / 100K / 1M DAU | Switch when |
|---|---|---|---|
| Auth | custom JWT in Workers | <$2 / ~$6-18 / ~$60-180 | email/password, SMS OTP, MFA or account recovery enters scope: buy Firebase Auth / Identity Platform |
| IAP | DIY validation | ~$0 / ~$0 / ~$1-5 | subscriptions or VIP are a core revenue line, a web shop, cross-platform entitlements: RevenueCat (~1% of tracked revenue) |
| Errors | Sentry Team ($26/mo, @sentry/cloudflare supports Durable Objects) + sampled Workers Logs | ||
| Push | FCM HTTP v1 as the single pipe | free | marketing needs campaign UI: OneSignal (~$0.012/MAU) |
Firebase Auth was quoted at ~$1.2K/mo at 100K DAU and ~$10.8K/mo at 1M DAU, and guest (anonymous) accounts count as
users, which an idle game inflates. A vendor would still sit behind your own /connect/token, so it offloads only the
provider verifiers.
JWT (ES256 via WebCrypto)
Section titled “JWT (ES256 via WebCrypto)”- Sign and verify with
crypto.subtleECDSA P-256 / SHA-256. WebCrypto’s signature is rawr||s, 64 bytes, which is exactly the JWSES256format: no DER conversion. Keep the private key as a JWK secret, never in the repo. - CPU is not a concern (measured, coarse loop): sign ~61 µs, verify ~80 µs on workerd. An older ~2 ms assumption was ~30x too high.
- Verify in a middleware that runs before any route and before any Durable Object; a bad token must cost one Worker request and never a DO request (assert it in a test).
- Put a session-version claim in the token and compare it in the PlayerDO: force-logout is then free because the DO is touched anyway. Rotating the refresh token on every call adds ~$120/mo of DO row writes at 1M DAU (modelled).
- You own key rotation, JWKS caching, nonce/replay checks and linking edge cases. No email, phone or recovery.
- Token numeric ids that the client parses as numbers must fit 53 bits (
Number.isSafeInteger). - Verifier must pin
alg, require and checkexp, and validateiss/aud. Enforcesvin the DO or drop the claim. Never put the server secret in a token response. Full list, signup/login design and the open items:references/account-signup.md. - Tamper tests: flip the FIRST signature character, not the last (see
t1k-gamebackend-game-server-rest-contract-port).
Provider tokens
Section titled “Provider tokens”| Provider | Verify | Status |
|---|---|---|
| Google ID token | JWKS https://www.googleapis.com/oauth2/v3/certs; check aud, iss, exp. tokeninfo is not for production | published |
| Facebook Limited Login | OIDC token, JWKS https://limited.facebook.com/.well-known/oauth/openid/jwks/; documented for iOS | Android path UNVERIFIED; issuer/audience/algorithm not seen |
| Apple identity token | JWKS appleid.apple.com/auth/keys, RS256 | UNVERIFIED (the page fetch returned filler) |
Linking uniqueness: map hash(provider:sub) to one playerId in the D1 directory (or a sharded identity DO); written
only at register/link time. Decide the “provider account already linked to another player” outcome explicitly; it is
the hardest edge in linking.
Google Play IAP
Section titled “Google Play IAP”purchaseTokenis the unique key (notorderId). Grant only in statePURCHASED.- Acknowledge or consume within 3 days or Play auto-refunds.
- Default API quota 3,000 queries/min per bucket (one-time and subscriptions separate), far above a game’s load.
- Dedupe on
purchaseTokeninside the PlayerDO: the dedupe key and the grant are one transactional write. - Phase 2, refunds: real-time developer notifications arrive through a Google Cloud Pub/Sub push subscription (a GCP
project, a second cloud). A notification needs a follow-up API call; dedupe on
messageId; voided-purchase and chargeback notifications exist. - Never await the store call inside the DO (it blocks hibernation):
PlayerDO -> Queue (batched) -> consumer verifies -> callback.
Apple IAP
Section titled “Apple IAP”- Phase 1: the client sends the signed transaction (a JWS). Verify the signature with the leaf certificate in the
x5cheader and verify the chain to Apple’s root. Or call Get Transaction Info (needs issuer id, key id, bundle id,.p8). - Phase 2: App Store Server Notifications V2 are a
signedPayloadJWS verified with the samex5cchain. - Apple’s own Node library uses Node crypto (X.509); its
SignedDataVerifierneeds Apple root certificates. - Measured on workerd under
nodejs_compat(3-cert ES256 chain built with openssl, not a real Apple chain):X509Certificateexists onnode:cryptoonly;verify()andcheckIssued()give correct results including the negative case; anx5centry is base64 DER and must be decoded to aUint8Arrayfirst (the base64 string throws “not a valid certificate”);node:cryptoverifyneeds the public key as a PEM string (aPublicKeyObject, SPKI DER or the cert object all fail); prefer WebCryptosubtle.verifyfor the JWS signature. Detail and the fallback inreferences/apple-x5c.md. - Not spiked, required before trusting it: pinning the chain root to Apple’s root certificate, checking validity dates and the bundle id / environment claims, and testing against a real sandbox transaction. A chain that verifies to a self-chosen root proves nothing: the root must be one you pinned.
UNVERIFIED
Section titled “UNVERIFIED”Apple ES256 JWT claims, max expiry and API rate limits (429 / Retry-After); App Store Server API behaviour of
Notifications V2 retries; whether FCM-to-APNs needs an APNs key uploaded in Firebase (believed yes); whether the game’s
mediation passes AdMob SSV through MAX; Play Integrity / App Attest not researched; Cloudflare Pro plan price and WAF
rule counts; whether WAF-blocked requests are excluded from Workers billing.
Related
Section titled “Related”t1k-gamebackend-game-server-architecture, t1k-gamebackend-game-server-rest-contract-port, rule gamebackend-game-server-invariants.
Credentials the Worker needs (JWT_SIGNING_KEY, Apple .p8, Play service account) are Worker secrets set with
cf workers secrets bulk --body @file (t1k-gamebackend-game-server-template-bootstrap); studio-shared credentials live in the studio vault.