@pithy-sh/auth 0.15.3 → 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
@@ -29,6 +29,9 @@ import type { SessionSecretVersions } from "./sessionSecrets";
29
29
  * - `auth-microsoft-credentials` — the Microsoft Entra ID app registration's client id, client secret,
30
30
  * and tenant, as a typed JSON value. The tenant rides inside because it means nothing apart from the
31
31
  * registration it belongs to. Rotatable: an Entra client secret expires (24 months at most).
32
+ * - `auth-play-integrity-service-account` — the Google Cloud service account JSON key the Worker decodes Play
33
+ * Integrity tokens with. Read only when an Android attestation arrives; rotated by adding a key in Google
34
+ * Cloud Console, not on our schedule.
32
35
  */
33
36
  export const AUTH_SESSION_SECRET = "auth-session-secret";
34
37
  export const AUTH_GOOGLE_CREDENTIALS = "auth-google-credentials";
@@ -36,9 +39,10 @@ export const AUTH_APPLE_CREDENTIALS = "auth-apple-credentials";
36
39
  export const AUTH_FACEBOOK_CREDENTIALS = "auth-facebook-credentials";
37
40
  export const AUTH_GITHUB_CREDENTIALS = "auth-github-credentials";
38
41
  export const AUTH_MICROSOFT_CREDENTIALS = "auth-microsoft-credentials";
42
+ export const AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT = "auth-play-integrity-service-account";
39
43
 
40
44
  /**
41
- * The JWKS private keys, as `auth-session-secret`'s overlap names them (#602).
45
+ * The JWKS private keys, as `auth-session-secret`'s overlap names them.
42
46
  *
43
47
  * Better Auth encrypts every key in `pithy_auth_jwks` under the session secret, and a key never expires —
44
48
  * so retiring the version one is sealed under would leave a signing key nothing can open. The session
@@ -181,6 +185,52 @@ export const MicrosoftOAuthCredentials = z
181
185
  .describe("A Microsoft Entra ID credential set (`clientId` + `clientSecret` + `tenantId`) for one environment.");
182
186
  export type MicrosoftOAuthCredentials = z.infer<typeof MicrosoftOAuthCredentials>;
183
187
 
188
+ /**
189
+ * The Google Cloud service account key Play Integrity tokens are decoded with: the JSON file Google Cloud
190
+ * Console downloads, pasted whole. Fields auth does not read are dropped on write.
191
+ */
192
+ export const PlayIntegrityServiceAccount = z
193
+ .object({
194
+ type: z
195
+ .literal("service_account")
196
+ .optional()
197
+ .meta({ multiline: false })
198
+ .describe("The key file's kind. Google writes `service_account`."),
199
+ project_id: z
200
+ .string()
201
+ .optional()
202
+ .meta({ multiline: false })
203
+ .describe("The Google Cloud project the service account belongs to, linked to the app in Play Console."),
204
+ private_key_id: z
205
+ .string()
206
+ .optional()
207
+ .meta({ multiline: false })
208
+ .describe("The key's id, sent as the assertion's `kid` so Google picks the right public key."),
209
+ private_key: z
210
+ .string()
211
+ .min(1)
212
+ .meta({ multiline: true })
213
+ .describe("The RSA private key, a PKCS#8 PEM. It spans many lines, so paste the whole JSON file."),
214
+ client_email: z
215
+ .string()
216
+ .min(1)
217
+ .meta({ multiline: false })
218
+ .describe("The service account's address, such as `play-integrity@my-project.iam.gserviceaccount.com`."),
219
+ client_id: z
220
+ .string()
221
+ .optional()
222
+ .meta({ multiline: false })
223
+ .describe("The service account's numeric id. Not read; kept so the stored value matches the file."),
224
+ token_uri: z
225
+ .string()
226
+ .regex(/^https:\/\//, "The token endpoint is an https URL.")
227
+ .optional()
228
+ .meta({ multiline: false })
229
+ .describe("Google's OAuth token endpoint. Defaults to `https://oauth2.googleapis.com/token`."),
230
+ })
231
+ .describe("A Google Cloud service account JSON key, for decoding Play Integrity tokens in one environment.");
232
+ export type PlayIntegrityServiceAccount = z.infer<typeof PlayIntegrityServiceAccount>;
233
+
184
234
  /**
185
235
  * Where a human goes for each OAuth credential pair, and where the same human rotates it.
186
236
  *
@@ -195,6 +245,7 @@ const FACEBOOK_APPS_PAGE = "https://developers.facebook.com/apps/";
195
245
  const GITHUB_OAUTH_APPS_PAGE = "https://github.com/settings/developers";
196
246
  const MICROSOFT_APP_REGISTRATIONS_PAGE =
197
247
  "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade";
248
+ const GOOGLE_SERVICE_ACCOUNTS_PAGE = "https://console.cloud.google.com/iam-admin/serviceaccounts";
198
249
 
199
250
  export const authSecretsRegistry = defineSecretRegistry({
200
251
  // `devValue` is the whole difference between an app that runs after `pithy add auth` and one that
@@ -210,11 +261,11 @@ export const authSecretsRegistry = defineSecretRegistry({
210
261
  // a session signature, so the kit both makes it and replaces it.
211
262
  origin: { kind: "minted", recipe: { kind: "random", bytes: 32, encoding: "base64url" } },
212
263
  rotation: { kind: "local" },
213
- // The default session lifetime's overlap, and the JWKS keys sealed under it (#602). `auth()` declares
264
+ // The default session lifetime's overlap, and the JWKS keys sealed under it. `auth()` declares
214
265
  // its own from the configured `sessionExpiresIn`; this is what a module reading the secret sees.
215
266
  overlap: { days: 7, minimumDays: 7, reencrypt: [AUTH_JWKS_DEPENDENT] },
216
267
  },
217
- // The five below are `obtained` and rotate `manual`, and each names the page rather than the product.
268
+ // The six below are `obtained` and rotate `manual`, and each names the page rather than the product.
218
269
  // An adopter searching Google's console for which of four credential types "client secret" means is the
219
270
  // gap this closes — and nothing will ever mint one, so saying where is the whole of what the kit can do.
220
271
  [AUTH_GOOGLE_CREDENTIALS]: {
@@ -262,10 +313,19 @@ export const authSecretsRegistry = defineSecretRegistry({
262
313
  origin: { kind: "obtained", issuer: "microsoft", documentation: MICROSOFT_APP_REGISTRATIONS_PAGE },
263
314
  rotation: { kind: "manual", issuer: "microsoft", documentation: MICROSOFT_APP_REGISTRATIONS_PAGE },
264
315
  },
316
+ [AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT]: {
317
+ backend: "d1",
318
+ scope: "environment",
319
+ rotatable: false,
320
+ valueType: "json",
321
+ schema: PlayIntegrityServiceAccount,
322
+ origin: { kind: "obtained", issuer: "google", documentation: GOOGLE_SERVICE_ACCOUNTS_PAGE },
323
+ rotation: { kind: "manual", issuer: "google", documentation: GOOGLE_SERVICE_ACCOUNTS_PAGE },
324
+ },
265
325
  });
266
326
 
267
327
  /**
268
- * **The registry `auth()` contributes, from its own configuration (#602).**
328
+ * **The registry `auth()` contributes, from its own configuration.**
269
329
  *
270
330
  * The session secret's overlap follows the configured session lifetime — {@link sessionSecretOverlapDays} —
271
331
  * and it is both the overlap and its floor: an adopter who lengthens sessions lengthens the overlap with
@@ -308,7 +368,7 @@ export function authSecretsRegistryFor(config: {
308
368
  }
309
369
 
310
370
  /**
311
- * Which provider a credential belongs to — the join the CLI must never make by spelling (#541).
371
+ * Which provider a credential belongs to — the join the CLI must never make by spelling.
312
372
  *
313
373
  * `auth-apple-credentials` and the `apple` config key look like each other and that is a coincidence:
314
374
  * nothing makes a secret name and a config key the same thing, and a reporting command that matched
@@ -329,9 +389,9 @@ export type AuthProviderToggles = Record<(typeof PROVIDER_CREDENTIALS)[number][0
329
389
  * **The provider credentials this composition cannot reach**, as the `inapplicableSecrets` contribution.
330
390
  *
331
391
  * Auth declares five credentials whether or not a project runs five providers, so a project on Google
332
- * and GitHub carries two secrets nothing will ever read. `pithy doctor` asked for them every run under
333
- * *"fine to leave until you need it"* — softening, not silence, and "until you need it" is wrong about a
334
- * provider the configuration has not enabled.
392
+ * and GitHub carries two secrets nothing will ever read. A disabled provider's credential is listed as not
393
+ * applicable rather than as outstanding work: "set it until you need it" is wrong about a provider the
394
+ * configuration has not enabled.
335
395
  *
336
396
  * **The session secret is never in here**, and that is the line this draws: it is read on every sign-in
337
397
  * whatever the providers are, so it is outstanding work in every project that has not set it.
@@ -355,7 +415,7 @@ export async function resolveSessionSecret(env: SecretsStoreEnv): Promise<string
355
415
  }
356
416
 
357
417
  /**
358
- * Resolve every retained version of the session secret (#602) — what an instance needs to open values sealed
418
+ * Resolve every retained version of the session secret: what an instance needs to open values sealed
359
419
  * under the previous version, and what a credential signed under it is verified against. One read through
360
420
  * the same cached accessor as {@link resolveSessionSecret}.
361
421
  */
@@ -388,6 +448,25 @@ export async function resolveGithubCredentials(env: SecretsStoreEnv): Promise<Gi
388
448
  return secrets.get(AUTH_GITHUB_CREDENTIALS);
389
449
  }
390
450
 
451
+ /**
452
+ * The Play Integrity service account when no environment of this composition allows an Android app: nothing
453
+ * there reads it.
454
+ */
455
+ export function inapplicablePlayIntegritySecret(attestation: {
456
+ environments: Record<string, { android: readonly unknown[] }>;
457
+ }): Record<string, string> {
458
+ const allowsAndroid = Object.values(attestation.environments).some((block) => block.android.length > 0);
459
+ return allowsAndroid
460
+ ? {}
461
+ : { [AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT]: "auth() allows no Android app to attest in any environment" };
462
+ }
463
+
464
+ /** Resolve the Play Integrity service account for this invocation (only call for an Android attestation). */
465
+ export async function resolvePlayIntegrityServiceAccount(env: SecretsStoreEnv): Promise<PlayIntegrityServiceAccount> {
466
+ const secrets = await sharedSecretsStore(env, authSecretsRegistry);
467
+ return secrets.get(AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT);
468
+ }
469
+
391
470
  /** Resolve the Microsoft Entra ID credentials for this invocation (only call when Microsoft is enabled). */
392
471
  export async function resolveMicrosoftCredentials(env: SecretsStoreEnv): Promise<MicrosoftOAuthCredentials> {
393
472
  const secrets = await sharedSecretsStore(env, authSecretsRegistry);
@@ -0,0 +1,28 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /** How the issue path finds the challenges that have run out. */
8
+ const EXPIRES_INDEX = "pithyAuthAttestationChallengesExpiresAtIdx";
9
+
10
+ /**
11
+ * `pithy_auth_attestation_challenges`: one row per challenge the attestation challenge route issued and nobody
12
+ * has presented yet. See `../attestation/challenge.ts`. Every date is `integer`, ms-epoch.
13
+ */
14
+ export const auth_0009_attestation_challenges: Migration = {
15
+ async up(db: Kysely<unknown>): Promise<void> {
16
+ await db.schema
17
+ .createTable("pithyAuthAttestationChallenges")
18
+ .addColumn("id", "text", (c) => c.primaryKey())
19
+ .addColumn("issuedAt", "integer", (c) => c.notNull())
20
+ .addColumn("expiresAt", "integer", (c) => c.notNull())
21
+ .execute();
22
+ await db.schema.createIndex(EXPIRES_INDEX).on("pithyAuthAttestationChallenges").column("expiresAt").execute();
23
+ },
24
+ async down(db: Kysely<unknown>): Promise<void> {
25
+ await db.schema.dropIndex(EXPIRES_INDEX).execute();
26
+ await db.schema.dropTable("pithyAuthAttestationChallenges").execute();
27
+ },
28
+ };
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { Kysely } from "kysely";
5
+ import type { Migration } from "kysely/migration";
6
+
7
+ /**
8
+ * `pithy_auth_app_attest_keys`: one row per App Attest key an iOS app registered. See `../data/appAttestKey.ts`.
9
+ * Every date is `integer`, ms-epoch.
10
+ */
11
+ export const auth_0010_app_attest_keys: Migration = {
12
+ async up(db: Kysely<unknown>): Promise<void> {
13
+ await db.schema
14
+ .createTable("pithyAuthAppAttestKeys")
15
+ .addColumn("id", "text", (c) => c.primaryKey())
16
+ .addColumn("publicKey", "text", (c) => c.notNull())
17
+ .addColumn("appId", "text", (c) => c.notNull())
18
+ .addColumn("environment", "text", (c) => c.notNull())
19
+ .addColumn("counter", "integer", (c) => c.notNull())
20
+ .addColumn("createdAt", "integer", (c) => c.notNull())
21
+ .addColumn("lastUsedAt", "integer")
22
+ .execute();
23
+ },
24
+ async down(db: Kysely<unknown>): Promise<void> {
25
+ await db.schema.dropTable("pithyAuthAppAttestKeys").execute();
26
+ },
27
+ };
@@ -9,6 +9,8 @@ import { auth_0005_purge_once } from "./0005_purge_once";
9
9
  import { auth_0006_verification_outcomes } from "./0006_verification_outcomes";
10
10
  import { auth_0007_erasure_record } from "./0007_erasure_record";
11
11
  import { auth_0008_last_active } from "./0008_last_active";
12
+ import { auth_0009_attestation_challenges } from "./0009_attestation_challenges";
13
+ import { auth_0010_app_attest_keys } from "./0010_app_attest_keys";
12
14
 
13
15
  /**
14
16
  * Every migration `@pithy-sh/auth` ships, keyed as `pithy migrate` composes them.
@@ -20,7 +22,7 @@ import { auth_0008_last_active } from "./0008_last_active";
20
22
  * migration. Adding a `0002` turned all five into a schema one column short of the code, and the symptom
21
23
  * was `table pithy_auth_sessions has no column named authenticated_at` in thirteen unrelated tests.
22
24
  *
23
- * `0003` through `0007` appended here and reached every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
25
+ * Every later migration is appended here and reaches every reader, which is the point. `0001_init.workers.test.ts` is deliberately not a reader:
24
26
  * its subject is that one migration's own `up` and `down`, so it names it directly.
25
27
  */
26
28
  export const AUTH_MIGRATIONS = {
@@ -32,4 +34,6 @@ export const AUTH_MIGRATIONS = {
32
34
  "0006_verification_outcomes": auth_0006_verification_outcomes,
33
35
  "0007_erasure_record": auth_0007_erasure_record,
34
36
  "0008_last_active": auth_0008_last_active,
37
+ "0009_attestation_challenges": auth_0009_attestation_challenges,
38
+ "0010_app_attest_keys": auth_0010_app_attest_keys,
35
39
  } as const;
@@ -0,0 +1,399 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
5
+
6
+ /**
7
+ * A stand-in for Apple's App Attest service and a device's Secure Enclave, built on WebCrypto.
8
+ *
9
+ * It mints a root and an intermediate in the shape Apple's are (P-384, ECDSA with SHA-384), and per key a P-256
10
+ * leaf signed with SHA-256 that carries the nonce extension `1.2.840.113635.100.8.2`, then the attestation object
11
+ * and assertions exactly as `DCAppAttestService` returns them. A test trusts {@link AppAttestAuthority.root} in
12
+ * place of Apple's, which is the only difference from a real device: every byte goes through the same reader.
13
+ */
14
+
15
+ type Bytes = Uint8Array;
16
+
17
+ function concat(...parts: Bytes[]): Bytes {
18
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
19
+ let offset = 0;
20
+ for (const part of parts) {
21
+ out.set(part, offset);
22
+ offset += part.length;
23
+ }
24
+ return out;
25
+ }
26
+
27
+ function standardBase64(bytes: Bytes): string {
28
+ let binary = "";
29
+ for (const byte of bytes) binary += String.fromCharCode(byte);
30
+ return btoa(binary);
31
+ }
32
+
33
+ async function sha256(...parts: Bytes[]): Promise<Bytes> {
34
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", concat(...parts)));
35
+ }
36
+
37
+ // DER writer.
38
+
39
+ function tlv(tag: number, content: Bytes): Bytes {
40
+ const length = content.length;
41
+ const header =
42
+ length < 0x80
43
+ ? [length]
44
+ : length < 0x100
45
+ ? [0x81, length]
46
+ : length < 0x10000
47
+ ? [0x82, length >> 8, length & 0xff]
48
+ : [0x83, length >> 16, (length >> 8) & 0xff, length & 0xff];
49
+ return concat(new Uint8Array([tag, ...header]), content);
50
+ }
51
+ const seq = (...items: Bytes[]) => tlv(0x30, concat(...items));
52
+ const set = (...items: Bytes[]) => tlv(0x31, concat(...items));
53
+ const octets = (bytes: Bytes) => tlv(0x04, bytes);
54
+ const bits = (bytes: Bytes) => tlv(0x03, concat(new Uint8Array([0]), bytes));
55
+ const utf8 = (text: string) => tlv(0x0c, new TextEncoder().encode(text));
56
+
57
+ function integer(bytes: Bytes): Bytes {
58
+ let start = 0;
59
+ while (start < bytes.length - 1 && bytes[start] === 0) start++;
60
+ const digits = bytes.subarray(start);
61
+ return tlv(0x02, (digits[0] as number) & 0x80 ? concat(new Uint8Array([0]), digits) : digits);
62
+ }
63
+
64
+ function oid(dotted: string): Bytes {
65
+ const [first, second, ...rest] = dotted.split(".").map(Number) as number[];
66
+ const out = [(first as number) * 40 + (second as number)];
67
+ for (const arc of rest) {
68
+ const chunk = [arc & 0x7f];
69
+ for (let value = Math.floor(arc / 128); value > 0; value = Math.floor(value / 128))
70
+ chunk.unshift((value & 0x7f) | 0x80);
71
+ out.push(...chunk);
72
+ }
73
+ return tlv(0x06, new Uint8Array(out));
74
+ }
75
+
76
+ function time(date: Date): Bytes {
77
+ const iso = date.toISOString();
78
+ const text = `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
79
+ return tlv(0x17, new TextEncoder().encode(text));
80
+ }
81
+
82
+ const name = (commonName: string) =>
83
+ seq(set(seq(oid("2.5.4.3"), utf8(commonName))), set(seq(oid("2.5.4.10"), utf8("Apple Inc."))));
84
+
85
+ const CURVE_OID = { "P-256": "1.2.840.10045.3.1.7", "P-384": "1.3.132.0.34" } as const;
86
+ const SIGNATURE_OID = { "SHA-256": "1.2.840.10045.4.3.2", "SHA-384": "1.2.840.10045.4.3.3" } as const;
87
+ const FIELD = { "P-256": 32, "P-384": 48 } as const;
88
+
89
+ type Curve = keyof typeof CURVE_OID;
90
+ type Hash = keyof typeof SIGNATURE_OID;
91
+
92
+ interface KeyPair {
93
+ curve: Curve;
94
+ privateKey: CryptoKey;
95
+ point: Bytes;
96
+ }
97
+
98
+ async function keyPair(curve: Curve): Promise<KeyPair> {
99
+ const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: curve }, true, [
100
+ "sign",
101
+ "verify",
102
+ ])) as CryptoKeyPair;
103
+ const point = new Uint8Array((await crypto.subtle.exportKey("raw", pair.publicKey)) as ArrayBuffer);
104
+ return { curve, privateKey: pair.privateKey, point };
105
+ }
106
+
107
+ /** An ECDSA signature, DER-encoded as X.509 and App Attest carry it. */
108
+ async function sign(key: KeyPair, hash: Hash, data: Bytes): Promise<Bytes> {
109
+ const raw = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash }, key.privateKey, data));
110
+ const size = FIELD[key.curve];
111
+ return seq(integer(raw.subarray(0, size)), integer(raw.subarray(size)));
112
+ }
113
+
114
+ interface CertificateSpec {
115
+ serial: number;
116
+ issuer: string;
117
+ subject: string;
118
+ subjectKey: KeyPair;
119
+ signer: KeyPair;
120
+ hash: Hash;
121
+ notBefore: Date;
122
+ notAfter: Date;
123
+ ca: boolean;
124
+ extensions?: Bytes[];
125
+ }
126
+
127
+ async function certificate(spec: CertificateSpec): Promise<Bytes> {
128
+ const algorithm = seq(oid(SIGNATURE_OID[spec.hash]));
129
+ const spki = seq(seq(oid("1.2.840.10045.2.1"), oid(CURVE_OID[spec.subjectKey.curve])), bits(spec.subjectKey.point));
130
+ const extensions = [
131
+ ...(spec.ca
132
+ ? [seq(oid("2.5.29.19"), tlv(0x01, new Uint8Array([0xff])), octets(seq(tlv(0x01, new Uint8Array([0xff])))))]
133
+ : []),
134
+ ...(spec.extensions ?? []),
135
+ ];
136
+ const tbs = seq(
137
+ tlv(0xa0, integer(new Uint8Array([2]))),
138
+ integer(new Uint8Array([spec.serial >> 8, spec.serial & 0xff])),
139
+ algorithm,
140
+ name(spec.issuer),
141
+ seq(time(spec.notBefore), time(spec.notAfter)),
142
+ name(spec.subject),
143
+ spki,
144
+ ...(extensions.length > 0 ? [tlv(0xa3, seq(...extensions))] : []),
145
+ );
146
+ return seq(tbs, algorithm, bits(await sign(spec.signer, spec.hash, tbs)));
147
+ }
148
+
149
+ // CBOR writer.
150
+
151
+ type CborIn = number | string | Bytes | CborIn[] | Map<CborIn, CborIn>;
152
+
153
+ function cborHead(major: number, value: number): Bytes {
154
+ if (value < 24) return new Uint8Array([(major << 5) | value]);
155
+ if (value < 0x100) return new Uint8Array([(major << 5) | 24, value]);
156
+ if (value < 0x10000) return new Uint8Array([(major << 5) | 25, value >> 8, value & 0xff]);
157
+ return new Uint8Array([(major << 5) | 26, value >>> 24, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]);
158
+ }
159
+
160
+ function cbor(value: CborIn): Bytes {
161
+ if (typeof value === "number") return value >= 0 ? cborHead(0, value) : cborHead(1, -1 - value);
162
+ if (typeof value === "string") {
163
+ const bytes = new TextEncoder().encode(value);
164
+ return concat(cborHead(3, bytes.length), bytes);
165
+ }
166
+ if (value instanceof Uint8Array) return concat(cborHead(2, value.length), value);
167
+ if (Array.isArray(value)) return concat(cborHead(4, value.length), ...value.map(cbor));
168
+ return concat(cborHead(5, value.size), ...[...value.entries()].flatMap(([k, v]) => [cbor(k), cbor(v)]));
169
+ }
170
+
171
+ function uint32(value: number): Bytes {
172
+ return new Uint8Array([value >>> 24, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]);
173
+ }
174
+
175
+ const AAGUID = {
176
+ production: concat(new TextEncoder().encode("appattest"), new Uint8Array(7)),
177
+ development: new TextEncoder().encode("appattestdevelop"),
178
+ };
179
+
180
+ /** What to put in one attestation. Each override breaks the one field a refusal test is about. */
181
+ export interface AttestOptions {
182
+ /** `<TeamID>.<bundleId>`, hashed into the authenticator data's `rpIdHash`. */
183
+ appId: string;
184
+ /** What the app passed to `attestKey`. */
185
+ clientDataHash: Bytes;
186
+ environment?: "production" | "development";
187
+ /** The authenticator data's counter. Apple's is always 0. */
188
+ counter?: number;
189
+ /** A nonce to write into the leaf in place of the right one. */
190
+ nonce?: Bytes;
191
+ /** A credential id to write in place of the key id. */
192
+ credentialId?: Bytes;
193
+ /** Leaf validity, defaulting to an hour either side of the authority's `now`. */
194
+ notBefore?: Date;
195
+ notAfter?: Date;
196
+ }
197
+
198
+ /** One attested key. */
199
+ export interface AttestedKey {
200
+ /** The key id as `generateKey` hands it over: standard base64 of SHA-256 over the public point. */
201
+ keyId: string;
202
+ /** The attestation object as `attestKey` hands it over: standard base64. */
203
+ attestation: string;
204
+ /** The raw public point. */
205
+ publicKey: Bytes;
206
+ /** An assertion over `clientDataHash`, as `generateAssertion` hands it over: standard base64. */
207
+ assert(options: { appId: string; clientDataHash: Bytes; counter: number }): Promise<string>;
208
+ }
209
+
210
+ /** A key generated in the fake Secure Enclave and not yet attested, as `generateKey` leaves it. */
211
+ export interface GeneratedKey {
212
+ /** The key id as `generateKey` hands it over: standard base64 of SHA-256 over the public point. */
213
+ keyId: string;
214
+ /** The raw public point. */
215
+ publicKey: Bytes;
216
+ /** Apple's attestation of this key, as `attestKey` hands it over: standard base64. */
217
+ attest(options: AttestOptions): Promise<string>;
218
+ /** An assertion over `clientDataHash`, as `generateAssertion` hands it over: standard base64. */
219
+ assert(options: { appId: string; clientDataHash: Bytes; counter: number }): Promise<string>;
220
+ }
221
+
222
+ /** A fake App Attest service. */
223
+ export interface AppAttestAuthority {
224
+ /** The root to trust in place of Apple's, DER. */
225
+ root: Bytes;
226
+ /** Generate a key and attest to it. */
227
+ attest(options: AttestOptions): Promise<AttestedKey>;
228
+ /** Generate a key, to attest later: the two steps a device takes, `generateKey` then `attestKey`. */
229
+ generate(): Promise<GeneratedKey>;
230
+ }
231
+
232
+ /** Stand up a fake App Attest service whose certificates are valid around `now`. */
233
+ export async function appAttestAuthority(options: { now?: Date } = {}): Promise<AppAttestAuthority> {
234
+ const now = options.now ?? new Date();
235
+ const hours = (n: number) => new Date(now.getTime() + n * 3_600_000);
236
+ const rootKey = await keyPair("P-384");
237
+ const intermediateKey = await keyPair("P-384");
238
+ const rootName = "Test App Attestation Root CA";
239
+ const intermediateName = "Test App Attestation CA 1";
240
+ const root = await certificate({
241
+ serial: 1,
242
+ issuer: rootName,
243
+ subject: rootName,
244
+ subjectKey: rootKey,
245
+ signer: rootKey,
246
+ hash: "SHA-384",
247
+ notBefore: hours(-24 * 365),
248
+ notAfter: hours(24 * 365 * 20),
249
+ ca: true,
250
+ });
251
+ const intermediate = await certificate({
252
+ serial: 2,
253
+ issuer: rootName,
254
+ subject: intermediateName,
255
+ subjectKey: intermediateKey,
256
+ signer: rootKey,
257
+ hash: "SHA-384",
258
+ notBefore: hours(-24 * 365),
259
+ notAfter: hours(24 * 365 * 10),
260
+ ca: true,
261
+ });
262
+
263
+ async function generate(): Promise<GeneratedKey> {
264
+ const key = await keyPair("P-256");
265
+ const keyId = await sha256(key.point);
266
+ return {
267
+ keyId: standardBase64(keyId),
268
+ publicKey: key.point,
269
+ async attest(spec) {
270
+ const authData = concat(
271
+ await sha256(new TextEncoder().encode(spec.appId)),
272
+ new Uint8Array([0x40]),
273
+ uint32(spec.counter ?? 0),
274
+ AAGUID[spec.environment ?? "production"],
275
+ new Uint8Array([0, (spec.credentialId ?? keyId).length]),
276
+ spec.credentialId ?? keyId,
277
+ cbor(
278
+ new Map<CborIn, CborIn>([
279
+ [1, 2],
280
+ [3, -7],
281
+ [-1, 1],
282
+ [-2, key.point.subarray(1, 33)],
283
+ [-3, key.point.subarray(33)],
284
+ ]),
285
+ ),
286
+ );
287
+ const nonce = spec.nonce ?? (await sha256(authData, spec.clientDataHash));
288
+ const leaf = await certificate({
289
+ serial: 3,
290
+ issuer: intermediateName,
291
+ subject: Array.from(keyId, (byte) => byte.toString(16).padStart(2, "0")).join(""),
292
+ subjectKey: key,
293
+ signer: intermediateKey,
294
+ hash: "SHA-256",
295
+ notBefore: spec.notBefore ?? hours(-1),
296
+ notAfter: spec.notAfter ?? hours(72),
297
+ ca: false,
298
+ extensions: [seq(oid("1.2.840.113635.100.8.2"), octets(seq(tlv(0xa1, octets(nonce)))))],
299
+ });
300
+ return standardBase64(
301
+ cbor(
302
+ new Map<CborIn, CborIn>([
303
+ ["fmt", "apple-appattest"],
304
+ [
305
+ "attStmt",
306
+ new Map<CborIn, CborIn>([
307
+ ["x5c", [leaf, intermediate]],
308
+ ["receipt", new Uint8Array([1, 2, 3])],
309
+ ]),
310
+ ],
311
+ ["authData", authData],
312
+ ]),
313
+ ),
314
+ );
315
+ },
316
+ async assert({ appId, clientDataHash, counter }) {
317
+ const authenticatorData = concat(
318
+ await sha256(new TextEncoder().encode(appId)),
319
+ new Uint8Array([0x40]),
320
+ uint32(counter),
321
+ );
322
+ const signature = await sign(key, "SHA-256", await sha256(authenticatorData, clientDataHash));
323
+ return standardBase64(
324
+ cbor(
325
+ new Map<CborIn, CborIn>([
326
+ ["signature", signature],
327
+ ["authenticatorData", authenticatorData],
328
+ ]),
329
+ ),
330
+ );
331
+ },
332
+ };
333
+ }
334
+
335
+ return {
336
+ root,
337
+ generate,
338
+ async attest(spec) {
339
+ const key = await generate();
340
+ return { keyId: key.keyId, attestation: await key.attest(spec), publicKey: key.publicKey, assert: key.assert };
341
+ },
342
+ };
343
+ }
344
+
345
+ /** A key id as auth stores it: base64url of the 32 bytes. */
346
+ export function storedKeyId(keyId: string): string {
347
+ return base64UrlEncode(Uint8Array.from(atob(keyId), (char) => char.charCodeAt(0)));
348
+ }
349
+
350
+ /** A fake device's `@expo/app-integrity`: the shape `appAttestAttester` takes, over `authority`'s keys. */
351
+ export interface AppAttestDeviceModule {
352
+ readonly isSupported: boolean;
353
+ generateKeyAsync(): Promise<string>;
354
+ attestKeyAsync(keyId: string, challenge: string): Promise<string>;
355
+ generateAssertionAsync(keyId: string, challenge: string): Promise<string>;
356
+ /** Forget every key, as a reinstall or a restore to a new phone does: asserting with one then throws. */
357
+ wipe(): void;
358
+ /** Each call in order, with the string it was handed. */
359
+ readonly calls: string[];
360
+ }
361
+
362
+ /**
363
+ * `@expo/app-integrity`'s App Attest half on a fake device: the key lives in `authority`'s Secure Enclave stand-in,
364
+ * and each call hashes the string it is handed with SHA-256 over its UTF-8 into `clientDataHash`, as the native
365
+ * module does. Each key's counter rises by one per assertion, as the Secure Enclave's does.
366
+ */
367
+ export function appAttestDeviceModule(authority: AppAttestAuthority, appId: string): AppAttestDeviceModule {
368
+ const keys = new Map<string, { key: GeneratedKey; counter: number }>();
369
+ const calls: string[] = [];
370
+ const hash = (text: string) => sha256(new TextEncoder().encode(text));
371
+ const find = (keyId: string) => {
372
+ const entry = keys.get(keyId);
373
+ if (entry === undefined) throw new Error("invalidKey");
374
+ return entry;
375
+ };
376
+ return {
377
+ isSupported: true,
378
+ calls,
379
+ async generateKeyAsync() {
380
+ const key = await authority.generate();
381
+ keys.set(key.keyId, { key, counter: 0 });
382
+ calls.push(`generateKeyAsync -> ${key.keyId}`);
383
+ return key.keyId;
384
+ },
385
+ async attestKeyAsync(keyId, challenge) {
386
+ calls.push(`attestKeyAsync ${keyId} ${challenge}`);
387
+ return find(keyId).key.attest({ appId, clientDataHash: await hash(challenge) });
388
+ },
389
+ async generateAssertionAsync(keyId, challenge) {
390
+ calls.push(`generateAssertionAsync ${keyId} ${challenge}`);
391
+ const entry = find(keyId);
392
+ entry.counter += 1;
393
+ return entry.key.assert({ appId, clientDataHash: await hash(challenge), counter: entry.counter });
394
+ },
395
+ wipe() {
396
+ keys.clear();
397
+ },
398
+ };
399
+ }