Skip to content

feat(push): register Apple push through v2 - #393

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/45-apple-push-registration-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/45-apple-push-registration-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

The iOS app now registers its APNs token through the ordered v2 push protocol, with a persisted per-server installation key and generation journal.

Problem

The iOS app still registers its APNs token with POST /api/v1/devices/push/apple (rows 127 and 137). The v2 operation, registerApplePushDevice, is not a path swap. It is an ordered installation protocol with two more required headers:

  • X-Push-Installation-Key: a secret 32-byte key in unpadded base64url (43 characters). It is persisted per server and device installation, kept across account and profile switches, and never rotated.
  • X-Push-Generation: a positive decimal int64. It increases strictly for each new registration intent and is reused exactly, with the same body and owner, after an uncertain outcome.

The server keys the installation by device_id. It answers 403 when the key does not match the one it stored, and 409 when the generation goes backwards or reuses a generation for a different intent. The contract has no automatic recovery for a lost key or a reset counter.

On main, APIv2Client.registerApplePush and applePushRegistrationCapability had no callers. Nothing generated, stored or sent a key or a generation. The coordinator also had a v1-only 404/405 fallback (endpointUnsupportedForContext).

Solution

  • Journal (Notifications/ApplePushInstallationJournal.swift): one Keychain item per server registry ID. It holds the installation key and the latest intent with its generation and outcome (pending, accepted, or refused). An intent is the durable owner (server, verified account ID, account epoch, profile) plus the exact request body. The item uses the same Keychain group and accessibility as the device ID from AppleDeviceIdentity, so the two are kept or lost together. A missing item gets a fresh key, but only on its first allocation. An unreadable or undecodable item is never overwritten. Registration for that server stops, and the reason is logged.
  • Allocation and replay (ApplePushInstallationJournal.plan):
    • A new intent takes the next generation, for example after an APNs token, account, login or profile change. The record is written inside TokenStore.withCurrentDurableAuthority, before the request is sent, so a generation is never allocated for an owner that has already been replaced.
    • A pending intent is replayed with the same key, generation and body bytes. The encoder sorts keys, so the bytes match.
    • An accepted, active intent is replayed only to renew the display token.
    • A refused intent, or an accepted intent that is disabled or removed, is not sent again.
    • A held generation (after a 403, a refused renewal, or an accepted registration with no display token) is not sent again for six hours. The hold is in memory, so a relaunch also retries.
    • A newer intent supersedes a pending one. This is safe on the server whether or not the pending one landed, because a late lower generation gets 409.
  • Registrar (ApplePushRegistrar, an actor in ApplePushRegistration.swift): checks the body against the ApplePushRegistrationBody schema before allocating, so a build with another bundle ID never uses up a generation. Next it reads the capability and requires allowed, state == "available" and registration_available. The revision stays opaque, so the legacy ordered_apple_v1 comparison is not used. Then it sends the registration and records the outcome. The actor keeps Keychain I/O off the main actor.
  • Transport (APIv2Client.registerApplePush): sends both ordered headers. HTTPClient adds X-Profile-Id, and X-Profile-Token for PIN-locked profiles, from the captured owner. The existing withOwnerFence in applePushRequest guards both calls. The client throws ApplePushRegistrationError.invalidReceipt unless the receipt names the sent generation and push mode and has non-empty id and server_device_id.
  • Display token: stored or cleared inside withCurrentDurableAuthority, in the same TokenStore turn as the owner check. A late answer therefore cannot write into a slot that a sign-out or profile switch already cleared. On main, the write ran after the fence returned. A disabled or removed registration clears the token. hasCurrentToken(forServerID:) now also checks which server issued the token. The six-hour back-off for servers that return no token stays, and now also covers 403s and refused renewals.
  • Coordinator: captures TokenStore.captureDurableAccountAuth(). A call that arrives while a registration is running queues one more pass, so two sends never race for a generation.
  • Deleted: the v1 endpoint constant, the v1 request/response models, the process-lifetime fingerprint dedupe, the 404/405 fallback, and the v1 receipt decode test. APIv2ApplePushRegistration and the nested ApplePushCapability moved into APIv2PushModels.swift as APIv2ApplePushRegistrationReceipt and APIv2ApplePushCapability (all four schema fields).

The Android reference is AndroidPushRegistrar.kt:15-123. This differs from Android in two ways:

  • After an uncertain send, a changed intent takes the next generation. Android first replays the pending intent. If the owner differs, Android refuses to register at all.
  • A refusal blocks only that exact intent. Android persists a stopped state. Both choices avoid the permanent per-scope block from audit F8, and the legacy blockedScopes journal was not harvested.

Failure outcomes

registerApplePushDevice is x-silo-retry-safety: domain_identity. The contract (docs/notifications-push-api.md) asks for an exact replay after uncertainty and forbids a new generation just to retry.

Outcome Examples Behavior
Definite success 200 with a receipt for the sent generation and push mode Journal records accepted with the registration ID, enabled and removed. The display token is stored, or cleared when the registration is disabled or removed. A later trigger sends nothing unless the display token needs renewal.
Definite failure, intent refused 400, 404, 406, 409 (generation or ownership conflict), 413, 415, 422, or a 200 receipt for another generation or mode, on a new or pending intent; 409 on a renewal Journal records refused with the status and problem type, and the real error is logged once. The same intent is never resent. The next changed intent takes the next generation with the same key. No rebase, no new key.
Refused, no verdict on the intent (held) 403 on any send: the server answers permission_denied both for a bad installation proof and for a login-authority check that can fail transiently (a 2-second lookup timeout, an access token that expires during the lock wait, a stale role claim). Any refusal of a display-token renewal other than 409, including an invalid receipt Journal is unchanged: a pending intent stays pending, an accepted one stays accepted, because the server never changes a registration for an exact replay. The generation is held in memory for six hours, then the same key, generation and body are sent again. A changed intent takes the next generation right away.
Definite failure, nothing sent The body breaks the schema, the capability is unavailable or its read failed, the journal can't be read, the allocation can't be written, or the owner was replaced before allocation No generation is allocated, or the allocated one is never sent. The reason is logged. The next trigger starts over.
Uncertain Transport failure or timeout; 401 after the refresh retry; 408, 410, 429, 5xx; the owner changed while in flight (authorityChanged) The intent stays pending with its generation. No display token is written. The next trigger under the same durable owner replays it exactly. A new intent supersedes it with the next generation.

Lost key. The record and the device ID share one Keychain group and accessibility, so a Keychain reset normally loses both. The server then sees a new device ID, which counts as a new installation. If only the record is lost, every later registration for this device on that server fails with 403, or with 409 when the generation falls behind. The client records a 409 as a refusal. It holds a 403 and retries it every six hours (or on relaunch), because the server uses the same problem type for a transient login-authority failure. It does not guess replacement credentials. If the record exists but cannot be read or decoded, the client leaves it in place and sends nothing for that server. The Notification Service extension falls back to the access token for display fetches. Recovery needs a server-side way to drop this device's installation. No v2 operation for that exists for Apple.

Validation

  • iOS, tvOS and macOS builds pass on this branch.
  • Focused iOS tests pass: ApplePushOrderedRegistrationTests (19 tests), ApplePushRegistrationTests, CredentialIdentityTests and APIv2ContractTests, 0 failures. Push code is iOS-only: the new test file compiles to nothing on tvOS, and ApplePushRegistrationTests is excluded from SiloTVTests. On tvOS, CredentialIdentityTests and APIv2ContractTests pass (34 tests).
  • scripts/ci/check-no-api-v1.sh passes. ApplePushRegistration.swift no longer contains a v1 path. The one v1 literal left in ApplePushRegistrationTests.swift is the display URL test, which W5-U owns.
  • The final stack passed the full suites (iOS 1981 tests, tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.
  • New tests (ApplePushOrderedRegistrationTests, on StubURLProtocol with a real TokenStore and HTTPClient) cover:
    • Wire shape: exact snake_case body, a 43-character key, generation "1", and X-Profile-Id/X-Profile-Token.
    • No request for an accepted intent that already has a current display token.
    • Exact replay (same key, generation and body bytes) after a lost answer, with a fresh registrar standing in for a restart.
    • The next generation with the same key after a token change or a profile switch.
    • 409 and 422 recorded as refusals and not resent. A changed intent afterwards takes the next generation.
    • A 403 leaves the intent pending, sends nothing during the hold, and replays the same key, generation and body after it (injected clock).
    • A 403 on a display-token renewal keeps the journal accepted, and the renewal is sent again after the hold. A 409 on a renewal is recorded as a refusal.
    • 503 keeps the intent pending.
    • A receipt for another generation is refused and stores no display token.
    • An unavailable capability allocates nothing.
    • An unreadable journal is neither sent nor overwritten.
    • A non-contract topic uses up no generation.
    • A removed registration on renewal clears the display token and is not renewed again.
    • An owner change in flight stores no display token and leaves the intent pending.
    • Key format and generation exhaustion.
  • APNs delivery needs a real device, so these results are compile and unit evidence only. Nobody ran the app against a live server.

Risks and follow-ups

  • The installation key lives in the shared Keychain access group (SharedStorage.keychainAccessGroup, user-independent audience), the same group that holds the account tokens and the device ID. Every app and extension in that group can read it; it is not an app-private item.
  • The coordinator requires captureDurableAccountAuth(), which needs a verified account ID on the session. W1-B (restore validation through account/me) and W5-A (binding from TokenPair.user.id), earlier in the stack, supply it; a session installed without one does not register. Temporary playback credentials never register, as before.
  • The journal is keyed by the registry server ID, which is derived from the URL. The server keys installations by device_id alone. Two registry entries for one deployment (for example LAN and public addresses) get two keys, so the second one to register gets 403 and is held and retried every six hours. Registration still works from the first address. verifiedServerId is self-asserted and never authorizes anything, so it is not used to share a secret. Android keys by server URL in the same way. A follow-up could share the record across entries once the deployment identity is verified.
  • First v2 registration on a device that has a v1 registration for a different account is refused with 409 by the server's bootstrap rule. It stays refused until the intent changes (a new token, login or profile).
  • A real installation-proof 403 costs one request per six hours or per relaunch, because the client cannot tell it from a transient login-authority 403. Cross-repo note, not published: Android (AndroidPushRegistrar.kt:115) records 401 and 403 as durable refusals and has the same problem. The server could give ErrPushInstallationProof its own problem type so clients can refuse it durably.
  • A refusal blocks only that exact intent. After a 409 caused by a counter behind the server, each new intent advances the counter by one, with no rebase. That follows the contract's rule of no automatic recovery.
  • The push methods stay in APIv2Client.swift, inside the existing iOS-only block where main already had them, instead of moving to an APIv2Client+Push.swift extension. New wire models are in APIv2PushModels.swift.
  • Fence count: the lines matching withOwnerFence|sameCredentialIdentity in iosApp/iosApp drop from 69 to 67 on the stacked branch: one call and one comment that described it. The call moved from the coordinator into the existing applePushRequest fence, which now guards both push calls. The path also gains two withCurrentDurableAuthority checks (1 to 3 in the tree), one for the allocation write and one for the display-token write.
  • W5-U (display fetch) is next in this lane. S9, whether display tokens minted through v1 work on the v2 display route, is still open.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 45 of 50 in the Apple API v2 stack. Base: apiv2-stack/44-subtitle-ai-jobs-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: e4e0ed5b-b34c-4791-a582-f71d96c68b30

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:23:56.218416Z 5f61261 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 308d4ae2 (apiv2-stack/45-apple-push-registration-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • major: A refused display-token renewal overwrites a working accepted registration with refused, so the token is never renewed again
  • major: Every 403 counts as a permanent refusal, but the server also answers 403 for transient login-authority failures
    Refuted or unconfirmed after verification: 1 (not acted on).

Known deviation from the plan: the push installation key is stored in the shared Keychain access group, the same group that already holds the account tokens. Moving it to an app-only group would need a new entitlement and a migration, with no practical security gain.

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@Quick104
Quick104 force-pushed the apiv2-stack/44-subtitle-ai-jobs-v2 branch from 27dac38 to 5b65565 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/45-apple-push-registration-v2 branch from 308d4ae to 5f61261 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/44-subtitle-ai-jobs-v2 branch from 5b65565 to 6e408ef Compare September 23, 2026 13:45
Base automatically changed from apiv2-stack/44-subtitle-ai-jobs-v2 to main September 23, 2026 13:45
Quick104 and others added 3 commits September 23, 2026 09:45
The app still registered its APNs token with POST /api/v1/devices/push/apple.
The v2 operation is an ordered installation protocol: every request carries
a secret per-server installation key and a strictly increasing generation,
and a lost answer must be replayed with the same generation and body. Nothing
on main generated, stored or sent either value, and the v2 client methods had
no callers.

Register through registerApplePushDevice instead. A new Keychain journal holds
one record per server: the installation key (32 random bytes, base64url,
created once and never rotated) and the latest intent with its generation and
outcome. A new intent (APNs token, account, login or profile change) takes the
next generation, persisted in the same TokenStore turn as the owner check and
before the request is sent. A lost answer, 401, 408, 429 or 5xx keeps the
intent pending and the next trigger replays it exactly. 400, 403, 404, 406,
409, 413, 415, 422 and a receipt for another generation are recorded as
refusals and not resent; there is no generation rebase and no new key. The
capability read gates each send on allowed, state available and
registration_available. Display tokens are stored or cleared under the
durable owner, and removed or disabled registrations are not renewed.

Delete the v1 endpoint, request and response models and the v1 receipt test.

Stack-PR: W5-T
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Stack-PR: W5-T
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every 403 was recorded as a durable refusal, and so was any refusal of a
display-token renewal. The server answers 403 permission_denied both for a
bad installation proof and for a login-authority check that can fail
transiently, so one slow lookup stopped registration for the rest of the
login. A renewal is an exact replay the server never acts on, so recording
its refusal made the journal forget a working accepted registration, and
the display token was never renewed again.

A 403, and a renewal refusal other than 409, now hold the generation in
memory for six hours (the existing no-display-token back-off, now keyed per
server) and leave the journal as it was: a pending intent stays pending and
an accepted one stays accepted. After the hold the same key, generation and
body are sent again. A 409 on a renewal is still recorded as a refusal,
because the server has moved past that generation.

Stack-PR: W5-T
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/45-apple-push-registration-v2 branch from 5f61261 to 17c0244 Compare September 23, 2026 13:45
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Quick104
Quick104 merged commit a1b29f2 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/45-apple-push-registration-v2 branch September 23, 2026 13:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant