### Install with npm Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Install the apple-signin-auth package using npm. ```bash npm install --save apple-signin-auth ``` -------------------------------- ### Install with yarn Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Install the apple-signin-auth package using yarn. ```bash yarn add apple-signin-auth ``` -------------------------------- ### _getApplePublicKeys usage example Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md Example of calling _getApplePublicKeys with disableCaching: true and logging the first key. ```javascript import appleSignin from 'apple-signin-auth'; const keys = await appleSignin._getApplePublicKeys({ disableCaching: true }); console.log(keys[0]); // '-----BEGIN PUBLIC KEY-----...' ``` -------------------------------- ### _setFetch usage example Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md Example of using _setFetch to route requests through a proxy and then calling getAuthorizationToken. ```javascript import appleSignin from 'apple-signin-auth'; // route all requests through a proxy, e.g. undici's ProxyAgent appleSignin._setFetch((url, init) => fetchWithProxy(url, init)); // later calls use the replaced fetch const token = await appleSignin.getAuthorizationToken(code, options); ``` -------------------------------- ### GET /auth/keys response example (JWKS JSON) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/endpoints.md Example response body for the GET /auth/keys endpoint, showing the JWKS structure with a keys array. Each key entry includes kty, kid, use, alg, n, and e fields. This response is parsed and used for id/webhook token verification. ```json { "keys": [ { "kty": "RSA", "kid": "", "use": "sig", "alg": "RS256", "n": "", "e": "", ... } ] } ``` -------------------------------- ### Basic call example Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationUrl.md Imports the default appleSignin object and calls getAuthorizationUrl with clientID, redirectUri, and scope. Because scope includes 'email', the returned URL contains response_mode=form_post. The example then redirects the user to the authorization URL. ```javascript import appleSignin from 'apple-signin-auth'; const authorizationUrl = appleSignin.getAuthorizationUrl({ clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', scope: 'email name', }); // redirect the user res.redirect(authorizationUrl); ``` -------------------------------- ### Basic refresh example Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/refreshAuthorizationToken.md Shows how to call refreshAuthorizationToken with a client secret generated by getClientSecret. The returned access_token is destructured from the result. ```javascript import appleSignin from 'apple-signin-auth'; const clientSecret = appleSignin.getClientSecret({ clientID: 'com.company.app', teamID: '4ABCDE2FGH', privateKey: process.env.APPLE_PRIVATE_KEY, keyIdentifier: 'A1B2C3D4E5', }); const { access_token } = await appleSignin.refreshAuthorizationToken(refreshToken, { clientID: 'com.company.app', clientSecret, }); ``` -------------------------------- ### Minimal verification with error handling Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyWebhookToken.md A minimal example that verifies the token and logs the event details. It catches errors and specifically handles `TokenExpiredError`. ```javascript import { verifyWebhookToken } from 'apple-signin-auth'; try { const decoded = await verifyWebhookToken(req.body.payload); console.log(decoded.events.type, decoded.events.sub, decoded.events.event_time); } catch (err) { if (err.name === 'TokenExpiredError') { // notifications should be handled promptly; the token expires quickly } console.error(err.name, err.message); } ``` -------------------------------- ### Get authorization URL with apple-signin-auth Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Starts the 'Sign in with Apple' flow by redirecting the user to the authorization URL. Requires a clientID and redirectUri; optional state, responseMode, and scope options are supported. The responseMode must be set to 'form_post' if the scope includes 'email'. ```javascript import appleSignin from 'apple-signin-auth'; // OR const appleSignin = require('apple-signin-auth'); // OR import { getAuthorizationUrl } from 'apple-signin-auth'; const options = { clientID: 'com.company.app', // Apple Client ID redirectUri: 'http://localhost:3000/auth/apple/callback', // OPTIONAL state: 'state', // optional, An unguessable random string. It is primarily used to protect against CSRF attacks. responseMode: 'query' | 'fragment' | 'form_post', // Force set to form_post if scope includes 'email' scope: 'email' // optional }; const authorizationUrl = appleSignin.getAuthorizationUrl(options); ``` -------------------------------- ### Error handling example Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationUrl.md Calls getAuthorizationUrl with an empty options object, which throws an error because clientID and redirectUri are missing. The error message is logged to the console. ```javascript try { getAuthorizationUrl({}); // missing clientID and redirectUri } catch (err) { console.error(err.message); // "clientID is empty" } ``` -------------------------------- ### GET /auth/keys Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/endpoints.md Fetches Apple's public JWKS for token verification. Used by _getApplePublicKeys. ```APIDOC ## GET /auth/keys ### Description Fetches Apple's public JWKS for token verification. Used by _getApplePublicKeys. ### Method GET ### Endpoint https://appleid.apple.com/auth/keys ### Parameters #### Headers - **Content-Type** (string) - Required - `application/json`. ### Response #### Success Response (200) JWKS-shaped JSON with a `keys` array. Each key contains `kty`, `kid`, `use`, `alg`, `n`, `e`, and other fields. #### Response Example { "keys": [ { "kty": "RSA", "kid": "", "use": "sig", "alg": "RS256", "n": "", "e": "" } ] } ``` -------------------------------- ### getAuthorizationUrl(options) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationUrl.md Builds the 'Sign in with Apple' authorization URL to start the OAuth authorization-code flow. Callers redirect the user to this URL. Returns a string containing the fully-formed authorization URL. ```APIDOC ## getAuthorizationUrl(options) ### Description Builds the ``` -------------------------------- ### GET /auth/authorize Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/endpoints.md Builds the authorization URL for the OAuth flow. The library does not fetch this endpoint; it constructs the URL for the caller to redirect the user to. ```APIDOC ## GET /auth/authorize ### Description Builds the authorization URL for the OAuth flow. The library does not fetch this endpoint; it constructs the URL for the caller to redirect the user to. ### Method GET ### Endpoint https://appleid.apple.com/auth/authorize ### Parameters #### Query Parameters - **response_type** (string) - Required - Always `code`. - **state** (string) - Required - `options.state` or `'state'`. - **client_id** (string) - Required - `options.clientID`. - **redirect_uri** (string) - Required - `options.redirectUri`. - **scope** (string) - Required - `openid` plus optional `options.scope`. - **response_mode** (string) - Optional - `form_post` if scope includes `email`, else `options.responseMode`. ### Response #### Success Response (200) User sign-in page. On success, Apple redirects to `redirect_uri` with `code` and `state`, or POSTs `form_post`. #### Response Example (No explicit response body example provided in source.) ``` -------------------------------- ### Basic verification and getting the user ID Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyIdToken.md Verifies an Apple ID token using the default import and extracts the stable, unique Apple user identifier (sub). The audience option can be a string or an array. Throws an error if the token is not verified. ```javascript import appleSignin from 'apple-signin-auth'; try { const { sub: userAppleId } = await appleSignin.verifyIdToken(tokenResponse.id_token, { audience: 'com.company.app', // client id — can also be an array }); // userAppleId is the stable, unique Apple user identifier } catch (err) { // Token is not verified console.error(err); } ``` -------------------------------- ### Revoke an access token with error handling Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/revokeAuthorizationToken.md Example of revoking an access token with error handling. It uses a try/catch block to handle network failures or missing clientID/clientSecret. The result is checked for an empty string to indicate a successful revoke. ```js import { revokeAuthorizationToken } from 'apple-signin-auth'; try { const result = await revokeAuthorizationToken(accessToken, { clientID: 'com.company.app', clientSecret, tokenTypeHint: 'access_token', }); console.log('revoked', result === '' ? '(empty body — ok)' : result); } catch (err) { // network failure or missing clientID/clientSecret console.error(err); } ``` -------------------------------- ### Verifying a notification in an Express webhook Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyWebhookToken.md Example of using `verifyWebhookToken` in an Express webhook endpoint. It verifies the token from `req.body.payload`, handles different event types, and responds with 200 on success or 500 on error. ```javascript import appleSignin from 'apple-signin-auth'; app.post('/apple-signin-webhook', async (req, res) => { try { const { events } = await appleSignin.verifyWebhookToken(req.body.payload, { audience: 'com.company.app', // client id — can also be an array }); const { sub: userAppleId, type, email } = events; // email only on email events switch (type) { case 'email-disabled': // email no longer forwarded via private relay break; case 'email-enabled': // email forwarded again break; case 'consent-revoked': // user stopped using Apple ID with this app — log them out break; case 'account-delete': // user deleted their Apple ID — user id is no longer valid break; } res.sendStatus(200); } catch (err) { // Event token is not verified console.error(err); res.sendStatus(500); } }); ``` -------------------------------- ### Revoke a refresh token on sign-out Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/revokeAuthorizationToken.md Example of revoking a refresh token on sign-out. It generates a client secret using getClientSecret and then calls revokeAuthorizationToken with the refresh token. On success, the promise resolves to an empty string. ```js import appleSignin from 'apple-signin-auth'; const clientSecret = appleSignin.getClientSecret({ clientID: 'com.company.app', teamID: '4ABCDE2FGH', privateKey: process.env.APPLE_PRIVATE_KEY, keyIdentifier: 'A1B2C3D4E5', }); await appleSignin.revokeAuthorizationToken(refreshToken, { clientID: 'com.company.app', clientSecret, tokenTypeHint: 'refresh_token', }); // resolves to '' on success ``` -------------------------------- ### Source directly (ES6) import Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Import the apple-signin-auth package directly from the source directory as per the README. ```javascript import appleSignin from 'apple-signin-auth/src'; ``` -------------------------------- ### Using state and an explicit response mode Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationUrl.md Imports the named getAuthorizationUrl function and passes state and responseMode. Since scope does not include 'email', the responseMode 'query' is used. The comment shows the resulting URL with percent-encoded redirect_uri and scope. ```javascript import { getAuthorizationUrl } from 'apple-signin-auth'; const authorizationUrl = getAuthorizationUrl({ clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', state: crypto.randomUUID(), responseMode: 'query', // used because scope has no 'email' scope: 'name', }); // => https://appleid.apple.com/auth/authorize? // response_type=code&state=...&client_id=com.company.app& // redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fapple%2Fcallback& // scope=openid+name&response_mode=query ``` -------------------------------- ### Reading the key from a file and handling validation errors Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getClientSecret.md Generates a client secret by reading the private key from a file using privateKeyPath. Catches errors, specifically handling the "Can't find private key" error and logging other validation errors like "teamID is empty". On filesystem-less runtimes like Cloudflare Workers, use privateKey instead of privateKeyPath. ```javascript import { getClientSecret } from 'apple-signin-auth'; import fs from 'node:fs'; try { const secret = getClientSecret({ clientID: 'com.company.app', teamID: '4ABCDE2FGH', keyIdentifier: 'A1B2C3D4E5', privateKeyPath: '/path/to/AuthKey_A1B2C3D4E5.p8', }); console.log('client secret ready:', secret.slice(0, 20) + '…'); } catch (err) { if (err.message === "Can't find private key") { console.error('Key file missing — check privateKeyPath'); } else { console.error(err.message); // e.g. "teamID is empty" } } ``` -------------------------------- ### _getApplePublicKeys Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/errors.md Promise rejects on fetch/parse errors. No Apple error bodies are returned; errors relate to JWKS malformation. ```APIDOC ## _getApplePublicKeys ### Description Promise rejects on fetch/parse errors. No Apple error bodies are returned; errors relate to JWKS malformation. ### Error Delivery - **Type**: promise rejects (fetch/parse) - **Apple error bodies**: n/a (JWKS malformation) ``` -------------------------------- ### With PKCE and Apple-side error handling Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationToken.md Uses named import getAuthorizationToken with a codeVerifier for PKCE. Wraps the call in try/catch for input-validation or network errors, but notes that Apple's own error responses (e.g., invalid_grant) resolve with the parsed body instead of rejecting, so you must check for res.error. ```javascript import { getAuthorizationToken } from 'apple-signin-auth'; try { const tokenResponse = await getAuthorizationToken(code, { clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', clientSecret, codeVerifier: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', // PKCE }); console.log(tokenResponse.access_token); } catch (err) { // Only input-validation errors (clientID/clientSecret empty) // or network/JSON errors reach here. console.error(err); } // NOTE: Apple's own error responses (e.g. invalid_grant) resolve with the // parsed body instead of rejecting: const res = await getAuthorizationToken(code, { clientID, clientSecret }); if (res.error) { // { error: 'invalid_grant', error_description: '...' } console.error(res.error_description); } ``` -------------------------------- ### Basic call with inline private key Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getClientSecret.md Generates a client secret using an inline private key from an environment variable, then uses it to obtain an authorization token. The private key must be an EC P-256 key (ES256). The exp defaults to iat + 300 seconds, and Apple requires expiry no more than 6 months (15777000 seconds) in the future. ```javascript import appleSignin from 'apple-signin-auth'; const clientSecret = appleSignin.getClientSecret({ clientID: 'com.company.app', teamID: '4ABCDE2FGH', // Apple Developer Team ID privateKey: process.env.APPLE_PRIVATE_KEY, // PEM string keyIdentifier: 'A1B2C3D4E5', // key ID from the developer console // expAfter: 15777000, // optional, defaults to 300 (5 min) }); const tokenResponse = await appleSignin.getAuthorizationToken(code, { clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', clientSecret, }); ``` -------------------------------- ### CommonJS require import Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Import the apple-signin-auth package using CommonJS require. ```javascript const appleSignin = require('apple-signin-auth'); ``` -------------------------------- ### ESM default import Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Import the apple-signin-auth package using ES module default import. ```javascript import appleSignin from 'apple-signin-auth'; ``` -------------------------------- ### Inject custom fetch with _setFetch Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/configuration.md Replaces the default fetch implementation used for all HTTP calls. The injected function receives the URL and init object and must return a fetch-compatible Promise. This is useful for proxies or custom network handling. ```javascript import appleSignin from 'apple-signin-auth'; appleSignin._setFetch((url, init) => myProxiedFetch(url, init)); // all subsequent HTTP calls use the replacement ``` -------------------------------- ### _populateResAsJson implementation (private) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md Implementation of the private _populateResAsJson function, which parses response text as JSON or returns the raw string if empty. ```javascript const _populateResAsJson = async (res: { text(): Promise }) => { const data = await res.text(); if (!data) { return data; } return JSON.parse(data); }; ``` -------------------------------- ### With nonce and expiration handling Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyIdToken.md Verifies an Apple ID token using a named import, with an array of audiences and a nonce that must match the one sent in the authorization request. Handles TokenExpiredError separately, otherwise logs the error message. ```javascript import { verifyIdToken } from 'apple-signin-auth'; try { const decoded = await verifyIdToken(idToken, { audience: ['com.company.app', 'com.company.app.service'], nonce: 'NONCE', // must match the nonce sent in the authorization request }); console.log(decoded.email, decoded.email_verified, decoded.is_private_email); } catch (err) { if (err.name === 'TokenExpiredError') { // handled separately, or call refreshAuthorizationToken } else { console.error('invalid token:', err.message); } } ``` -------------------------------- ### Cloudflare Workers wrangler.toml configuration Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Enable the nodejs_compat flag and set a recent compatibility_date for Cloudflare Workers to support apple-signin-auth. ```toml # wrangler.toml compatibility_date = "2024-09-23" compatibility_flags = ["nodejs_compat"] ``` -------------------------------- ### getClientSecret Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/errors.md Synchronously throws errors; no HTTP involved. No Apple error bodies are returned. ```APIDOC ## getClientSecret ### Description Synchronously throws errors; no HTTP involved. No Apple error bodies are returned. ### Error Delivery - **Type**: synchronous `throw` - **Apple error bodies**: n/a (no HTTP) ``` -------------------------------- ### getAuthorizationUrl Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/errors.md Synchronously throws errors; no HTTP involved. No Apple error bodies are returned. ```APIDOC ## getAuthorizationUrl ### Description Synchronously throws errors; no HTTP involved. No Apple error bodies are returned. ### Error Delivery - **Type**: synchronous `throw` - **Apple error bodies**: n/a (no HTTP) ``` -------------------------------- ### apple-signin-auth API Functions Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Code snippets for each exported function of the apple-signin-auth module. ```APIDOC ## getAuthorizationUrl ### Description Builds the "Sign in with Apple" authorization URL. ### Method Function ### Signature `getAuthorizationUrl(options)` ### Parameters - **options** (object) - Required - Configuration for the authorization URL. ### Returns - **string** - The authorization URL. ``` ```APIDOC ## getClientSecret ### Description Generates the ES256 client secret JWT. ### Method Function ### Signature `getClientSecret(options)` ### Parameters - **options** (object) - Required - Configuration for the client secret. ### Returns - **string** - The client secret JWT. ``` ```APIDOC ## getAuthorizationToken ### Description Exchanges an authorization `code` for tokens. ### Method Function ### Signature `getAuthorizationToken(code, options)` ### Parameters - **code** (string) - Required - The authorization code. - **options** (object) - Required - Configuration for the token exchange. ### Returns - **Promise** - The token response. ``` ```APIDOC ## refreshAuthorizationToken ### Description Refreshes an expired access token. ### Method Function ### Signature `refreshAuthorizationToken(refreshToken, options)` ### Parameters - **refreshToken** (string) - Required - The refresh token. - **options** (object) - Required - Configuration for the refresh. ### Returns - **Promise** - The refreshed token response. ``` ```APIDOC ## revokeAuthorizationToken ### Description Revokes a refresh or access token. ### Method Function ### Signature `revokeAuthorizationToken(token, options)` ### Parameters - **token** (string) - Required - The token to revoke. - **options** (object) - Required - Configuration for the revocation. ### Returns - **Promise** - Resolves when the token is revoked. ``` ```APIDOC ## verifyIdToken ### Description Verifies the user's id token signature and claims. ### Method Function ### Signature `verifyIdToken(idToken, options)` ### Parameters - **idToken** (string) - Required - The id token to verify. - **options** (object) - Required - Verification options. ### Returns - **Promise** - The verified token claims. ``` ```APIDOC ## verifyWebhookToken ### Description Verifies Apple server-to-server notification tokens. ### Method Function ### Signature `verifyWebhookToken(token, options)` ### Parameters - **token** (string) - Required - The webhook token to verify. - **options** (object) - Required - Verification options. ### Returns - **Promise** - The verified token claims. ``` ```APIDOC ## _getApplePublicKeys ### Description Fetches and PEM-encodes Apple's public JWKS keys. This is an internal function exposed for advanced use. ### Method Function ### Signature `_getApplePublicKeys()` ### Parameters None. ### Returns - **Promise>** - The PEM-encoded public keys. ``` ```APIDOC ## _setFetch ### Description Replaces the `fetch` implementation used for all HTTP calls. This is an internal function exposed for advanced use. ### Method Function ### Signature `_setFetch(fetchImpl)` ### Parameters - **fetchImpl** (function) - Required - The new fetch implementation. ### Returns - **void** ``` -------------------------------- ### TypeScript declaration Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyWebhookToken.md The TypeScript declaration for `verifyWebhookToken`. ```typescript declare function verifyWebhookToken( /** payload provided by Apple server-to-server notification */ webhookToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options?: {}, ): Promise; ``` -------------------------------- ### _getApplePublicKeys signature (JavaScript) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md Signature of the _getApplePublicKeys function, which fetches Apple's public JWKS and returns PEM-encoded keys. Accepts an optional options object with disableCaching. ```javascript const _getApplePublicKeys = async ({ disableCaching, }: { disableCaching?: boolean } = {}): Promise> => { ``` -------------------------------- ### Handling both validation and Apple errors Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/refreshAuthorizationToken.md Shows how to handle both validation errors (missing clientID/clientSecret) and Apple-side errors. Apple errors resolve with an error property, while network or validation errors reject. ```javascript import { refreshAuthorizationToken } from 'apple-signin-auth'; try { const res = await refreshAuthorizationToken(refreshToken, { clientID: 'com.company.app', clientSecret, }); if (res.error) { // Apple rejected the refresh token console.error(res.error, res.error_description); // invalid_grant // -> prompt the user to sign in again } else { // rotate the stored refresh token refreshToken = res.refresh_token; } } catch (err) { // network failure or missing clientID/clientSecret console.error(err); } ``` -------------------------------- ### Function signature (JavaScript) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyWebhookToken.md The async function signature for `verifyWebhookToken`. It takes a `webhookToken` string and an optional `options` object, returning a Promise of `AppleWebhookTokenType`. ```javascript const verifyWebhookToken = async ( /** payload provided by Apple server-to-server notification */ webhookToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options: Object = {}, ): Promise => ``` -------------------------------- ### POST /apple-signin-webhook Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Webhook endpoint for receiving Apple server-to-server notifications about user lifecycle events. The endpoint expects a POST request with a JSON body containing a JWT payload, which must be verified using the appleSignin.verifyWebhookToken function. ```APIDOC ## [POST] /apple-signin-webhook ### Description Receives server-to-server notifications from Apple about user lifecycle events such as email-disabled, email-enabled, consent-revoked, and account-delete. The request body contains a JWT payload that must be verified. ### Method POST ### Endpoint /apple-signin-webhook ### Request Body - **payload** (string) - Required - The server-to-server notification JWT. ### Request Example { "payload": "" } ### Response #### Success Response (200) - Status 200 indicates successful receipt and verification. #### Error Response (500) - Status 500 indicates verification failure or processing error. ### Notes - TLS 1.2 is required to receive notifications at the specified endpoint. - The webhook URL must be configured in the Apple Developer console under the Primary App ID's "Server to Server Notification Endpoint". ``` -------------------------------- ### _setFetch signature (JavaScript) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md Signature of the _setFetch function, which replaces the module-level fetch function. ```javascript const _setFetch = (fetchFn: Function) => { fetch = fetchFn; }; ``` -------------------------------- ### Default export for ES5 compatibility Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Provides a default export object containing the same nine functions for backwards compatibility with ES5. ```javascript /* For backwards compatibility with es5 */ export default { getAuthorizationUrl, getClientSecret, getAuthorizationToken, refreshAuthorizationToken, revokeAuthorizationToken, verifyIdToken, verifyWebhookToken, // Internals - exposed for hacky people _getApplePublicKeys, _setFetch, }; ``` -------------------------------- ### Basic exchange with apple-signin-auth Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationToken.md Exchanges an authorization code for tokens using the default import. Generates a client secret, calls getAuthorizationToken, then verifies the ID token to obtain the user's Apple ID (sub). ```javascript import appleSignin from 'apple-signin-auth'; const clientSecret = appleSignin.getClientSecret({ /* ... */ }); const tokenResponse = await appleSignin.getAuthorizationToken(code, { clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', clientSecret, }); // tokenResponse.access_token, tokenResponse.id_token, // tokenResponse.refresh_token, tokenResponse.expires_in const { sub: userAppleId } = await appleSignin.verifyIdToken(tokenResponse.id_token, { audience: 'com.company.app', }); ``` -------------------------------- ### appleSigninAuth._setFetch Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/README.md Sets the fetch function used for network requests. Defaults to native Node.js fetch. ```APIDOC ## appleSigninAuth._setFetch ### Description Sets the fetch function used for network requests. Defaults to native Node.js fetch. ### Method Function ### Parameters - **fetchFn** (function) - Required - The fetch function to use, e.g., `fetchWithProxy`. ### Returns - **void** ``` -------------------------------- ### getClientSecret Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getClientSecret.md Generates a client secret (JWT) for Apple Sign In. Accepts options including clientID, teamID, privateKey or privateKeyPath, and keyIdentifier. Returns a JWT string. ```APIDOC ## getClientSecret ### Description Generates a client secret (JWT) for Apple Sign In. Accepts options including clientID, teamID, privateKey or privateKeyPath, and keyIdentifier. Returns a JWT string. ### Method Function ### Endpoint N/A (SDK function) ### Parameters #### Options Object - **clientID** (string) - Required - Your Apple app's bundle ID or service ID. - **teamID** (string) - Required - Your Apple Developer Team ID. - **privateKey** (string) - Optional - The private key as a PEM string. Required if privateKeyPath is not provided. - **privateKeyPath** (string) - Optional - Path to the private key file (.p8). Required if privateKey is not provided. - **keyIdentifier** (string) - Required - The key ID from the Apple Developer console. - **expAfter** (number) - Optional - Expiration time in seconds from now. Defaults to 300 (5 minutes). ### Request Example ```js import appleSignin from 'apple-signin-auth'; const clientSecret = appleSignin.getClientSecret({ clientID: 'com.company.app', teamID: '4ABCDE2FGH', privateKey: process.env.APPLE_PRIVATE_KEY, keyIdentifier: 'A1B2C3D4E5', }); ``` ### Response #### Success Response Returns a JWT string (client secret). #### Response Example ```js const clientSecret = appleSignin.getClientSecret({ ... }); // clientSecret is a string like 'eyJhbGciOiJFUzI1NiIs...' ``` ### Notes - The private key must be an EC P-256 key (ES256). - On filesystem-less runtimes (e.g., Cloudflare Workers), always pass `privateKey`, never `privateKeyPath`. - `exp` defaults to `iat + 300` seconds. Apple requires expiry no more than 6 months (15777000 seconds) in the future. - The `teamId` alias exists only in the Flow source; the TypeScript declaration accepts only `teamID`. ``` -------------------------------- ### _getApplePublicKeys TypeScript declaration Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md TypeScript declaration for _getApplePublicKeys, showing the function signature and return type. ```typescript declare function _getApplePublicKeys(options?: { disableCaching?: boolean; }): Promise; ``` -------------------------------- ### getAuthorizationToken(code, options) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationToken.md Exchanges an authorization code for Apple tokens. Supports optional PKCE code verifier. Note that Apple's error responses resolve with the parsed body instead of rejecting. ```APIDOC ## getAuthorizationToken(code, options) ### Description Exchanges an authorization code for Apple tokens (access, ID, refresh). Supports optional PKCE code verifier. Apple's error responses (e.g. invalid_grant) resolve with the parsed body instead of rejecting. ### Method Function call (async) ### Endpoint N/A - SDK function ### Parameters - **code** (string) - Required - The authorization code received from Apple. - **options** (object) - Required - Configuration object. - **clientID** (string) - Required - Your Apple client ID (e.g. 'com.company.app'). - **redirectUri** (string) - Optional - Redirect URI used in the authorization request. Required by Apple for web flows; appended only when truthy. - **clientSecret** (string) - Required - The client secret generated via getClientSecret. - **codeVerifier** (string) - Optional - PKCE code verifier for PKCE flow. ### Request Example ```js const tokenResponse = await getAuthorizationToken(code, { clientID: 'com.company.app', redirectUri: 'https://example.com/auth/apple/callback', clientSecret, codeVerifier: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', // PKCE }); ``` ### Response #### Success Response - **access_token** (string) - Access token. - **id_token** (string) - ID token. - **refresh_token** (string) - Refresh token. - **expires_in** (number) - Token expiration time in seconds. #### Error Response If Apple returns an error, the response resolves with an object containing: - **error** (string) - Error code (e.g. 'invalid_grant'). - **error_description** (string) - Human-readable error description. #### Response Example ```js // Success { access_token: '...', id_token: '...', refresh_token: '...', expires_in: 3600 } // Error { error: 'invalid_grant', error_description: '...' } ``` ### Notes - Only input-validation errors (clientID/clientSecret empty) or network/JSON errors reject. - The response body is parsed by a private helper: empty bodies resolve to '', non-empty bodies are JSON.parse'd. - The fetch used is the module-level fetch (native Node 18+ by default), replaceable via _setFetch. ``` -------------------------------- ### verifyWebhookToken Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyWebhookToken.md Verifies Apple server-to-server notification tokens and returns the decoded token with the events claim parsed into an object. ```APIDOC ## verifyWebhookToken ### Description Verifies Apple server-to-server notification tokens (sent to your webhook as `payload` in a `POST` request body) and returns the decoded token with the `events` claim parsed into an object. ### Signature ```js const verifyWebhookToken = async ( /** payload provided by Apple server-to-server notification */ webhookToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options: Object = {}, ): Promise => ``` TypeScript declaration: ```ts declare function verifyWebhookToken( /** payload provided by Apple server-to-server notification */ webhookToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options?: {}, ): Promise; ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `webhookToken` | `string` | yes | — | The `payload` string from the server-to-server notification `POST` body (`{ "payload": "" }`) | | `options` | `Object` | no | `{}` | JWT verify options, spread over the defaults below (`src/index.js:401`) | ### Defaults merged under the hood (`src/index.js:396-404`) ```js { algorithms: ['RS256'], issuer: ENDPOINT_URL, // 'https://appleid.apple.com' ...options, } ``` Common `options`: `audience` (your client id, can also be an array), `ignoreExpiration`, `clockTolerance`. ### Return value `Promise` — the decoded token with the `events` claim JSON-parsed into an object (`src/index.js:405-408`): ```js resolve({ ...decoded, events: JSON.parse(decoded.events) }); ``` | Field | Type | Description | |---|---|---| | `iss` | `string` | `https://appleid.apple.com` | | `aud` | `string` | your `client_id` | | `exp` | `string` | expiry (typically ~5 minutes) | | `iat` | `string` | issued-at time | | `jti` | `string` | unique token identifier | | `events` | `AppleWebhookTokenEventType` | parsed event object: `{ type, sub, event_time, email?, is_private_email? }` | `events.type` is one of `'email-disabled' | 'email-enabled' | 'consent-revoked' | 'account-delete'`. See [types.md](/workspace/home/output/types.md). ### Rejects Same rejection modes as `verifyIdToken` (shared key-resolution path): `JsonWebTokenError` for bad signature/audience/issuer/kid mismatch, `TokenExpiredError`, `NotBeforeError`, `Error('input error: Invalid id token public key id')` when no `kid` and key resolution fails. Note the `events` claim is `JSON.parse`d *after* verification succeeds — a `JSON.parse` error would reject as a `SyntaxError` if Apple emitted a malformed `events` claim. Full catalog: [errors.md](/workspace/home/output/errors.md). ### Examples #### Verifying a notification in an Express webhook ```js import appleSignin from 'apple-signin-auth'; app.post('/apple-signin-webhook', async (req, res) => { try { const { events } = await appleSignin.verifyWebhookToken(req.body.payload, { audience: 'com.company.app', // client id — can also be an array }); const { sub: userAppleId, type, email } = events; // email only on email events switch (type) { case 'email-disabled': // email no longer forwarded via private relay break; case 'email-enabled': // email forwarded again break; case 'consent-revoked': // user stopped using Apple ID with this app — log them out break; case 'account-delete': // user deleted their Apple ID — user id is no longer valid break; } res.sendStatus(200); } catch (err) { // Event token is not verified console.error(err); res.sendStatus(500); } }); ``` #### Minimal verification with error handling ```js import { verifyWebhookToken } from 'apple-signin-auth'; try { const decoded = await verifyWebhookToken(req.body.payload); console.log(decoded.events.type, decoded.events.sub, decoded.events.event_time); } catch (err) { if (err.name === 'TokenExpiredError') { // notifications should be handled promptly; the token expires quickly } console.error(err.name, err.message); } ``` ### Notes - The incoming notification is a `POST` whose JSON body contains a single `payload` field holding the JWT (README). - TLS 1.2 is required on the webhook endpoint to receive notifications (README). - A server-to-server webhook can only be configured for a Primary App ID in the Apple Developer console. ``` -------------------------------- ### verifyIdToken(idToken, options?) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyIdToken.md Verifies the signature and claims of an Apple id token and returns the user's identity payload. Uses jsonwebtoken's jwt.verify with a getKey callback that resolves Apple's public keys dynamically. ```APIDOC ## verifyIdToken(idToken, options?) ### Description Verifies the signature and claims of an Apple id token (from `getAuthorizationToken`'s `id_token` field) and returns the user's identity payload. Uses `jsonwebtoken`'s `jwt.verify` with a getKey callback that resolves Apple's public keys dynamically. ### Method async function ### Signature ```js const verifyIdToken = async ( /** id_token provided by Apple post Auth */ idToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options: Object = {}, ): Promise => ``` TypeScript declaration: ```ts declare function verifyIdToken( /** id_token provided by Apple post Auth */ idToken: string, /** JWT verify options - Full list here https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ options?: {}, ): Promise; ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `idToken` | `string` | yes | — | The id token returned by Apple after authorization | | `options` | `Object` | no | `{}` | JWT verify options, spread over the library's hardcoded defaults | ### Defaults merged under the hood ```js { algorithms: ['RS256'], issuer: ENDPOINT_URL, // 'https://appleid.apple.com' ...options, } ``` `options` are spread last, so caller values win. Common `options` (from the README and `jsonwebtoken` docs): | Option | Type | Meaning | |---|---|---| | `audience` | `string \| string[]` | Client ID(s) the token's `aud` must match; essential in practice | | `nonce` | `string` | Value the `nonce` claim must match (mitigates replay attacks) | | `ignoreExpiration` | `boolean` | If `true`, expired tokens verify (default `false`) | | `clockTolerance` | `number` | Seconds of leeway when comparing `exp`/`nbf` | ### Returns `Promise` - The user's identity payload. ``` -------------------------------- ### verifyIdToken(token, options) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/verifyIdToken.md Verifies an Apple ID token. Returns a promise that resolves to the decoded token payload. The token's signature is checked against Apple's public keys. ```APIDOC ## verifyIdToken(token, options) ### Description Verifies an Apple ID token. Returns a promise that resolves to the decoded token payload. The token's signature is checked against Apple's public keys fetched from `https://appleid.apple.com/auth/keys`. ### Method Function call ### Endpoint N/A - SDK function ### Parameters #### token (string) - Required The Apple ID token (id_token) to verify. #### options (object) - Optional Configuration options for verification. - **audience** (string | string[]) - Required - The client ID(s) that the token was issued for. Can be a string or an array of strings. - **nonce** (string) - Optional - The nonce value that must match the nonce sent in the authorization request. ### Request Example ```js import appleSignin from 'apple-signin-auth'; const { sub: userAppleId } = await appleSignin.verifyIdToken(tokenResponse.id_token, { audience: 'com.company.app', // client id — can also be an array }); ``` ### Response #### Success Response Resolves to the decoded token payload (object). Contains fields such as `sub` (user identifier), `email`, `email_verified`, `is_private_email`. #### Response Example ```js const decoded = await verifyIdToken(idToken, { audience: ['com.company.app', 'com.company.app.service'], nonce: 'NONCE', }); console.log(decoded.email, decoded.email_verified, decoded.is_private_email); ``` ### Error Handling - If the token is invalid, the promise rejects with an error. - If the token is expired, the error has `name === 'TokenExpiredError'`. ### Notes - Signature is checked against Apple's live public keys, fetched from `https://appleid.apple.com/auth/keys` and PEM-encoded with Node's built-in `crypto.createPublicKey` (JWK → SPKI PEM). - The key corresponding to the header `kid` is fetched and used for verification. ``` -------------------------------- ### Handle getAuthorizationToken error field Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/errors.md For token/revoke endpoints, treat error fields as expected states rather than exceptions. Check res.error and log res.error_description (e.g., invalid_grant) or use res.access_token on success. ```js const res = await appleSignin.getAuthorizationToken(code, options); if (res.error) { console.error(res.error, res.error_description); // e.g. invalid_grant } else { console.log(res.access_token); } ``` -------------------------------- ### Function signature (JavaScript) Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/getAuthorizationUrl.md The JavaScript implementation signature of getAuthorizationUrl. It accepts an options object with clientID, redirectUri, responseMode, state, and scope. The function returns a string. ```javascript const getAuthorizationUrl = (options?: { clientID: string, redirectUri: string, responseMode?: 'query' | 'fragment' | 'form_post', state?: string, scope?: string, }): string => { ``` -------------------------------- ### Named exports from src/index.js Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/index.md Exports the nine callable functions from the module, including internal functions for advanced use. ```javascript export { getAuthorizationUrl, getClientSecret, getAuthorizationToken, refreshAuthorizationToken, revokeAuthorizationToken, verifyIdToken, verifyWebhookToken, // Internals - exposed for hacky people _getApplePublicKeys, _setFetch, }; ``` -------------------------------- ### TypeScript declaration Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/refreshAuthorizationToken.md The TypeScript declaration for refreshAuthorizationToken, showing the same parameters and return type. ```typescript declare function refreshAuthorizationToken( refreshToken: string, options: { clientID: string; clientSecret: string; }, ): Promise; ``` -------------------------------- ### _setFetch TypeScript declaration Source: https://github.com/a-tokyo/apple-signin-auth/blob/main/_autodocs/api-reference/internal-helpers.md TypeScript declaration for _setFetch, showing the function signature and parameter type. ```typescript declare function _setFetch(fetchFn: (...args: any[]) => any): void; ```