For the first week of ClamNotes, an OpenRouter key was compiled into the app's development builds. That was fine while the only copies were the ones I installed from Xcode. It came out in the same change that prepared the first TestFlight build, because a TestFlight build is a file other people can download and open. This post is about what replaced it: a small Cloudflare Worker that holds the AI provider's keys and lets in only requests from genuine copies of the app, checked with Apple's App Attest.
None of it is specific to my app or to LLMs. If your iOS app calls any paid API with a secret, the same reasoning applies.
Why a key in the binary is a key for everyone
An App Store or TestFlight build is a signed archive. The executable is encrypted with FairPlay on disk, but the app decrypts in memory to run, and tools that dump a decrypted copy from a jailbroken device have existed for as long as the App Store has. Everything else in the bundle, Info.plist included, is not encrypted at all. From there it is strings, a hex editor or a disassembler.
Even without touching the binary, the key travels. If the app calls the provider directly, the key is in an Authorization header on every request, and a debugging proxy with its own root certificate installed on the phone reads it in plain text. Certificate pinning raises the bar, but on a device the attacker controls, pinning is just more code to patch out.
Splitting the key, XOR-ing it or fetching it at launch changes how long extraction takes, not whether it works: the app must hold the plaintext key when it makes the call. And an LLM key is a good target. It is worth money directly, works from anywhere, and the bill comes to you.
So the rule I now follow: no build that leaves my Mac contains a provider key. The keys live only in the relay's encrypted Worker secrets. The Anthropic key that writes the notes today has lived only in the relay since 11 October, the day the app switched to it.
The threat model
Moving the key to a server is the easy half. A plain proxy that adds the key and forwards whatever it receives is an open door with your key behind it. The real question is: who should the relay accept requests from?
ClamNotes has no accounts. That is a deliberate product choice, so "sign in first" was not available. What I can ask is whether the request comes from my app, unmodified, running on real Apple hardware. That is exactly the question App Attest answers. The attackers I care about:
| Who | What they want | What stops them |
|---|---|---|
| Someone who unzips the app | The provider key | There is no key in the app |
| A script calling the relay | Free LLM calls on my bill | No attested key, no token |
| A modified copy of the app | Same, with a real-looking client | App Attest won't certify a key for it |
| Someone replaying captured traffic | To reuse an attestation or assertion | One-time challenges, the assertion counter |
| A genuine user on a genuine iPhone | To use a lot | Not App Attest: spending limits per install |
The last row matters. App Attest proves what is calling, never how much it should be allowed to spend. I come back to that at the end.
The attestation flow, step by step
App Attest is part of the DeviceCheck framework (DCAppAttestService, iOS 14 and later). Apple's two articles are the specification: Establishing your app's integrity for the app, and Validating apps that connect to your server for the server. Here is how the pieces line up when a new install registers with the relay.
In the app
- Check
isSupported. If it isfalse, App Attest isn't available here and you need another path (more on that below). - Generate a key with
generateKey(). The private key is created in the Secure Enclave and never leaves it; you get back a key identifier, which you must store yourself because there is no way to look it up later. - Get a one-time challenge from your server. Apple asks for at least 16 random bytes.
- Attest the key with
attestKey(_:clientDataHash:), passing the SHA-256 of the challenge. The device talks to Apple's servers and returns a CBOR attestation object. - Send the attestation, the key ID and the challenge to your server. Store the key ID, never the attestation.
In ClamNotes this lives in an actor called Relay. Stripped of retries and the Mac paths, the registration is short:
import CryptoKit
import DeviceCheck
// simplified: retries, back-off and the Mac fallbacks removed
private func register() async throws -> String {
let service = DCAppAttestService.shared
guard service.isSupported else { throw Failure.unsupported }
// Reuse a key that was generated but never accepted by the server.
let keyID = try await pendingKeyID() ?? service.generateKey()
savePendingKeyID(keyID)
let challenge = try await fetchChallenge() // from the relay
let clientDataHash = Data(SHA256.hash(data: Data(challenge.utf8)))
let attestation = try await service.attestKey(keyID, clientDataHash: clientDataHash)
let token = try await send(.register, [
"keyId": keyID,
"attestation": attestation.base64EncodedString(),
"challenge": challenge,
])
saveKeyID(keyID) // now this install's key
clearPendingKeyID()
return token
}
On the server
The attestation object decodes (CBOR) to fmt, which must be "apple-appattest", an attStmt with a certificate chain x5c and a receipt, and authData, the WebAuthn-style authenticator data. Apple's checklist, condensed:
- Certificate chain.
x5cholds the credential (leaf) certificate and an intermediate. Verify that they chain to Apple's App Attestation Root CA, which you download from Apple and pin in your server code. - Nonce. Compute
clientDataHash = SHA256(challenge), append it toauthData, hash the result: that is the nonce. The leaf certificate carries an extension with OID1.2.840.113635.100.8.2whose single octet string must equal it. - Key ID. SHA-256 of the leaf certificate's public key (as an uncompressed X9.62 point) must equal the key ID the app sent.
- App ID. The first 32 bytes of
authData, the RP ID hash, must equal SHA-256 of your App ID: team ID, a dot, bundle ID. - Counter. Must be
0: a fresh key has signed nothing yet. - Environment. The AAGUID is
appattestdevelopfor development keys, orappattestfollowed by seven zero bytes for production. - Credential ID. The credential ID in
authDatamust equal the key ID. - Store the public key against the install, make sure no other install already has it, and keep the receipt if you want Apple's fraud metric later.
All of this runs inside a Cloudflare Worker without Node's crypto module. Workers have Web Crypto (ECDSA P-256, SHA-256, HMAC), which covers the cryptography. For parsing I use two small npm packages, one for CBOR and one for X.509, the latter told to use the Worker's Web Crypto as its provider. Apple's App Attestation Root CA is a PEM string constant in the Worker, so the chain check needs no network call. The stored public key and the last assertion counter live in a D1 table keyed by a hash of the key ID. Here is the shape of the attestation check as a minimal sketch. It is written for this post, not copied from the relay, and the helpers are left to your libraries:
// A minimal outline of Apple's attestation checks. Not production code.
const NONCE_OID = "1.2.840.113635.100.8.2";
export async function verifyAttestation(
attestation: Uint8Array, keyId: Uint8Array, challenge: Uint8Array, appId: string,
): Promise<Uint8Array> {
const { fmt, attStmt, authData } = decodeCbor(attestation);
if (fmt !== "apple-appattest") throw new Error("format");
const [leaf, intermediate] = attStmt.x5c.map(parseCertificate);
await verifyChain(leaf, intermediate, APPLE_APP_ATTEST_ROOT); // step 1
const nonce = await sha256(concat(authData, await sha256(challenge)));
if (!equal(octetStringIn(leaf, NONCE_OID), nonce)) throw new Error("nonce");
const publicKey = await rawPublicKey(leaf); // 65 bytes, 0x04…
if (!equal(await sha256(publicKey), keyId)) throw new Error("key id");
const auth = parseAuthData(authData);
if (!equal(auth.rpIdHash, await sha256(utf8(appId)))) throw new Error("app id");
if (auth.counter !== 0) throw new Error("counter");
if (!acceptedEnvironment(auth.aaguid)) throw new Error("environment");
if (!equal(auth.credentialId, keyId)) throw new Error("credential id");
return publicKey; // store it; refuse a key that is already registered
}
Assertions: per request, or per token?
Once a key is attested, the app can sign anything with generateAssertion(_:clientDataHash:). The server verifies an assertion with the stored public key: build the nonce from the assertion's authenticatorData and SHA256(clientData), verify the ECDSA signature over it, check the RP ID hash again, and require the counter to be greater than the last one you saw. Then check that the challenge inside the client data is the one you issued, and store the new counter.
Apple's examples sign individual sensitive requests. I don't. In ClamNotes an assertion buys a short-lived bearer token, signed by the relay with an HMAC, and the token goes with the AI requests until it is close to expiring. Then the app asks for a new challenge, signs it, and gets a new token.
Why a token instead of an assertion on every call:
- Background transfers. When the app runs out of background time, ClamNotes hands unfinished AI requests to a background
URLSession, and iOS sends them whenever it decides to. A per-request assertion over a one-time challenge that expires after a few minutes doesn't survive that; a token does. - Round trips. A per-request assertion needs a fresh challenge first, so every call costs an extra request to the relay before the real one.
- One choke point. Each AI request only needs an HMAC check in the Worker. The App Attest cryptography and its database write happen once per renewal.
The cost is that a token is a bearer credential: copied off a device, it works from anywhere until it expires. So the lifetime matters. My first version issued tokens for a month; an audit the next day cut that to a week. The app keeps the token in the Keychain as kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly (after first unlock, because background requests need it with the screen locked; this device only, so it never moves in a backup), and the relay can block an install, after which its token is refused on the next request.
Three details that trip people up
"Nonce does not match". This is the classic first failure, and it is usually a bytes question, not a crypto one. The app hashes some bytes of the challenge into clientDataHash; the server must hash exactly the same bytes. If the server sends the challenge as a base64 string, decide once whether the challenge is that string's UTF-8 bytes or the decoded random bytes, and do the same on both sides. ClamNotes hashes the string as it arrived, on both ends. Another common cause is comparing against the whole extension value: it is a DER-encoded sequence, and what must equal the nonce is the 32-byte octet string inside it.
The signature format. App Attest's signature is DER-encoded ECDSA. Web Crypto's verify wants the raw 64-byte r ‖ s form, so you convert, padding or trimming each integer to 32 bytes. And Apple's step "verify that the signature is valid for nonce" means the nonce is the message: with Web Crypto you pass the 32-byte nonce to verify with hash: "SHA-256", which hashes it once more. Passing the unhashed authData ‖ clientDataHash fails.
const nonce = await sha256(concat(authenticatorData, await sha256(clientData)));
const key = await crypto.subtle.importKey(
"raw", storedPublicKey, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
const ok = await crypto.subtle.verify(
{ name: "ECDSA", hash: "SHA-256" }, key, derToRaw(signature), nonce);
Attestation is once per key. If the upload of an attestation fails (no network, the relay was busy), don't call attestKey again on the same key. Keep the attestation object and resend it while its challenge is still valid; after that, start over. Apple's guidance on errors is specific: on DCError.serverUnavailable, retry later with the same key; on any other error, discard the key and generate a new one. Generating keys freely is not harmless, because Apple's fraud metric counts attested keys per device, and you would be inflating your own users' counts.
Challenges that cost nothing to hand out
Apple says to give out a random, one-time challenge and "remember the value". The obvious implementation is a database row per challenge. That was my first version, and an audit of the relay pointed out what it means: the challenge endpoint is necessarily unauthenticated (you ask for one before you have anything to prove), so anyone on the internet could make the relay write a row, as fast as they liked. A Cloudflare D1 database is a single SQLite database, so those writes queue with the writes that real users' requests depend on.
The fix was a stateless challenge: random bytes plus an expiry time, followed by an HMAC over both with a server secret. Handing one out writes nothing. When it comes back, the Worker checks the HMAC and the expiry before it touches the database, so a made-up challenge costs one HMAC. "One-time" is then enforced where it actually matters:
- For registration, the relay records a challenge as used only after it has proved to be one the relay issued, and keeps that record until the challenge would have expired anyway. Only then does it parse the attestation.
- For renewal, the assertion's counter already makes a replayed assertion worthless, so nothing is written until a genuine assertion arrives.
The general lesson: on any endpoint that runs before authentication, count what a stranger can make you do per request, and get it as close to zero writes as you can. Cloudflare's rate limiting on those routes is a second line, not the first.
Development builds take a different road
There are three different situations, and mixing them up is how keys leak.
Builds installed from Xcode generate App Attest keys in the development environment by default, and their attestations carry the appattestdevelop AAGUID. Apple keeps these keys apart from production, so you can create as many as you like without touching a device's production metrics. Builds distributed through TestFlight or the App Store always use production, whatever the appattest-environment entitlement says. The relay records each install's environment and has a switch that refuses development keys, so builds from Xcode can be shut out without touching anything else.
Debug builds with my own key can skip the relay and call OpenRouter directly. The key comes from Secrets.xcconfig, which Git ignores, and it is guarded three times so a Release build can't pick it up:
// App.xcconfig: shared by every configuration
PROVIDER_API_KEY =
// App-Debug.xcconfig: the Debug configuration only
#include "App.xcconfig"
#include? "Secrets.xcconfig" // ignored by Git; the optional include doesn't fail without it
// Info.plist, with INFOPLIST_PREPROCESS = YES and the define set for Debug only
#ifdef OWN_PROVIDER_KEY
<key>OpenRouterAPIKey</key>
<string>$(PROVIDER_API_KEY)</string>
#endif
/// A developer's own key, which sends requests straight to the provider;
/// without one, as in every build given out, they go through the relay.
static var ownKey: String? {
#if DEBUG
guard let key = Bundle.main.object(forInfoDictionaryKey: "OpenRouterAPIKey") as? String,
!key.isEmpty, !key.hasPrefix("$(") else { return nil }
return key
#else
// A build given out always goes through the relay, even if a key got into its Info.plist.
return nil
#endif
}
The #ifdef in the plist is the newest layer. Until it went in, Release builds still had the plist entry, with an empty value. Harmless as it was, but one misplaced #include away from shipping a key, and the #if DEBUG in Swift would have been the only thing standing in the way. Now the entry doesn't exist outside Debug. Treat any key in a debug build as already leaked anyway: give it a spending limit at the provider.
Debug builds without a key use the real relay with a development App Attest key, which is how I test that path on a device.
Where App Attest isn't available
Check isSupported every time and design the fallback before you need it.
- The Simulator reports
isSupported == false. App Attest needs Secure Enclave hardware, so the real flow can only be tested on a device. - App extensions mostly can't use it. Apple's documentation lists very few supported extension types, and says
generateKeyfails in the others even whenisSupportedistrue. ClamNotes' extensions don't call the relay. - The Mac is where Apple's own pages disagree. The
isSupportedreference says it readsfalseon a Mac, including Mac Catalyst and iPhone apps on Apple silicon, while the server article now has macOS-specific verification steps. Don't trust either page for your build: checkisSupportedat run time, on the exact build you distribute, and look at which environment its keys attest in.
Wherever isSupported is false, you need another way to prove an install is real, tied to something App Attest has already vouched for or to a purchase. Whatever you choose there is a weaker guarantee than App Attest, so give those installs their own limits and make every one of them revocable.
What App Attest does not protect against
It is easy to oversell. App Attest gives you one strong statement: this key was created by your app, unmodified, on genuine Apple hardware. Everything beyond that is still your problem.
- A genuine user spending your money. An attested app running on a real iPhone can be driven hard, or automated through its own UI. You still need per-install spending limits, a global daily limit, and a provider-side spending cap as the last net. In my relay the worst-case cost of a request is set aside before it is forwarded, so parallel requests can't overrun a limit together.
- A compromised device. Apple's fraud-risk article says an attacker who modifies the operating system might get around the restrictions, and one such device could serve assertions to many modified apps. What does that attacker get from a relay like mine? What a genuine install gets: a token and that install's quota, until it is blocked. Not the provider key, and more quota only by attesting more keys. Apple's tool for spotting that is the receipt from the attestation, which your server can exchange for a risk metric: an approximate count of attested keys for your app on that device.
- Misuse of a legitimate session. With a valid token, an attacker can send anything your relay forwards. So the relay doesn't forward arbitrary bodies: it rebuilds each request from an allow-list of what the app actually sends (models, tools, size limits) and refuses everything else. Without that, an attested token is a general-purpose API key with extra steps.
- Stolen tokens. If you mint bearer tokens as I do, they are only as safe as their lifetime and storage.
- Privacy. The relay sees every request it forwards. Mine keeps no request, no answer and no IP address, but that is a policy, not something App Attest enforces.
Lessons
- Move the key before the first build leaves your machine. A TestFlight build is a download. Rotating a leaked key is easy; finding out it leaked usually comes with an invoice.
- Follow Apple's checklist literally. The chain proves Apple, the nonce your challenge, the key ID the key, the RP ID your app, the counter freshness. Skip one and you reopen its hole.
- Choose assertions or tokens deliberately. Tokens fit background transfers; keep them short-lived and revocable.
- Handle the error codes the way Apple says. Retry
serverUnavailablewith the same key, discard the key on anything else, and expect keys to vanish after a reinstall, a device migration or a restore. An audit caught my app reporting a passingserverUnavailableas a refusal; a transient failure should look transient. - Keep development and production apart, with a server switch that refuses development keys.
- App Attest answers "what is calling", not "how much". Budget limits, request allow-lists and provider-side caps are not optional extras.
The relay is not big. The App Attest verification is under two hundred lines of TypeScript, most of it the steps above. What took longer was everything around it: the fallbacks, the races, and deciding what a genuine copy of the app should still not be allowed to do.
Built for ClamNotes
Every note ClamNotes writes goes through this relay, with no key in the app.
ClamNotes records a class, transcribes it on the device and writes a study note in the language that was spoken. For iPhone, iPad and Mac.
See ClamNotes