Add PKCE (Proof Key for Code Exchange) to every OAuth for iCloud flow, and use the S256 method only. PKCE ties each authorization code to the specific client request that produced it, so an intercepted code cannot be exchanged by an attacker. RFC 9700 makes PKCE mandatory for all public OAuth clients.
Why does PKCE matter for an Apple data connection?
PKCE closes the authorization-code injection gap. A public client (a single-page app, a native desktop app, or any client that cannot keep a client secret) cannot prove its identity to the token endpoint with a secret. When the authorization server redirects back to your URI with the code, a malicious app that shares a URI scheme or redirect pattern can intercept it. With the code in hand, the attacker calls the token endpoint and receives a valid access token for your user's data.
PKCE removes that opportunity. Before the authorization redirect, your client generates a one-time random string called the code verifier. It sends a hashed derivative, the code challenge, with the authorization request and keeps the verifier private. The token endpoint requires the original verifier at exchange time, derives the hash itself, and compares. Only the client that started the flow holds the verifier.
RFC 9700 states that public clients must use PKCE (RFC 9700). Use S256 exclusively. RFC 7636 is explicit: the plain method offers no protection against an observer who can read the authorization request, and exists only for constrained environments that cannot support S256 (RFC 7636). A client that falls back to plain after attempting S256 should treat that as a potential downgrade attack, not a compatibility accommodation.
Figment's OAuth for iCloud issues each app a scoped grant, and PKCE protects the authorization code for that grant. Revoking your app's grant stops that app's access and leaves other connected apps unaffected.
How do I generate a code verifier and challenge?
Encode 32 cryptographically random bytes as base64url without padding. That gives exactly 43 characters, which meets RFC 7636: a verifier of 43 to 128 characters from the unreserved set [A-Za-z0-9\-._~], with at least 256 bits of entropy.
# Untested example — test output before production use
import secrets, hashlib, base64
# 32 bytes = 256 bits; base64url without padding = 43 characters
raw = secrets.token_bytes(32)
code_verifier = base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
# S256 challenge per RFC 7636 §4.2: BASE64URL(SHA256(ASCII(code_verifier)))
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
Generate a fresh pair for each authorization attempt. Discard the verifier after a successful exchange, because keeping it longer adds exposure with no benefit.
What does the authorization request contain?
Redirect the user's browser to https://figment.so/icloud/authorize with the parameters below. Register your app and get a client_id at /icloud/developers.
| Parameter | Value | Note |
|---|---|---|
response_type | code | Required for authorization-code flow |
client_id | your app's client ID | Assigned during app registration |
redirect_uri | exact registered HTTPS URI | RFC 9700: exact string match, no wildcards |
scope | space-separated list | Available scopes: credentials:use, messages:read, messages:send, notes:read, reminders:read, and the sandbox scopes contacts:read and calendar:read; request only what your app needs |
state | random, session-bound token | Binds the callback to the initiating session |
code_challenge | base64url(SHA-256(verifier)) | Computed above |
code_challenge_method | S256 | Never plain; always include this parameter explicitly |
- Always include
code_challenge_methodexplicitly. RFC 7636 specifies that if the parameter is omitted, the server defaults toplain. SendingS256explicitly prevents an unintentional downgrade regardless of server defaults. - Redirect URI matching is strict. RFC 9700 requires exact string matching between the URI registered at app setup and the URI sent in both the authorization request and the token exchange. Register the exact URI, including scheme, host, path, and any fixed query string, and do not rely on prefix or wildcard rules. RFC 9700 allows one narrow exception: variable port numbers for
localhostredirect URIs in native apps, following RFC 8252. - Persist
statebefore you redirect. Store the value in the user's session and reject any callback where the returnedstatedoes not match. This binds the callback to the session that started the flow and rules out cross-site request forgery.
How do I exchange the code for tokens?
Post the code to the token endpoint along with the original verifier and the same redirect_uri:
# Token exchange — untested example; replace placeholders before use
POST https://figment.so/api/icloud/oauth/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=AUTHORIZATION_CODE
&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
&client_id=YOUR_CLIENT_ID
&code_verifier=CODE_VERIFIER
A successful response includes:
{
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"token_type": "Bearer",
"expires_in": 900,
"scope": "messages:read",
"connection_id": "con_..."
}
The server derives BASE64URL(SHA256(verifier)), compares it to the challenge stored with the code, and issues a token only on a match. A verifier mismatch returns an error. A second exchange of the same code returns invalid_grant, because authorization codes are single-use.
If the token exchange times out or returns an ambiguous response, treat the outcome as an error and do not silently retry. You cannot tell from the client whether the code was consumed. Restart the full authorization flow rather than reusing the code.
How long do tokens last, and how do I refresh them?
Access tokens expire after 900 seconds. Refresh tokens are separate rotating credentials. Refresh with grant_type=refresh_token, your client_id and the current refresh_token. After every refresh, store the new refresh token, and serialize refresh operations per grant to avoid concurrent invalidation. Figment tokens are opaque strings, so do not parse them as JWTs.
What happens on the Apple side?
PKCE protects your app's authorization code. The Apple account sign-in itself (trusted-device confirmation, Mac permission prompts, iCloud sync) happens inside Figment's hosted connection setup, separate from your app's OAuth flow. The developer's app never receives or stores the Apple account password.
Apple supports third-party authorization for Mail, Calendar, and Contacts through approved apps. Users can review and revoke individual grants at account.apple.com under Sign-In and Security > Account Data Sharing (Apple support). Figment's app-consent grant is distinct from that Apple-issued grant. Figment is the issuer of the app-access token and connection record.
How do I know the connection is ready for data requests?
Check the connection state, because a completed OAuth exchange does not mean data is available yet. Figment tracks state per service:
GET https://figment.so/api/icloud/v1/connections/con_.../
Authorization: Bearer ACCESS_TOKEN
The response uses the form {connection:{id, mode, services, ...}}. Each service in connection.services is an object with state, reason, and observedAt (epoch milliseconds), and only granted services appear. Possible states:
| State | What it means |
|---|---|
connecting | Initial handshake in progress |
needs_approval | A Mac permission or trusted-device step is pending |
syncing | Data indexing in progress |
ready | Service is responding to requests |
offline | Service is unreachable |
reconnect_required | Grant needs re-establishment |
revoked | Access has been revoked |
The endpoint enforces authorization and can return a non-2xx response for revoked or non-ready connections instead of a diagnostic state object, so handle non-2xx responses in your code. A ready state does not guarantee complete history or successful delivery. Use /icloud/account to view and manage setup status.
What should my PKCE and state test cover?
Run this worksheet before shipping. Each row maps a flow event to the parameter it produces and the assertion your test should make.
| Step | Action | Parameter or check | Assertion |
|---|---|---|---|
| 1 | Generate verifier | code_verifier | Length 43–128; characters in [A-Za-z0-9\-._~] only |
| 2 | Derive S256 challenge | code_challenge | Equals BASE64URL(SHA256(verifier)); no = padding |
| 3 | Authorization request | code_challenge_method | Value is S256; parameter is present; server must reject plain |
| 4 | Authorization request | state | Cryptographically random; stored in session before redirect |
| 5 | Callback received | state check | Reject if returned value does not match stored session value |
| 6 | Token exchange | code_verifier | Identical string to step 1; any altered value returns an error |
| 7 | Code reuse | second exchange attempt | Server returns invalid_grant on the second request |
| 8 | Redirect URI consistency | redirect_uri | Byte-for-byte identical in authorization request and token request |
| 9 | Connection state | GET /v1/connections/{connection_id} | connection.services.[service].state is ready before data operations proceed |
| 10 | Revocation | Apple Account Data Sharing revoke | Service state changes; check /icloud/account for current connection status |
Steps 6 and 7 together confirm that the server treats the verifier as a one-time proof and the code as single-use. If either assertion fails in staging, review the authorization server configuration before connecting real user accounts.
Where do I go next?
Register your app and start the connection flow at Connect Apple Account. For the full consent and scoping model, see OAuth for iCloud: Connect Apple Data to Your App. For framework-specific setup, see Add Connect Apple Account to a Next.js App.