@pithy-sh/auth 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +4 -0
  2. package/dist/attestation/appAttest/assertion.d.ts +32 -0
  3. package/dist/attestation/appAttest/assertion.d.ts.map +1 -0
  4. package/dist/attestation/appAttest/assertion.js +59 -0
  5. package/dist/attestation/appAttest/attestation.d.ts +49 -0
  6. package/dist/attestation/appAttest/attestation.d.ts.map +1 -0
  7. package/dist/attestation/appAttest/attestation.js +111 -0
  8. package/dist/attestation/appAttest/authData.d.ts +24 -0
  9. package/dist/attestation/appAttest/authData.d.ts.map +1 -0
  10. package/dist/attestation/appAttest/authData.js +32 -0
  11. package/dist/attestation/appAttest/base64.d.ts +8 -0
  12. package/dist/attestation/appAttest/base64.d.ts.map +1 -0
  13. package/dist/attestation/appAttest/base64.js +27 -0
  14. package/dist/attestation/appAttest/bytes.d.ts +7 -0
  15. package/dist/attestation/appAttest/bytes.d.ts.map +1 -0
  16. package/dist/attestation/appAttest/bytes.js +19 -0
  17. package/dist/attestation/appAttest/cbor.d.ts +20 -0
  18. package/dist/attestation/appAttest/cbor.d.ts.map +1 -0
  19. package/dist/attestation/appAttest/cbor.js +96 -0
  20. package/dist/attestation/appAttest/der.d.ts +38 -0
  21. package/dist/attestation/appAttest/der.d.ts.map +1 -0
  22. package/dist/attestation/appAttest/der.js +106 -0
  23. package/dist/attestation/appAttest/keys.d.ts +15 -0
  24. package/dist/attestation/appAttest/keys.d.ts.map +1 -0
  25. package/dist/attestation/appAttest/keys.js +37 -0
  26. package/dist/attestation/appAttest/root.d.ts +9 -0
  27. package/dist/attestation/appAttest/root.d.ts.map +1 -0
  28. package/dist/attestation/appAttest/root.js +12 -0
  29. package/dist/attestation/appAttest/verifier.d.ts +39 -0
  30. package/dist/attestation/appAttest/verifier.d.ts.map +1 -0
  31. package/dist/attestation/appAttest/verifier.js +121 -0
  32. package/dist/attestation/appAttest/x509.d.ts +50 -0
  33. package/dist/attestation/appAttest/x509.d.ts.map +1 -0
  34. package/dist/attestation/appAttest/x509.js +163 -0
  35. package/dist/attestation/challenge.d.ts +26 -0
  36. package/dist/attestation/challenge.d.ts.map +1 -0
  37. package/dist/attestation/challenge.js +47 -0
  38. package/dist/attestation/config.d.ts +72 -0
  39. package/dist/attestation/config.d.ts.map +1 -0
  40. package/dist/attestation/config.js +52 -0
  41. package/dist/attestation/errors.d.ts +30 -0
  42. package/dist/attestation/errors.d.ts.map +1 -0
  43. package/dist/attestation/errors.js +45 -0
  44. package/dist/attestation/gate.d.ts +27 -0
  45. package/dist/attestation/gate.d.ts.map +1 -0
  46. package/dist/attestation/gate.js +78 -0
  47. package/dist/attestation/playIntegrity/google.d.ts +47 -0
  48. package/dist/attestation/playIntegrity/google.d.ts.map +1 -0
  49. package/dist/attestation/playIntegrity/google.js +178 -0
  50. package/dist/attestation/playIntegrity/verdict.d.ts +40 -0
  51. package/dist/attestation/playIntegrity/verdict.d.ts.map +1 -0
  52. package/dist/attestation/playIntegrity/verdict.js +93 -0
  53. package/dist/attestation/playIntegrity/verifier.d.ts +22 -0
  54. package/dist/attestation/playIntegrity/verifier.d.ts.map +1 -0
  55. package/dist/attestation/playIntegrity/verifier.js +64 -0
  56. package/dist/attestation/verifier.d.ts +60 -0
  57. package/dist/attestation/verifier.d.ts.map +1 -0
  58. package/dist/attestation/verifier.js +46 -0
  59. package/dist/attestation/wire.d.ts +42 -0
  60. package/dist/attestation/wire.d.ts.map +1 -0
  61. package/dist/attestation/wire.js +72 -0
  62. package/dist/capability.d.ts +40 -0
  63. package/dist/capability.d.ts.map +1 -1
  64. package/dist/capability.js +38 -5
  65. package/dist/client/api.d.ts +37 -24
  66. package/dist/client/api.d.ts.map +1 -1
  67. package/dist/client/api.js +52 -41
  68. package/dist/client/attestation.d.ts +148 -0
  69. package/dist/client/attestation.d.ts.map +1 -0
  70. package/dist/client/attestation.js +321 -0
  71. package/dist/client/projection.d.ts +29 -4
  72. package/dist/client/projection.d.ts.map +1 -1
  73. package/dist/data/appAttestKey.d.ts +30 -0
  74. package/dist/data/appAttestKey.d.ts.map +1 -0
  75. package/dist/data/appAttestKey.js +25 -0
  76. package/dist/data/attestationChallenge.d.ts +17 -0
  77. package/dist/data/attestationChallenge.d.ts.map +1 -0
  78. package/dist/data/attestationChallenge.js +19 -0
  79. package/dist/data/tables.d.ts +18 -1
  80. package/dist/data/tables.d.ts.map +1 -1
  81. package/dist/data/tables.js +6 -2
  82. package/dist/http/devLoginRoute.js +3 -3
  83. package/dist/http/resolve.js +1 -1
  84. package/dist/http/responses.d.ts +12 -0
  85. package/dist/http/responses.d.ts.map +1 -1
  86. package/dist/http/responses.js +11 -1
  87. package/dist/http/routes.d.ts +5 -1
  88. package/dist/http/routes.d.ts.map +1 -1
  89. package/dist/http/routes.js +92 -25
  90. package/dist/http/schemas.d.ts +7 -0
  91. package/dist/http/schemas.d.ts.map +1 -1
  92. package/dist/http/schemas.js +7 -1
  93. package/dist/index.js +1 -1
  94. package/dist/instance/secrets.d.ts +86 -7
  95. package/dist/instance/secrets.d.ts.map +1 -1
  96. package/dist/instance/secrets.js +54 -8
  97. package/dist/migrations/0009_attestation_challenges.d.ts +9 -0
  98. package/dist/migrations/0009_attestation_challenges.d.ts.map +1 -0
  99. package/dist/migrations/0009_attestation_challenges.js +21 -0
  100. package/dist/migrations/0010_app_attest_keys.d.ts +9 -0
  101. package/dist/migrations/0010_app_attest_keys.d.ts.map +1 -0
  102. package/dist/migrations/0010_app_attest_keys.js +17 -0
  103. package/dist/migrations/set.d.ts +3 -1
  104. package/dist/migrations/set.d.ts.map +1 -1
  105. package/dist/migrations/set.js +6 -2
  106. package/dist/seeds/devSession.js +1 -1
  107. package/dist/test-utils/appAttestDevice.d.ts +92 -0
  108. package/dist/test-utils/appAttestDevice.d.ts.map +1 -0
  109. package/dist/test-utils/appAttestDevice.js +282 -0
  110. package/dist/test-utils/appAttestSample.d.ts +22 -0
  111. package/dist/test-utils/appAttestSample.d.ts.map +1 -0
  112. package/dist/test-utils/appAttestSample.js +24 -0
  113. package/dist/test-utils/googlePlay.d.ts +47 -0
  114. package/dist/test-utils/googlePlay.d.ts.map +1 -0
  115. package/dist/test-utils/googlePlay.js +117 -0
  116. package/dist/test-utils/liveApp.d.ts +76 -36
  117. package/dist/test-utils/liveApp.d.ts.map +1 -1
  118. package/dist/test-utils/liveApp.js +16 -5
  119. package/dist/test-utils/rollbackThrough.d.ts +11 -0
  120. package/dist/test-utils/rollbackThrough.d.ts.map +1 -0
  121. package/dist/test-utils/rollbackThrough.js +16 -0
  122. package/dist/test-utils/scopedBackend.d.ts +25 -0
  123. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  124. package/dist/test-utils/scopedBackend.js +1 -1
  125. package/dist/version.generated.d.ts +1 -1
  126. package/dist/version.generated.js +1 -1
  127. package/docs/attestation.md +173 -0
  128. package/package.json +5 -5
  129. package/pithy.manifest.json +14 -0
  130. package/src/attestation/appAttest/assertion.ts +65 -0
  131. package/src/attestation/appAttest/attestation.ts +159 -0
  132. package/src/attestation/appAttest/authData.ts +45 -0
  133. package/src/attestation/appAttest/base64.ts +29 -0
  134. package/src/attestation/appAttest/bytes.ts +18 -0
  135. package/src/attestation/appAttest/cbor.ts +116 -0
  136. package/src/attestation/appAttest/der.ts +126 -0
  137. package/src/attestation/appAttest/keys.ts +57 -0
  138. package/src/attestation/appAttest/root.ts +13 -0
  139. package/src/attestation/appAttest/verifier.ts +113 -0
  140. package/src/attestation/appAttest/x509.ts +209 -0
  141. package/src/attestation/challenge.ts +56 -0
  142. package/src/attestation/config.ts +118 -0
  143. package/src/attestation/errors.ts +60 -0
  144. package/src/attestation/gate.ts +105 -0
  145. package/src/attestation/playIntegrity/google.ts +239 -0
  146. package/src/attestation/playIntegrity/verdict.ts +149 -0
  147. package/src/attestation/playIntegrity/verifier.ts +77 -0
  148. package/src/attestation/verifier.ts +87 -0
  149. package/src/attestation/wire.ts +79 -0
  150. package/src/capability.ts +64 -8
  151. package/src/client/api.ts +73 -40
  152. package/src/client/attestation.ts +404 -0
  153. package/src/client/projection.ts +29 -4
  154. package/src/data/appAttestKey.ts +45 -0
  155. package/src/data/attestationChallenge.ts +23 -0
  156. package/src/data/tables.ts +5 -1
  157. package/src/http/responses.ts +22 -0
  158. package/src/http/routes.ts +128 -38
  159. package/src/http/schemas.ts +24 -0
  160. package/src/instance/secrets.ts +88 -9
  161. package/src/migrations/0009_attestation_challenges.ts +28 -0
  162. package/src/migrations/0010_app_attest_keys.ts +27 -0
  163. package/src/migrations/set.ts +5 -1
  164. package/src/test-utils/appAttestDevice.ts +399 -0
  165. package/src/test-utils/appAttestSample.ts +20 -0
  166. package/src/test-utils/googlePlay.ts +144 -0
  167. package/src/test-utils/liveApp.ts +31 -5
  168. package/src/test-utils/rollbackThrough.ts +24 -0
  169. package/src/version.generated.ts +1 -1
@@ -0,0 +1,173 @@
1
+ # Native app attestation
2
+
3
+ _This copy ships in the package because `README.md` sends an adopter to it by name._
4
+
5
+ A web page proves a human is there with Turnstile. A native app has no widget to solve. It proves something else instead: that the request came from your app, unmodified, on a real device. Apple calls that App Attest. Google calls it Play Integrity. Auth's send routes take either one in place of a Turnstile token.
6
+
7
+ ## What it gates
8
+
9
+ The two routes that send a sign-in email: `POST /auth/sign-in/magic-link` and `POST /auth/email-otp/send-verification-otp`. Signing up is the same two routes, so it is gated too. Nothing else.
10
+
11
+ ## The rule: either passes
12
+
13
+ - **A request carrying an attestation is judged by attestation, and only by attestation.** If it fails, the request is refused. It never falls through to Turnstile.
14
+ - **A request without one goes to Turnstile** when turnstile is composed, exactly as before.
15
+ - **Without turnstile composed**, a request with no attestation is refused with `auth/attestation_missing` in an environment that has an attestation block, and passes in one that has none.
16
+
17
+ Attestation works with turnstile composed or not. A project that composes turnstile and attestation serves its web page and its app from one Worker.
18
+
19
+ ## Configuring it
20
+
21
+ The block lives on `auth()`, per environment, keyed by the name the Worker is stamped with:
22
+
23
+ ```ts
24
+ auth({
25
+ baseURL: "https://api.example.com",
26
+ attestation: {
27
+ environments: {
28
+ dev: { mode: "test" },
29
+ staging: { mode: "test", ios: [{ teamId: "ABCDE12345", bundleId: "com.example.app" }] },
30
+ prod: {
31
+ mode: "enforce",
32
+ ios: [{ teamId: "ABCDE12345", bundleId: "com.example.app" }],
33
+ android: [{ packageName: "com.example.app" }],
34
+ },
35
+ },
36
+ },
37
+ });
38
+ ```
39
+
40
+ - **`environments.<env>.mode`** is `enforce` (the default) or `test`.
41
+ - **`environments.<env>.ios`** lists the iOS apps allowed to attest: the Apple Team ID and the bundle identifier.
42
+ - **`environments.<env>.android`** lists the Android apps allowed to attest: the package name.
43
+ - **`challengeExpiresIn`** is how long a challenge stays usable, in seconds. Five minutes by default, ten at most.
44
+
45
+ An `enforce` block must allow at least one app. A real assertion from a platform with no app listed is refused; the test assertion is judged by the mode and the environment alone. An environment with no block keeps its send routes exactly as they were.
46
+
47
+ A project that never configures attestation installs nothing new and mounts no new route. `pithy migrate` creates two tables, `pithy_auth_attestation_challenges` and `pithy_auth_app_attest_keys`, and nothing writes to either. Verification runs on WebCrypto, with auth's own CBOR and certificate reader for App Attest and auth's own JWT signer for Play Integrity, and `@pithy-sh/auth` takes no dependency for either.
48
+
49
+ ## The flow
50
+
51
+ 1. **Ask for a challenge.** `POST /auth/attestation/challenge` answers `{ challenge, expiresAt }`. The challenge is 32 random bytes as unpadded base64url. It is good once, until `expiresAt`. Auth stores only its SHA-256.
52
+ 2. **Attest over the request.** Hash the challenge's characters followed by the send's exact body bytes with SHA-256. That digest is App Attest's `clientDataHash`, and its unpadded base64url is Play Integrity's `requestHash`. It binds the attestation to this challenge and this body, so it cannot be lifted onto another address.
53
+ 3. **Send it in one header.** `x-pithy-attestation` carries unpadded base64url over the JSON `{ "platform": "ios" | "android", "challenge": "…", "assertion": "…", "keyId": "…" }`. `assertion` is the App Attest assertion from `generateAssertion`, or the Play Integrity token, as the platform hands it over. On iOS the key must already be registered: the attestation object from `attestKey` goes once to `POST /auth/attestation/ios/keys` (see [Registering a key](#registering-a-key)), never in this header. `keyId` is App Attest's key identifier; Android has none.
54
+
55
+ The challenge is spent the moment it is presented, pass or fail. A failed attempt asks for a new one.
56
+
57
+ ## Apple App Attest
58
+
59
+ ### What goes in config
60
+
61
+ Each iOS app is one entry in `ios`: `{ teamId, bundleId }`. Together they are the app's App ID, `<teamId>.<bundleId>`, and App Attest signs over its SHA-256.
62
+
63
+ - **`teamId`** is your Apple Developer Team ID: ten uppercase letters and digits, such as `ABCDE12345`. Find it at [developer.apple.com/account](https://developer.apple.com/account) under **Membership details**, or in Xcode on the target's **Signing & Capabilities** tab as the team's identifier. If the app's identifier in **Certificates, Identifiers & Profiles** shows an App ID prefix other than the Team ID, which only very old apps have, use that prefix.
64
+ - **`bundleId`** is the app's bundle identifier, such as `com.example.app`. Find it in Xcode on the target's **General** tab under **Identity**, or in an Expo app's `app.json` as `ios.bundleIdentifier`.
65
+
66
+ List every app that may attest in that environment. A staging build with its own bundle identifier is its own entry in the `staging` block.
67
+
68
+ The app needs the **App Attest** capability in Xcode, which adds the `com.apple.developer.devicecheck.appattest-environment` entitlement. Its value picks Apple's environment, and auth reads it from the attestation: `production` keys are accepted everywhere, and `development` keys only where the Worker's `ENVIRONMENT` is `dev`, `staging` or `feature`, the same rule test mode follows. A development key in `prod` is refused. TestFlight and App Store builds attest in `production`.
69
+
70
+ ### Registering a key
71
+
72
+ Once per key, before its first assertion:
73
+
74
+ 1. The app calls `generateKey()` and keeps the key id.
75
+ 2. It asks `POST /auth/attestation/challenge` for a challenge.
76
+ 3. It calls `attestKey(keyId, clientDataHash:)` with SHA-256 of the challenge's characters: the [binding](#the-flow) over the challenge and an empty body.
77
+ 4. It sends `POST /auth/attestation/ios/keys` with `{ "challenge": "…", "keyId": "…", "attestation": "…" }`, the key id and the attestation object base64 as Apple hands them over.
78
+
79
+ Auth spends the challenge, then checks the attestation Apple's way: the certificate chain leads to Apple App Attestation Root CA, which ships pinned in the package; the certificate's nonce is bound to this challenge; the certificate's key hashes to the key id; the `rpIdHash` is SHA-256 of an allowed app's App ID; the counter is zero; the AAGUID is an environment accepted here; and the credential id is the key id. It stores the key id, the public key, the App ID, the environment and a counter of zero in `pithy_auth_app_attest_keys`. A key registers once: registering it again is refused, so its counter cannot be reset. A key names no person.
80
+
81
+ ### Each send
82
+
83
+ The app calls `generateAssertion(keyId, clientDataHash:)` with the binding over a fresh challenge and the send's exact body, and sends the assertion as `assertion` with the key id as `keyId` in `x-pithy-attestation`. Auth finds the key, checks that its app is still allowed and that a development key is accepted here, checks the `rpIdHash`, verifies the signature over the binding with the stored public key, and requires the counter to rise above the stored one. Then it stores the new counter.
84
+
85
+ ### Refusals
86
+
87
+ Every App Attest check that fails is `auth/attestation_failed`, and `detail` starts with the check that failed: `challenge`, `format`, `chain`, `nonce`, `keyId`, `key` (no key with that id is registered), `rpIdHash`, `aaguid`, `credentialId`, `signature` or `counter`. A request carrying no `keyId` fails on `keyId`. The gate's own refusals come before these and are worded as [the codes](#the-three-refusals) say: a header that does not decode, or a send from a platform with no allowed app. An environment with no attestation block answers `auth/attestation_config`, at the registration route as at a send.
88
+
89
+ ## Google Play Integrity
90
+
91
+ ### What goes in config
92
+
93
+ Each Android app is one entry in `android`: `{ packageName }`, the application id Google Play knows it by, such as `com.example.app`. Find it in `build.gradle` as `applicationId`, or in an Expo app's `app.json` as `android.package`. List every app that may attest in that environment.
94
+
95
+ ### The service account
96
+
97
+ The Worker decodes each token through Google's `decodeIntegrityToken`, signed in as a Google Cloud service account. One service account serves every app in an environment.
98
+
99
+ 1. **Create it.** In [Google Cloud Console](https://console.cloud.google.com/iam-admin/serviceaccounts), pick the project the app uses for Play Integrity, or create one, and enable the **Google Play Integrity API** under **APIs & Services**. Under **IAM & Admin > Service accounts**, create a service account. It needs no role.
100
+ 2. **Make a key.** On the service account, open **Keys**, choose **Add key > Create new key**, pick **JSON**, and save the file. It is the only copy.
101
+ 3. **Link the project in Play Console.** In [Play Console](https://play.google.com/console), open the app, then **Test and release > App integrity > Play Integrity API**, and link the same Google Cloud project. The app requests tokens for that project's number, and only that project's service accounts can decode them.
102
+ 4. **Store it.** Paste the whole JSON file as the `auth-play-integrity-service-account` secret, once per environment:
103
+
104
+ ```bash
105
+ pithy secrets create auth-play-integrity-service-account --env prod < service-account.json
106
+ ```
107
+
108
+ The key's `private_key` spans many lines, so the prompt asks for the file as one JSON document rather than field by field. Auth keeps `client_email`, `private_key`, `private_key_id`, `project_id`, `client_id`, `token_uri` and `type`, and drops the rest. `pithy secrets ls` lists the secret, and `pithy doctor` reports it missing, once any environment lists an Android app. Delete the downloaded file once it is stored.
109
+
110
+ To rotate, add a new key to the service account, store it with `pithy secrets update`, then delete the old key in Cloud Console.
111
+
112
+ ### Each send
113
+
114
+ The app asks Play Integrity for a standard-request token whose `requestHash` is the unpadded base64url of the [binding](#the-flow), and sends the token as `assertion` in `x-pithy-attestation`, with no `keyId`. The Worker signs an RS256 assertion with the service account's key, exchanges it at Google's token endpoint for an access token, which the isolate reuses until a minute before it expires, and calls `decodeIntegrityToken` for each allowed package until one decodes. Then it requires, in order:
115
+
116
+ - **`requestHash`** in `requestDetails` to be the binding over this challenge and this body. A classic request's `nonce` is checked the same way when it carries no `requestHash`.
117
+ - **`requestPackageName`** to be the package Google decoded the token for.
118
+ - **`appRecognitionVerdict`** to be `PLAY_RECOGNIZED`.
119
+ - **`appIntegrity`**: its `packageName` to be that same package. `requestPackageName` is only what the caller asked for, so this is the check that ties the token to your app rather than to any app Google Play distributes.
120
+ - **`deviceIntegrity`** to include `MEETS_DEVICE_INTEGRITY`.
121
+ - **`timestamp`**: `timestampMillis` no more than five minutes old, and no more than a minute ahead of the Worker's clock.
122
+
123
+ The licensing and account verdicts are not checked.
124
+
125
+ ### Refusals
126
+
127
+ A verdict that fails is `auth/attestation_failed`, and `detail` starts with the check: `decode` (Google would decode the token for no allowed package), `requestHash` or `nonce`, `requestPackageName`, `appRecognitionVerdict`, `appIntegrity`, `deviceIntegrity`, `timestamp`, or `format`.
128
+
129
+ A fault in the server's setup is `auth/attestation_config` and never blames the user: no service account stored, a key that is not an RSA PEM, Google's token endpoint refusing the account, or `decodeIntegrityToken` answering 401, 403 or 404, which means the API is not enabled or the project is not linked to the app. Google failing outright, unreachable, a 429 or a 5xx, or an answer with no token or payload in it, is `core/upstream_failed` (502), and a call that runs past ten seconds is `core/upstream_timeout` (504).
130
+
131
+ ## Test mode
132
+
133
+ Simulators, emulators and CI cannot produce a real attestation. In an environment set to `test`, the gate also accepts the test assertion from either platform:
134
+
135
+ ```
136
+ pithy-test-attestation
137
+ ```
138
+
139
+ Send it as `assertion`, with a real challenge from the challenge route. The challenge is still single-use and still expires.
140
+
141
+ **Production never accepts it.** The Worker accepts the test assertion only where its `ENVIRONMENT` is `dev`, `staging` or `feature`, whatever the config says. Everywhere else it is refused: `prod`, an unstamped Worker, and every name a project declares, because a deployed Worker cannot read `seed.productionEnvironments` to tell a declared production name from any other. Test mode in a declared environment is therefore inert; use `staging` or a feature deployment for simulators and CI. `pithy doctor` reports a production environment set to `test`, and `pithy deploy` refuses to ship one. Both hold every name in the root config's `seed.productionEnvironments` to the same rule.
142
+
143
+ ## The three refusals
144
+
145
+ | Code | Status | When |
146
+ |---|---|---|
147
+ | `auth/attestation_missing` | 400 | The environment has a block, turnstile is not composed, and the request carried no attestation. |
148
+ | `auth/attestation_failed` | 403 | The attestation did not verify: a header that does not decode, a challenge that is stale, reused or never issued, a real assertion from a platform with no allowed app, an App Attest key that does not register, an assertion that does not check out, a Play Integrity verdict that fails, or the test assertion where it is not accepted. |
149
+ | `auth/attestation_config` | 500 | The server cannot judge it: the environment has no attestation block, no verifier for the platform is available, or the Play Integrity service account is missing or refused by Google. |
150
+
151
+ Each one says why in `detail`, which goes to the operator's log and never to the client. The client sees the code, the status and a short message.
152
+
153
+ ## The client
154
+
155
+ `@pithy-sh/auth/src/client/attestation` speaks this flow for a native app, and the React Native scaffold wires it for you ([`docs/UI.md`](../../../docs/UI.md) § *React Native*).
156
+
157
+ ```ts
158
+ import { sendOtp } from "@pithy-sh/auth/src/client/api";
159
+ import { createAttestation, testAttester } from "@pithy-sh/auth/src/client/attestation";
160
+
161
+ const attestation = createAttestation({ ...session.options, attester: testAttester("ios") });
162
+ const sent = await sendOtp({ email, type: "sign-in" }, { ...session.options, attestation });
163
+ ```
164
+
165
+ `createAttestation` asks the challenge route for a challenge before each send, hands the attester the challenge, the exact body, their binding and a transport for any call it must make first, and puts the result in `x-pithy-attestation`. With `attestation` set, the send carries no Turnstile token. The attester is injected:
166
+
167
+ - **`testAttester(platform)`** sends the test assertion.
168
+ - **`appAttestAttester({ module, store })`** is App Attest. `module` is `@expo/app-integrity`, and `store` keeps the key id. With no registered key, a send first [registers one](#registering-a-key): it calls `generateKeyAsync`, asks the challenge route for a challenge of its own, calls `attestKeyAsync` with that challenge, and posts the challenge, the key id and the attestation object to `POST /auth/attestation/ios/keys`. The key id goes into `store` only when that route answers success. Then the send, and every later one, calls `generateAssertionAsync` over its own challenge and the exact body and sends the assertion in the header. A registration the route refuses is not kept, the send answers the route's code with nothing sent, and the next send registers a new key. A key the device can no longer assert with, after a reinstall, a restore or a migration, is dropped and a new one registered on the same send. The module hashes the string it is handed into `clientDataHash`, so registration hands it the challenge alone and an assertion the challenge followed by the body: the two bindings auth checks.
169
+ - **`playIntegrityAttester({ module, cloudProjectNumber })`** is Play Integrity. It prepares the token provider, again after any failure to prepare it or to get a token, and asks for a token whose `requestHash` is the binding's base64url.
170
+
171
+ `@pithy-sh/auth` never depends on `@expo/app-integrity`: the app installs it and passes it in. A web-only or server-only project installs nothing for attestation. Its peers are `expo` and `react-native` at any version, so the floor is the API: 0.1.9, an Expo SDK 54 release, is the first with the `Async` names this client calls. The scaffold pins `expo` `~57.0.31` and `@expo/app-integrity` `~57.0.2`.
172
+
173
+ **A refusal keeps its code.** A refused send answers an `AuthResult` whose `failure.code` is the gate's: `auth/attestation_failed`, `auth/attestation_missing`, `auth/attestation_config`, `turnstile/failed` or `turnstile/missing_token`. `isGateRefusal(failure)` says whether a refusal is the gate's, which a screen may show without telling a registered address from another. A device that would not attest is `client/attestation_unavailable`, and nothing was sent. On `auth/attestation_failed` at a send the attestation is told which send was refused, and App Attest drops the key that send used, never a newer one another send registered since, so the next send registers a new one. A refused registration answers the registration route's code, and the send is never made.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.15.2",
3
+ "version": "0.16.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -46,10 +46,10 @@
46
46
  "better-auth": "^1.7.11"
47
47
  },
48
48
  "peerDependencies": {
49
- "@pithy-sh/core": "^0.22.0",
50
- "@pithy-sh/email": "^0.10.5",
51
- "@pithy-sh/secrets": "^0.6.10",
52
- "@pithy-sh/turnstile": "^0.8.6",
49
+ "@pithy-sh/core": "^0.24.0",
50
+ "@pithy-sh/email": "^0.10.7",
51
+ "@pithy-sh/secrets": "^0.6.12",
52
+ "@pithy-sh/turnstile": "^0.9.0",
53
53
  "hono": "^4.13.2",
54
54
  "kysely": "^0.29.0",
55
55
  "zod": "^4.4.0"
@@ -89,6 +89,19 @@
89
89
  "issuer": "microsoft",
90
90
  "documentation": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"
91
91
  }
92
+ },
93
+ {
94
+ "name": "auth-play-integrity-service-account",
95
+ "origin": {
96
+ "kind": "obtained",
97
+ "issuer": "google",
98
+ "documentation": "https://console.cloud.google.com/iam-admin/serviceaccounts"
99
+ },
100
+ "rotation": {
101
+ "kind": "manual",
102
+ "issuer": "google",
103
+ "documentation": "https://console.cloud.google.com/iam-admin/serviceaccounts"
104
+ }
92
105
  }
93
106
  ],
94
107
  "whenToEnable": "Sign-in for your app — passwordless, mobile and web both first-class. Magic link, email OTP, and social sign-in with Google, Apple, Facebook, GitHub, and Microsoft. A successful sign-in mints a rotated session whose token is the bearer credential, and short-lived JWTs that services outside the Worker verify against `/jwks`. It fills core's identity seams, so every other capability just calls `requireAuth()`. This is the keystone capability; add it first.",
@@ -103,6 +116,7 @@
103
116
  "Facebook (optional): set `facebook: { enabled: true }`, then `pithy secrets create auth-facebook-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/facebook-oauth.md.",
104
117
  "GitHub (optional): set `github: { enabled: true }`, then `pithy secrets create auth-github-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/github-oauth.md.",
105
118
  "Microsoft (optional): set `microsoft: { enabled: true }`, then `pithy secrets create auth-microsoft-credentials` with the typed JSON `{ clientId, clientSecret, tenantId }`. Add the `xms_edov` optional claim to the ID token in the app registration, or every work and school address is verified by magic link before it links. See the package's docs/microsoft-oauth.md.",
119
+ "Android attestation (optional): list the app under `attestation.environments.<env>.android`, then `pithy secrets create auth-play-integrity-service-account --env <env>` with the Google Cloud service account's JSON key, the account linked to the app in Play Console. See the package's docs/attestation.md.",
106
120
  "Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend` to suspend somebody and reinstate them, `auth:users:delete`, `auth:users:export`; and `auth:verifications:read` for the ledger of every sign-in link and code sent, used or expired, and the mail that carried it. Nine scopes and not one admin flag — a support tool that looks people up must not also be able to sign the customer base out, and an incident-response tool that kills a session has no business reading every address in the user table. With the seam not composed every /auth/admin route answers `controlplane/not_connected`, and no app session opens any of them whatever it carries. There is deliberately no impersonation: signing in as a user produces a credential indistinguishable from theirs, so it is excluded until it has its own design and security review."
107
121
  ],
108
122
  "configOptions": [
@@ -0,0 +1,65 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { readAuthenticatorData } from "./authData";
5
+ import { equalBytes, sha256 } from "./bytes";
6
+ import { CborError, cborBytes, decodeCbor } from "./cbor";
7
+ import { verifyEcdsa } from "./x509";
8
+
9
+ /** The checks an assertion can fail, each named in the refusal's `detail`. */
10
+ export type AppAttestAssertionCheck = "format" | "rpIdHash" | "signature" | "counter";
11
+
12
+ /** What {@link verifyAppAttestAssertion} judges. */
13
+ export interface AppAttestAssertionInput {
14
+ /** The assertion, decoded from the base64 `generateAssertion` hands over. */
15
+ assertion: Uint8Array;
16
+ /** The registered key's P-256 public point. */
17
+ publicKey: Uint8Array;
18
+ /** The App ID the key was registered for. */
19
+ appId: string;
20
+ /** What the app passed to `generateAssertion`. */
21
+ clientDataHash: Uint8Array;
22
+ /** The counter stored from the key's last accepted assertion, or 0 after registration. */
23
+ counter: number;
24
+ }
25
+
26
+ export type AppAttestAssertionResult =
27
+ | { ok: true; counter: number }
28
+ | { ok: false; check: AppAttestAssertionCheck; reason: string };
29
+
30
+ /**
31
+ * Verify an App Attest assertion, Apple's way: the signature is the key's ECDSA P-256 SHA-256 signature over
32
+ * SHA-256 of the authenticator data and the client data hash, the `rpIdHash` is the key's app's, and the counter is
33
+ * above the stored one. Answers the new counter, which the caller stores only if it is still above the stored one.
34
+ */
35
+ export async function verifyAppAttestAssertion(input: AppAttestAssertionInput): Promise<AppAttestAssertionResult> {
36
+ let signature: Uint8Array | undefined;
37
+ let authenticatorData: Uint8Array | undefined;
38
+ try {
39
+ const decoded = decodeCbor(input.assertion);
40
+ signature = cborBytes(decoded, "signature");
41
+ authenticatorData = cborBytes(decoded, "authenticatorData");
42
+ } catch (cause) {
43
+ if (!(cause instanceof CborError)) throw cause;
44
+ return { ok: false, check: "format", reason: `the assertion is not CBOR: ${cause.message}` };
45
+ }
46
+ const data = authenticatorData === undefined ? undefined : readAuthenticatorData(authenticatorData);
47
+ if (signature === undefined || authenticatorData === undefined || data === undefined) {
48
+ return { ok: false, check: "format", reason: "the assertion lacks a signature or authenticator data" };
49
+ }
50
+ if (!equalBytes(data.rpIdHash, await sha256(new TextEncoder().encode(input.appId)))) {
51
+ return { ok: false, check: "rpIdHash", reason: `the rpIdHash is not SHA-256 of ${input.appId}` };
52
+ }
53
+ const nonce = await sha256(authenticatorData, input.clientDataHash);
54
+ if (!(await verifyEcdsa({ curve: "P-256", point: input.publicKey }, "SHA-256", signature, nonce))) {
55
+ return { ok: false, check: "signature", reason: "the signature does not verify with the registered key" };
56
+ }
57
+ if (data.counter <= input.counter) {
58
+ return {
59
+ ok: false,
60
+ check: "counter",
61
+ reason: `the counter ${data.counter} does not increase on the stored ${input.counter}`,
62
+ };
63
+ }
64
+ return { ok: true, counter: data.counter };
65
+ }
@@ -0,0 +1,159 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { AppleAppIdentity } from "../config";
5
+ import { readAttestedAuthenticatorData } from "./authData";
6
+ import { equalBytes, sha256 } from "./bytes";
7
+ import { CborError, type CborValue, cborBytes, cborText, decodeCbor } from "./cbor";
8
+ import { DER_OCTET_STRING, DER_SEQUENCE, DerError, derChildren, expectTag, readDer } from "./der";
9
+ import { type Certificate, parseCertificate, verifyChain } from "./x509";
10
+
11
+ /** The App Attest environment an AAGUID names. */
12
+ export type AppAttestEnvironment = "production" | "development";
13
+
14
+ /** The checks an attestation can fail, each named in the refusal's `detail`. */
15
+ export type AppAttestationCheck =
16
+ | "format"
17
+ | "chain"
18
+ | "nonce"
19
+ | "keyId"
20
+ | "rpIdHash"
21
+ | "counter"
22
+ | "aaguid"
23
+ | "credentialId";
24
+
25
+ /** A key an attestation proved, ready to store. */
26
+ export interface AttestedAppAttestKey {
27
+ /** The key id: SHA-256 of {@link publicKey}. */
28
+ keyId: Uint8Array;
29
+ /** The P-256 public key, as an X9.62 uncompressed point. */
30
+ publicKey: Uint8Array;
31
+ /** The App ID the attestation was made for, `<TeamID>.<bundleId>`. */
32
+ appId: string;
33
+ environment: AppAttestEnvironment;
34
+ }
35
+
36
+ /** What {@link verifyAppAttestation} judges. */
37
+ export interface AppAttestationInput {
38
+ /** The attestation object, decoded from the base64 `attestKey` hands over. */
39
+ attestation: Uint8Array;
40
+ /** The key id, decoded from the base64 `generateKey` hands over. */
41
+ keyId: Uint8Array;
42
+ /** What the app passed to `attestKey`. */
43
+ clientDataHash: Uint8Array;
44
+ /** The apps allowed to attest. */
45
+ apps: readonly AppleAppIdentity[];
46
+ /** Whether a development AAGUID is accepted. A production one always is. */
47
+ allowDevelopment: boolean;
48
+ /** The root CA the chain must lead to, DER. */
49
+ root: Uint8Array;
50
+ now: Date;
51
+ }
52
+
53
+ export type AppAttestationResult =
54
+ | { ok: true; key: AttestedAppAttestKey }
55
+ | { ok: false; check: AppAttestationCheck; reason: string };
56
+
57
+ /** The leaf extension holding the nonce: a SEQUENCE holding `[1]` holding an OCTET STRING. */
58
+ const NONCE_EXTENSION = "1.2.840.113635.100.8.2";
59
+
60
+ const AAGUIDS: Record<AppAttestEnvironment, Uint8Array> = {
61
+ production: new Uint8Array([...new TextEncoder().encode("appattest"), 0, 0, 0, 0, 0, 0, 0]),
62
+ development: new TextEncoder().encode("appattestdevelop"),
63
+ };
64
+
65
+ const refuse = (check: AppAttestationCheck, reason: string): AppAttestationResult => ({ ok: false, check, reason });
66
+
67
+ /** `apple-appattest` statement parts, or `undefined` for anything else. */
68
+ function statement(value: CborValue): { x5c: Uint8Array[]; authData: Uint8Array } | undefined {
69
+ if (cborText(value, "fmt") !== "apple-appattest") return undefined;
70
+ const authData = cborBytes(value, "authData");
71
+ const attStmt = value instanceof Map ? value.get("attStmt") : undefined;
72
+ const x5c = attStmt instanceof Map ? attStmt.get("x5c") : undefined;
73
+ if (authData === undefined || !Array.isArray(x5c) || !x5c.every((cert) => cert instanceof Uint8Array)) {
74
+ return undefined;
75
+ }
76
+ return { x5c: x5c as Uint8Array[], authData };
77
+ }
78
+
79
+ function nonceOf(leaf: Certificate): Uint8Array | undefined {
80
+ const value = leaf.extensions.get(NONCE_EXTENSION);
81
+ if (value === undefined) return undefined;
82
+ try {
83
+ const [tagged] = derChildren(expectTag(readDer(value), DER_SEQUENCE, "the nonce extension"));
84
+ if (tagged?.tag !== 0xa1) return undefined;
85
+ const [nonce] = derChildren(tagged);
86
+ return expectTag(nonce, DER_OCTET_STRING, "the nonce").content;
87
+ } catch (cause) {
88
+ if (cause instanceof DerError) return undefined;
89
+ throw cause;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Verify an App Attest attestation object, Apple's way: the certificate chain leads to `root`, the leaf's nonce
95
+ * extension is SHA-256 of the authenticator data and the client data hash, the leaf's key hashes to the key id,
96
+ * the `rpIdHash` is an allowed app's, the counter is zero, the AAGUID is an accepted environment's, and the
97
+ * credential id is the key id. Answers the first check that fails.
98
+ */
99
+ export async function verifyAppAttestation(input: AppAttestationInput): Promise<AppAttestationResult> {
100
+ let parts: ReturnType<typeof statement>;
101
+ try {
102
+ parts = statement(decodeCbor(input.attestation));
103
+ } catch (cause) {
104
+ if (!(cause instanceof CborError)) throw cause;
105
+ return refuse("format", `the attestation object is not CBOR: ${cause.message}`);
106
+ }
107
+ if (parts === undefined) return refuse("format", "the attestation object is not an apple-appattest statement");
108
+ if (parts.x5c.length !== 2) return refuse("chain", "x5c does not hold exactly the leaf and the intermediate");
109
+
110
+ let chain: Certificate[];
111
+ let root: Certificate;
112
+ try {
113
+ chain = parts.x5c.map(parseCertificate);
114
+ root = parseCertificate(input.root);
115
+ } catch (cause) {
116
+ if (!(cause instanceof DerError)) throw cause;
117
+ return refuse("chain", `a certificate does not parse: ${cause.message}`);
118
+ }
119
+ const chained = await verifyChain(chain, root, input.now);
120
+ if (!chained.ok) return refuse("chain", chained.reason);
121
+ const leaf = chain[0] as Certificate;
122
+
123
+ const nonce = nonceOf(leaf);
124
+ if (nonce === undefined) return refuse("nonce", "the leaf certificate carries no nonce extension");
125
+ if (!equalBytes(nonce, await sha256(parts.authData, input.clientDataHash))) {
126
+ return refuse("nonce", "the leaf certificate's nonce is not bound to this challenge");
127
+ }
128
+
129
+ if (leaf.publicKey.curve !== "P-256") return refuse("keyId", "the leaf certificate's key is not on P-256");
130
+ if (!equalBytes(await sha256(leaf.publicKey.point), input.keyId)) {
131
+ return refuse("keyId", "the leaf certificate's key does not hash to the key id");
132
+ }
133
+
134
+ const authData = readAttestedAuthenticatorData(parts.authData);
135
+ if (authData === undefined) return refuse("format", "the authenticator data is too short");
136
+
137
+ let appId: string | undefined;
138
+ for (const app of input.apps) {
139
+ const candidate = `${app.teamId}.${app.bundleId}`;
140
+ if (equalBytes(await sha256(new TextEncoder().encode(candidate)), authData.rpIdHash)) appId = candidate;
141
+ }
142
+ if (appId === undefined) return refuse("rpIdHash", "the rpIdHash is not SHA-256 of an allowed app's App ID");
143
+
144
+ if (authData.counter !== 0) return refuse("counter", `an attestation's counter is ${authData.counter}, not 0`);
145
+
146
+ const environment = (Object.keys(AAGUIDS) as AppAttestEnvironment[]).find((name) =>
147
+ equalBytes(AAGUIDS[name], authData.aaguid),
148
+ );
149
+ if (environment === undefined) return refuse("aaguid", "the AAGUID is neither App Attest environment's");
150
+ if (environment === "development" && !input.allowDevelopment) {
151
+ return refuse("aaguid", "a development AAGUID is refused here: only production keys are accepted");
152
+ }
153
+
154
+ if (!equalBytes(authData.credentialId, input.keyId)) {
155
+ return refuse("credentialId", "the credential id is not the key id");
156
+ }
157
+
158
+ return { ok: true, key: { keyId: input.keyId, publicKey: leaf.publicKey.point, appId, environment } };
159
+ }
@@ -0,0 +1,45 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /** The authenticator data App Attest signs over, as far as a verifier reads it. */
5
+ export interface AuthenticatorData {
6
+ /** SHA-256 of the App ID, `<TeamID>.<bundleId>`. */
7
+ rpIdHash: Uint8Array;
8
+ /** How many assertions the key has made: 0 in an attestation, then strictly increasing. */
9
+ counter: number;
10
+ }
11
+
12
+ /** An attestation's authenticator data, which also carries the attested credential. */
13
+ export interface AttestedAuthenticatorData extends AuthenticatorData {
14
+ /** `appattestdevelop`, or `appattest` and seven zero bytes. */
15
+ aaguid: Uint8Array;
16
+ /** The key id the credential was created under. */
17
+ credentialId: Uint8Array;
18
+ }
19
+
20
+ /** The header every authenticator data starts with: `rpIdHash`, flags, counter. */
21
+ const HEADER = 37;
22
+
23
+ /** Read an assertion's authenticator data, or answer `undefined` when it is too short to hold one. */
24
+ export function readAuthenticatorData(bytes: Uint8Array): AuthenticatorData | undefined {
25
+ if (bytes.length < HEADER) return undefined;
26
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27
+ return { rpIdHash: bytes.slice(0, 32), counter: view.getUint32(33) };
28
+ }
29
+
30
+ /**
31
+ * Read an attestation's authenticator data, through the credential id. What follows it, the COSE key and any
32
+ * extensions, is not read: the public key is taken from the certificate, whose digest the key id must match.
33
+ */
34
+ export function readAttestedAuthenticatorData(bytes: Uint8Array): AttestedAuthenticatorData | undefined {
35
+ const header = readAuthenticatorData(bytes);
36
+ if (header === undefined || bytes.length < HEADER + 18) return undefined;
37
+ const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint16(HEADER + 16);
38
+ const start = HEADER + 18;
39
+ if (bytes.length < start + length) return undefined;
40
+ return {
41
+ ...header,
42
+ aaguid: bytes.slice(HEADER, HEADER + 16),
43
+ credentialId: bytes.slice(start, start + length),
44
+ };
45
+ }
@@ -0,0 +1,29 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
5
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
6
+
7
+ /**
8
+ * Decode base64 as Apple's APIs hand it over (standard alphabet, padded) or as a client may re-encode it
9
+ * (url alphabet, unpadded). Answers `undefined` for anything else, never a best guess.
10
+ */
11
+ export function decodeBase64(value: string): Uint8Array | undefined {
12
+ let standard: string;
13
+ if (BASE64.test(value)) {
14
+ if (value.includes("=") && value.length % 4 !== 0) return undefined;
15
+ standard = value.replace(/=+$/, "");
16
+ } else if (BASE64URL.test(value)) {
17
+ standard = value.replace(/-/g, "+").replace(/_/g, "/");
18
+ } else {
19
+ return undefined;
20
+ }
21
+ if (standard.length % 4 === 1) return undefined;
22
+ let binary: string;
23
+ try {
24
+ binary = atob(standard + "=".repeat((4 - (standard.length % 4)) % 4));
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
29
+ }
@@ -0,0 +1,18 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /** Whether two byte strings are equal. Every input compared here is public, so the early exit leaks nothing. */
5
+ export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
6
+ return a.length === b.length && a.every((byte, i) => byte === b[i]);
7
+ }
8
+
9
+ /** SHA-256 over the parts, in order. */
10
+ export async function sha256(...parts: Uint8Array[]): Promise<Uint8Array> {
11
+ const message = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
12
+ let offset = 0;
13
+ for (const part of parts) {
14
+ message.set(part, offset);
15
+ offset += part.length;
16
+ }
17
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", message));
18
+ }