@pithy-sh/auth 0.15.3 → 0.17.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 (209) 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 +49 -6
  63. package/dist/capability.d.ts.map +1 -1
  64. package/dist/capability.js +42 -7
  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 +19 -1
  80. package/dist/data/tables.d.ts.map +1 -1
  81. package/dist/data/tables.js +6 -2
  82. package/dist/data/userLifecycle.d.ts +1 -0
  83. package/dist/data/userLifecycle.d.ts.map +1 -1
  84. package/dist/data/userLifecycle.js +3 -2
  85. package/dist/hooks/runtime.d.ts +32 -0
  86. package/dist/hooks/runtime.d.ts.map +1 -0
  87. package/dist/hooks/runtime.js +25 -0
  88. package/dist/http/adminRoutes.d.ts.map +1 -1
  89. package/dist/http/adminRoutes.js +4 -2
  90. package/dist/http/devLoginRoute.js +3 -3
  91. package/dist/http/resolve.d.ts.map +1 -1
  92. package/dist/http/resolve.js +3 -2
  93. package/dist/http/responses.d.ts +15 -0
  94. package/dist/http/responses.d.ts.map +1 -1
  95. package/dist/http/responses.js +13 -2
  96. package/dist/http/routes.d.ts +5 -1
  97. package/dist/http/routes.d.ts.map +1 -1
  98. package/dist/http/routes.js +92 -25
  99. package/dist/http/schemas.d.ts +7 -0
  100. package/dist/http/schemas.d.ts.map +1 -1
  101. package/dist/http/schemas.js +7 -1
  102. package/dist/index.js +1 -1
  103. package/dist/instance/secrets.d.ts +86 -7
  104. package/dist/instance/secrets.d.ts.map +1 -1
  105. package/dist/instance/secrets.js +54 -8
  106. package/dist/lifecycle/erasure.d.ts.map +1 -1
  107. package/dist/lifecycle/erasure.js +2 -1
  108. package/dist/lifecycle/hooks.d.ts +18 -10
  109. package/dist/lifecycle/hooks.d.ts.map +1 -1
  110. package/dist/lifecycle/request.d.ts +2 -1
  111. package/dist/lifecycle/request.d.ts.map +1 -1
  112. package/dist/lifecycle/request.js +4 -1
  113. package/dist/lifecycle/transitions.d.ts +24 -16
  114. package/dist/lifecycle/transitions.d.ts.map +1 -1
  115. package/dist/lifecycle/transitions.js +27 -16
  116. package/dist/migrations/0009_attestation_challenges.d.ts +9 -0
  117. package/dist/migrations/0009_attestation_challenges.d.ts.map +1 -0
  118. package/dist/migrations/0009_attestation_challenges.js +21 -0
  119. package/dist/migrations/0010_app_attest_keys.d.ts +9 -0
  120. package/dist/migrations/0010_app_attest_keys.d.ts.map +1 -0
  121. package/dist/migrations/0010_app_attest_keys.js +17 -0
  122. package/dist/migrations/0011_retained_basis_key.d.ts +10 -0
  123. package/dist/migrations/0011_retained_basis_key.d.ts.map +1 -0
  124. package/dist/migrations/0011_retained_basis_key.js +18 -0
  125. package/dist/migrations/set.d.ts +4 -1
  126. package/dist/migrations/set.d.ts.map +1 -1
  127. package/dist/migrations/set.js +8 -2
  128. package/dist/purge/run.d.ts +11 -11
  129. package/dist/purge/run.d.ts.map +1 -1
  130. package/dist/purge/run.js +9 -8
  131. package/dist/purge/workflow.d.ts +7 -1
  132. package/dist/purge/workflow.d.ts.map +1 -1
  133. package/dist/purge/workflow.js +6 -2
  134. package/dist/seeds/devSession.js +1 -1
  135. package/dist/test-utils/appAttestDevice.d.ts +92 -0
  136. package/dist/test-utils/appAttestDevice.d.ts.map +1 -0
  137. package/dist/test-utils/appAttestDevice.js +282 -0
  138. package/dist/test-utils/appAttestSample.d.ts +22 -0
  139. package/dist/test-utils/appAttestSample.d.ts.map +1 -0
  140. package/dist/test-utils/appAttestSample.js +24 -0
  141. package/dist/test-utils/googlePlay.d.ts +47 -0
  142. package/dist/test-utils/googlePlay.d.ts.map +1 -0
  143. package/dist/test-utils/googlePlay.js +117 -0
  144. package/dist/test-utils/liveApp.d.ts +76 -36
  145. package/dist/test-utils/liveApp.d.ts.map +1 -1
  146. package/dist/test-utils/liveApp.js +16 -5
  147. package/dist/test-utils/rollbackThrough.d.ts +11 -0
  148. package/dist/test-utils/rollbackThrough.d.ts.map +1 -0
  149. package/dist/test-utils/rollbackThrough.js +16 -0
  150. package/dist/test-utils/scopedBackend.d.ts +25 -0
  151. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  152. package/dist/test-utils/scopedBackend.js +1 -1
  153. package/dist/version.generated.d.ts +1 -1
  154. package/dist/version.generated.js +1 -1
  155. package/docs/account-lifecycle.md +46 -10
  156. package/docs/attestation.md +173 -0
  157. package/package.json +5 -5
  158. package/pithy.manifest.json +14 -0
  159. package/src/attestation/appAttest/assertion.ts +65 -0
  160. package/src/attestation/appAttest/attestation.ts +159 -0
  161. package/src/attestation/appAttest/authData.ts +45 -0
  162. package/src/attestation/appAttest/base64.ts +29 -0
  163. package/src/attestation/appAttest/bytes.ts +18 -0
  164. package/src/attestation/appAttest/cbor.ts +116 -0
  165. package/src/attestation/appAttest/der.ts +126 -0
  166. package/src/attestation/appAttest/keys.ts +57 -0
  167. package/src/attestation/appAttest/root.ts +13 -0
  168. package/src/attestation/appAttest/verifier.ts +113 -0
  169. package/src/attestation/appAttest/x509.ts +209 -0
  170. package/src/attestation/challenge.ts +56 -0
  171. package/src/attestation/config.ts +118 -0
  172. package/src/attestation/errors.ts +60 -0
  173. package/src/attestation/gate.ts +105 -0
  174. package/src/attestation/playIntegrity/google.ts +239 -0
  175. package/src/attestation/playIntegrity/verdict.ts +149 -0
  176. package/src/attestation/playIntegrity/verifier.ts +77 -0
  177. package/src/attestation/verifier.ts +87 -0
  178. package/src/attestation/wire.ts +79 -0
  179. package/src/capability.ts +85 -16
  180. package/src/client/api.ts +73 -40
  181. package/src/client/attestation.ts +404 -0
  182. package/src/client/projection.ts +29 -4
  183. package/src/data/appAttestKey.ts +45 -0
  184. package/src/data/attestationChallenge.ts +23 -0
  185. package/src/data/tables.ts +5 -1
  186. package/src/data/userLifecycle.ts +9 -2
  187. package/src/hooks/runtime.ts +41 -0
  188. package/src/http/adminRoutes.ts +14 -7
  189. package/src/http/resolve.ts +8 -4
  190. package/src/http/responses.ts +29 -1
  191. package/src/http/routes.ts +128 -38
  192. package/src/http/schemas.ts +24 -0
  193. package/src/instance/secrets.ts +88 -9
  194. package/src/lifecycle/erasure.ts +2 -1
  195. package/src/lifecycle/hooks.ts +22 -10
  196. package/src/lifecycle/request.ts +4 -1
  197. package/src/lifecycle/transitions.ts +47 -28
  198. package/src/migrations/0009_attestation_challenges.ts +28 -0
  199. package/src/migrations/0010_app_attest_keys.ts +27 -0
  200. package/src/migrations/0011_retained_basis_key.ts +19 -0
  201. package/src/migrations/set.ts +7 -1
  202. package/src/purge/run.ts +29 -17
  203. package/src/purge/workflow.ts +7 -3
  204. package/src/test-utils/appAttestDevice.ts +399 -0
  205. package/src/test-utils/appAttestSample.ts +20 -0
  206. package/src/test-utils/googlePlay.ts +144 -0
  207. package/src/test-utils/liveApp.ts +31 -5
  208. package/src/test-utils/rollbackThrough.ts +24 -0
  209. package/src/version.generated.ts +1 -1
@@ -17,7 +17,7 @@
17
17
  *
18
18
  * **This is the only statement of the shape.** `@pithy-sh/ui-react`'s `templates/client-env.d.ts` — the
19
19
  * ambient declaration `pithy ui add react` copies into an adopter's Worker — is generated from this type
20
- * by `@pithy-sh/vite`'s `clientEnvDeclaration.ts` (#398). The unions and the per-field doc comments below
20
+ * by `@pithy-sh/vite`'s `clientEnvDeclaration.ts`. The unions and the per-field doc comments below
21
21
  * are emitted verbatim, so what is written here is what a screen author reads.
22
22
  */
23
23
  export type AuthClientProjection =
@@ -55,9 +55,8 @@ export type AuthClientProjection =
55
55
  *
56
56
  * **A second fact from {@link signUpEnabled}, and the screen needs both.** That one answers for
57
57
  * magic link and OTP; this answers per provider. A project can let email create accounts while
58
- * GitHub only signs existing ones in — which is the configuration #554 exists for — and with only
59
- * the global flag a screen renders "Signing in creates one." directly beneath a button that will
60
- * refuse (#559).
58
+ * GitHub only signs existing ones in, and with only the global flag a screen would promise an
59
+ * account directly beneath a button that will refuse.
61
60
  *
62
61
  * Optional, so a screen copied before this landed keeps compiling and reads `undefined` as "no
63
62
  * provider objects" — the state every project was in until now.
@@ -78,4 +77,30 @@ export type AuthClientProjection =
78
77
  otpLength: number;
79
78
  /** Whether signing in may provision a new user. Drives the sign-up copy. */
80
79
  signUpEnabled: boolean;
80
+ /**
81
+ * Native app attestation in this environment, when it has an attestation block. Absent, the send routes
82
+ * take no attestation, and a native app passes the humanity check as a web page does.
83
+ *
84
+ * Optional, so a screen copied before it existed keeps compiling.
85
+ */
86
+ attestation?: {
87
+ /**
88
+ * `test` where the Worker accepts the documented test assertion, so a simulator, an emulator or CI sends
89
+ * it; `enforce` where only a real App Attest or Play Integrity assertion passes.
90
+ */
91
+ mode: "enforce" | "test";
92
+ /**
93
+ * Whether a phone on each platform can pass by attesting here. Under `enforce`, `false` where the block
94
+ * allows no app for that platform or the Worker has no verifier for it, so that platform's phones pass the
95
+ * humanity check.
96
+ *
97
+ * Optional, so a screen copied before it existed keeps compiling; absent reads as both `true`.
98
+ */
99
+ platforms?: {
100
+ /** Whether an iPhone can pass with App Attest, or the test assertion. */
101
+ ios: boolean;
102
+ /** Whether an Android phone can pass with Play Integrity, or the test assertion. */
103
+ android: boolean;
104
+ };
105
+ };
81
106
  };
@@ -0,0 +1,45 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+
7
+ /** The App Attest environment a key was attested in, as its AAGUID names it. */
8
+ export const AppAttestEnvironment = z
9
+ .enum(["production", "development"])
10
+ .describe(
11
+ "The App Attest environment a key was attested in: `production` for TestFlight and App Store builds, `development` for a build carrying the development App Attest entitlement.",
12
+ );
13
+ export type AppAttestEnvironment = z.output<typeof AppAttestEnvironment>;
14
+
15
+ /**
16
+ * `pithy_auth_app_attest_keys`: an App Attest key an iOS app registered with an attestation Apple signed.
17
+ *
18
+ * One row per key, written once by the key route and then only its counter and last use, by each assertion that
19
+ * verifies (`../attestation/appAttest/keys.ts`). A key belongs to one install of the app, not to a person: it is
20
+ * registered before anybody signs in, and names no user.
21
+ */
22
+ export const AppAttestKey = z
23
+ .object({
24
+ id: z
25
+ .string()
26
+ .describe("Primary key: the App Attest key id, unpadded base64url of its 32 bytes, SHA-256 of `publicKey`."),
27
+ publicKey: z
28
+ .string()
29
+ .describe(
30
+ "The key's P-256 public key, an X9.62 uncompressed point, unpadded base64url. Assertions verify with it.",
31
+ ),
32
+ appId: z.string().describe("The App ID the key was attested for: `<TeamID>.<bundleId>`."),
33
+ environment: AppAttestEnvironment,
34
+ counter: z
35
+ .number()
36
+ .int()
37
+ .nonnegative()
38
+ .describe("The counter of the last assertion accepted, 0 at registration. Each assertion must exceed it."),
39
+ createdAt: SQLiteDate.describe("When the key was registered. Ms-epoch in SQLite."),
40
+ lastUsedAt: SQLiteDate.nullable().describe(
41
+ "When an assertion by this key last verified, or null before the first. Ms-epoch in SQLite.",
42
+ ),
43
+ })
44
+ .describe("A registered App Attest key in `pithy_auth_app_attest_keys`.");
45
+ export type AppAttestKey = z.output<typeof AppAttestKey>;
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * `pithy_auth_attestation_challenges`: a challenge the challenge route issued and nobody has presented yet.
9
+ *
10
+ * Keyed by the challenge's SHA-256, so a read of the table hands nobody a usable challenge. A row is deleted
11
+ * when its challenge is presented, pass or fail, which is what makes a challenge single-use, and issuing deletes
12
+ * the rows that ran out unpresented (`../attestation/challenge.ts`). It names no person and no device.
13
+ */
14
+ export const AttestationChallenge = z
15
+ .object({
16
+ id: z
17
+ .string()
18
+ .describe("Primary key: the unpadded base64url SHA-256 of the challenge. The challenge itself is never stored."),
19
+ issuedAt: SQLiteDate.describe("When the challenge was issued. Ms-epoch in SQLite."),
20
+ expiresAt: SQLiteDate.describe("When the challenge stops being accepted. Ms-epoch in SQLite. Indexed."),
21
+ })
22
+ .describe("An issued, unpresented attestation challenge in `pithy_auth_attestation_challenges`.");
23
+ export type AttestationChallenge = z.output<typeof AttestationChallenge>;
@@ -4,6 +4,8 @@
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
5
  import { createDatabase, type DatabaseSchema } from "@pithy-sh/core/src/data/db";
6
6
  import type { Kysely } from "kysely";
7
+ import { AppAttestKey } from "./appAttestKey";
8
+ import { AttestationChallenge } from "./attestationChallenge";
7
9
  import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth";
8
10
  import { Device } from "./device";
9
11
  import { RotatedToken } from "./rotatedToken";
@@ -16,7 +18,7 @@ import { VerificationOutcome } from "./verificationOutcome";
16
18
  * (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
17
19
  *
18
20
  * The first six tables are Better-Auth-managed; `pithyAuthDevices`, `pithyAuthRotatedTokens`,
19
- * `pithyAuthUserLifecycle` and `pithyAuthVerificationOutcomes` are ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
21
+ * `pithyAuthUserLifecycle`, `pithyAuthVerificationOutcomes`, `pithyAuthAttestationChallenges` and `pithyAuthAppAttestKeys` are ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
20
22
  * own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
21
23
  */
22
24
  export const authTables = {
@@ -30,6 +32,8 @@ export const authTables = {
30
32
  pithyAuthRotatedTokens: RotatedToken,
31
33
  pithyAuthUserLifecycle: UserLifecycleEvent,
32
34
  pithyAuthVerificationOutcomes: VerificationOutcome,
35
+ pithyAuthAttestationChallenges: AttestationChallenge,
36
+ pithyAuthAppAttestKeys: AppAttestKey,
33
37
  };
34
38
  export type AuthTables = typeof authTables;
35
39
 
@@ -33,7 +33,7 @@ export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
33
33
  export const UserLifecycleActorType = z
34
34
  .enum(["control-plane", "user", "system"])
35
35
  .describe(
36
- "Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder, deleting their own account), or `system` (the scheduled purge, with nobody calling).",
36
+ "Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (a signed-in person: the account's own holder deleting it, or an organization's owner whose deletion of that organization reached it through the sole-member cascade), or `system` (the scheduled purge, with nobody calling).",
37
37
  );
38
38
  export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
39
39
 
@@ -55,7 +55,7 @@ export const UserLifecycleEvent = z
55
55
  .string()
56
56
  .nullable()
57
57
  .describe(
58
- "The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none.",
58
+ "The acting principal's id — the user's own id for a self-service deletion, the deleting owner's for an organization's cascade, the connection's for a management client. Null for `system`, and for a management client that named none.",
59
59
  ),
60
60
  reason: z
61
61
  .string()
@@ -87,6 +87,13 @@ export const UserLifecycleEvent = z
87
87
  .describe(
88
88
  "For a `deleted` row, when its purge comes due — kept here because the purge erases the account's own column. Null for every other row, and before `0007_erasure_record` (#823). Ms-epoch in SQLite.",
89
89
  ),
90
+ basisKey: z
91
+ .string()
92
+ .nullable()
93
+ .default(null)
94
+ .describe(
95
+ "For a `purge_retained` row, the catalog key its basis in `reason` translates through, under the retaining capability's own domain — `payments/purge.retained`. Null for every other row, for a retained step that names no key, and before `0011_retained_basis_key`.",
96
+ ),
90
97
  createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
91
98
  })
92
99
  .describe(
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * What a hook is handed beside its event and the D1 binding: the Worker it runs in.
6
+ *
7
+ * `env` is the Worker's environment, typed as the adopter's own through `auth<Env>()` or
8
+ * `organization.withEnv<Env>()(...)`, so a hook can read a secret, start a Workflow or send to a queue. `waitUntil` is the request's
9
+ * `ExecutionContext.waitUntil`, already bound, present when the hook fires inside a request and absent when it fires
10
+ * from a purge Workflow, which has no `ExecutionContext` — a Workflow step already runs to completion.
11
+ */
12
+ export interface HookRuntime<Env = Record<string, unknown>> {
13
+ /** The Worker's environment: every binding and secret. */
14
+ readonly env: Env;
15
+ /** Keep work running after the response, inside a request. Absent in a Workflow. */
16
+ readonly waitUntil?: (promise: Promise<unknown>) => void;
17
+ }
18
+
19
+ /** What {@link requestRuntime} reads off a Hono context. */
20
+ interface RuntimeSource {
21
+ readonly env: unknown;
22
+ readonly executionCtx?: { waitUntil(promise: Promise<unknown>): void } | undefined;
23
+ }
24
+
25
+ /**
26
+ * The runtime for a hook fired inside a request: the request's env, and its `waitUntil` bound to the context.
27
+ *
28
+ * Hono's `executionCtx` getter throws when the request carries none, as under `app.request()` with no context, so
29
+ * that case reads as absent rather than failing the hook's caller.
30
+ */
31
+ export function requestRuntime<Env = Record<string, unknown>>(c: RuntimeSource): HookRuntime<Env> {
32
+ const env = c.env as Env;
33
+ let ctx: RuntimeSource["executionCtx"];
34
+ try {
35
+ ctx = c.executionCtx;
36
+ } catch {
37
+ ctx = undefined;
38
+ }
39
+ if (!ctx) return { env };
40
+ return { env, waitUntil: ctx.waitUntil.bind(ctx) };
41
+ }
@@ -9,6 +9,7 @@ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
9
9
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
10
10
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
11
11
  import { validate } from "@pithy-sh/core/src/http/validation";
12
+ import { composedTranslator } from "@pithy-sh/core/src/i18n/composed";
12
13
  import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
13
14
  import type { Context, Hono } from "hono";
14
15
  import type { z } from "zod";
@@ -859,13 +860,19 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
859
860
  { action: AuthAuditActions.adminUserExported, ...call.audit },
860
861
  async () => {
861
862
  const database = db(c, wiring);
862
- await requirePresent(database, userId);
863
- return purgeExports(wiring.purgeSteps ?? [], {
864
- subject: { type: "user", id: userId },
865
- env: c.env as Record<string, unknown>,
866
- // A capability holding rows by address — a suppression, a tester's membership — reads it here.
867
- address: () => purgeAddress(database, userId),
868
- });
863
+ const { locale } = await requirePresent(database, userId);
864
+ // A retained basis is told to the person, so it is read in their stored locale, never the caller's.
865
+ const t = composedTranslator(wiring.composed ?? [], locale);
866
+ return purgeExports(
867
+ wiring.purgeSteps ?? [],
868
+ {
869
+ subject: { type: "user", id: userId },
870
+ env: c.env as Record<string, unknown>,
871
+ // A capability holding rows by address — a suppression, a tester's membership — reads it here.
872
+ address: () => purgeAddress(database, userId),
873
+ },
874
+ t ? (key) => t.maybe(key) : undefined,
875
+ );
869
876
  },
870
877
  () => false,
871
878
  );
@@ -12,6 +12,7 @@ import type { Context } from "hono";
12
12
  import type { AuthWiring } from "../capability";
13
13
  import { authDatabase } from "../data/tables";
14
14
  import { makeSendAuthEmail, type ResolveRecipientLocale } from "../email/send";
15
+ import { requestRuntime } from "../hooks/runtime";
15
16
  import { type AuthInstance, makeAuth } from "../instance/auth";
16
17
  import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption";
17
18
  import { resolveProvider } from "../instance/providers";
@@ -133,10 +134,13 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
133
134
  const baseURL = baseURLResolver(cfg.baseURL)(c.req.raw);
134
135
  return makeAuth({
135
136
  db: authDatabase(d1),
136
- // The adopter's listener, bound to *this* request's binding. The instance is built per request, so
137
- // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
138
- // has none.
139
- ...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
137
+ // The adopter's listener, bound to *this* request's binding and runtime. The instance is built per request, so
138
+ // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and has none.
139
+ ...(listener
140
+ ? {
141
+ onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1, requestRuntime(c)),
142
+ }
143
+ : {}),
140
144
  secret,
141
145
  sessionSecrets,
142
146
  // Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
@@ -475,7 +475,13 @@ const exportEntry = {
475
475
  .string()
476
476
  .optional()
477
477
  .describe(
478
- "For a `retain` entry, why the rows are kept, in one sentence written for the person — `Kept for tax records.` Absent for `erase`.",
478
+ "For a `retain` entry, why the rows are kept, in one sentence written for the person and in their stored locale where a catalog translates it — `Kept for tax records.` Absent for `erase`.",
479
+ ),
480
+ basisKey: z
481
+ .string()
482
+ .optional()
483
+ .describe(
484
+ "For a `retain` entry, the catalog key `basis` was translated from, under the capability's own domain — `payments/purge.retained`. Absent when the capability names none, for `erase`, and from a Worker that predates it.",
479
485
  ),
480
486
  };
481
487
 
@@ -574,6 +580,28 @@ export const HandoffExchangeResponse = z
574
580
  .describe("The session a redirect sign-in made, handed to the native app that started it.");
575
581
  export type HandoffExchangeResponse = z.output<typeof HandoffExchangeResponse>;
576
582
 
583
+ /** `POST {base}/attestation/challenge`. */
584
+ export const AttestationChallengeResponse = z
585
+ .object({
586
+ challenge: z
587
+ .string()
588
+ .describe(
589
+ "The challenge: 32 random bytes, unpadded base64url. Good once, on one send route, until `expiresAt`. The platform's assertion is made over SHA-256 of these characters followed by that request's exact body.",
590
+ ),
591
+ expiresAt: z.iso.datetime().describe("When the challenge stops being accepted, ISO-8601."),
592
+ })
593
+ .describe("A single-use challenge for a native app attestation.");
594
+ export type AttestationChallengeResponse = z.output<typeof AttestationChallengeResponse>;
595
+
596
+ /** `POST {base}/attestation/ios/keys`. */
597
+ export const AppAttestKeyResponse = z
598
+ .object({
599
+ keyId: z.string().describe("The key identifier, as the request sent it. Assertions name it as `keyId`."),
600
+ registeredAt: z.iso.datetime().describe("When the key was registered, ISO-8601."),
601
+ })
602
+ .describe("An App Attest key this server verified and registered.");
603
+ export type AppAttestKeyResponse = z.output<typeof AppAttestKeyResponse>;
604
+
577
605
  /** One of the caller's own registered devices. */
578
606
  export const MyDeviceView = z
579
607
  .object({
@@ -8,10 +8,18 @@ import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
8
8
  import { validate } from "@pithy-sh/core/src/http/validation";
9
9
  import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
10
10
  import { announceSessionRotated } from "@pithy-sh/core/src/session/rotated";
11
+ import { workerIdentity } from "@pithy-sh/core/src/worker/identity";
11
12
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
12
13
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
13
14
  import type { Context, Hono } from "hono";
14
15
  import { userSessionTokens } from "../admin/users";
16
+ import { APPLE_APP_ATTESTATION_ROOT } from "../attestation/appAttest/root";
17
+ import { registerAppAttestKey } from "../attestation/appAttest/verifier";
18
+ import { issueChallenge } from "../attestation/challenge";
19
+ import { attestationIsConfigured } from "../attestation/config";
20
+ import { AttestationFailedError } from "../attestation/errors";
21
+ import { assertAttestationBlock, sendGate } from "../attestation/gate";
22
+ import { PLATFORM_VERIFIERS } from "../attestation/verifier";
15
23
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit";
16
24
  import type { AuthWiring } from "../capability";
17
25
  import { authDatabase } from "../data/tables";
@@ -39,12 +47,20 @@ import { collapseProviderRefusal } from "./providerRefusal";
39
47
  import { getAuthInstance, resolveDb } from "./resolve";
40
48
  import {
41
49
  AccountDeleteResponse,
50
+ AppAttestKeyResponse,
51
+ AttestationChallengeResponse,
42
52
  HandoffExchangeResponse,
43
53
  MyDeviceRevokeResponse,
44
54
  MyDevicesResponse,
45
55
  TokenRotateResponse,
46
56
  } from "./responses";
47
- import { DeleteAccountBody, HandoffExchangeBody, RevokeDeviceBody, SocialSignInStartQuery } from "./schemas";
57
+ import {
58
+ AppAttestKeyBody,
59
+ DeleteAccountBody,
60
+ HandoffExchangeBody,
61
+ RevokeDeviceBody,
62
+ SocialSignInStartQuery,
63
+ } from "./schemas";
48
64
  import { accountDeletionView } from "./views";
49
65
 
50
66
  type Ctx = Context<PithyHonoEnv>;
@@ -59,6 +75,9 @@ const BETTER_AUTH_ANSWER: RouteResponse = {
59
75
  contentType: "application/json",
60
76
  };
61
77
 
78
+ /** The routes that send a sign-in email, under `basePath`: the ones Turnstile and attestation gate. */
79
+ export const SEND_ROUTES = ["/sign-in/magic-link", "/email-otp/send-verification-otp"] as const;
80
+
62
81
  function db(c: Ctx, wiring: AuthWiring) {
63
82
  return authDatabase(resolveDb(c.env, wiring.config.database));
64
83
  }
@@ -66,7 +85,7 @@ function db(c: Ctx, wiring: AuthWiring) {
66
85
  /**
67
86
  * Register the auth routes onto the backend's Hono app.
68
87
  *
69
- * Order matters: turnstile gates the human-initiated send routes (only when composed), Pithy's own
88
+ * Order matters: Turnstile and attestation gate the send routes ({@link SEND_ROUTES}), Pithy's own
70
89
  * routes are registered before the catch-all so they win, and Better Auth owns everything else under
71
90
  * `basePath`. A handler that returns a Response ends the chain, so the specific routes never fall
72
91
  * through to the catch-all. (The tier-1 edge rate limiter is contributed as capability *middleware*, so
@@ -77,6 +96,8 @@ function db(c: Ctx, wiring: AuthWiring) {
77
96
  * | Route | Verification | Input |
78
97
  * | -------------------------- | --------------- | --------------------------- |
79
98
  * | `POST /token/rotate` | bearer/session | none — the credential only |
99
+ * | `POST /attestation/challenge` | public | none |
100
+ * | `POST /attestation/ios/keys` | public | json `AppAttestKeyBody` |
80
101
  * | `GET /sign-in/social/start` | public | query `SocialSignInStartQuery` |
81
102
  * | `POST /handoff` | public | json `HandoffExchangeBody` |
82
103
  * | `GET /devices` | bearer/session | none |
@@ -103,15 +124,54 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
103
124
  // resolved, and reads it back here rather than binding a second copy of the same decision.
104
125
  const csrf = requireSameOrigin();
105
126
 
106
- // Auto-gate the magic-link and OTP send routes with the humanity check, when turnstile is composed.
107
- // The action is `@pithy-sh/turnstile`'s constant, never a literal: the widget is solved for the same
108
- // string through the client projection, and a second copy of it could only be caught in production —
109
- // where the two disagreeing refuses every sign-in. #377, and `TURNSTILE_LOGIN_ACTION`'s docblock.
110
- if (wiring.turnstile) {
111
- const { mode, token } = wiring.turnstile;
112
- const guard = turnstile({ mode, field: token.field, header: token.header, action: TURNSTILE_LOGIN_ACTION });
113
- app.use(`${base}/sign-in/magic-link`, guard);
114
- app.use(`${base}/email-otp/send-verification-otp`, guard);
127
+ // The magic-link and OTP send routes are gated by Turnstile when it is composed, and by native app
128
+ // attestation once any environment has a block (`../attestation/gate.ts` holds the rule between the two).
129
+ // The Turnstile action is `@pithy-sh/turnstile`'s constant, never a literal: the widget is solved for the
130
+ // same string through the client projection, and two copies disagreeing refuses every sign-in.
131
+ const humanity = wiring.turnstile
132
+ ? turnstile({
133
+ mode: wiring.turnstile.mode,
134
+ field: wiring.turnstile.token.field,
135
+ header: wiring.turnstile.token.header,
136
+ action: TURNSTILE_LOGIN_ACTION,
137
+ })
138
+ : undefined;
139
+ const { attestation } = wiring.config;
140
+ const guard = attestationIsConfigured(attestation)
141
+ ? sendGate({
142
+ attestation,
143
+ database: wiring.config.database,
144
+ verifiers: wiring.attestationVerifiers ?? PLATFORM_VERIFIERS,
145
+ turnstile: humanity,
146
+ })
147
+ : humanity;
148
+ if (guard) {
149
+ for (const path of SEND_ROUTES) app.use(`${base}${path}`, guard);
150
+ }
151
+ if (attestationIsConfigured(attestation)) {
152
+ app.post(
153
+ `${base}/attestation/challenge`,
154
+ describeRoute({
155
+ summary: "Issue a single-use challenge for a native app attestation.",
156
+ description:
157
+ "A native app asks for one before each send. It attests over SHA-256 of the challenge followed by the send's exact body, and sends the result in the `x-pithy-attestation` header: unpadded base64url over the JSON `{ platform, challenge, assertion, keyId? }`. The challenge is good once, pass or fail, until `expiresAt`. An environment with no attestation block answers `auth/attestation_config`.",
158
+ verification: ["public"],
159
+ responses: { 200: AttestationChallengeResponse },
160
+ }),
161
+ (c) => issueAttestationChallenge(c, wiring),
162
+ );
163
+ app.post(
164
+ `${base}/attestation/ios/keys`,
165
+ describeRoute({
166
+ summary: "Register an iOS app's App Attest key, with Apple's attestation of it.",
167
+ description:
168
+ "Once per key, before its first assertion. The app asks for a challenge, passes SHA-256 of its characters to `attestKey` as the client data hash, and sends the key id and the attestation object here. The certificate chain must lead to Apple App Attestation Root CA, the `rpIdHash` must be an allowed app's, and the key must be from Apple's production environment, or from either in dev, staging and a feature deployment. Then each send carries an assertion by this key in `x-pithy-attestation`. Any check that fails, a key already registered included, answers `auth/attestation_failed`; an environment with no attestation block answers `auth/attestation_config`.",
169
+ verification: ["public"],
170
+ responses: { 200: AppAttestKeyResponse },
171
+ }),
172
+ validate("json", AppAttestKeyBody),
173
+ (c) => registerIosKey(c, wiring, c.req.valid("json")),
174
+ );
115
175
  }
116
176
 
117
177
  // Rotate the refresh credential: mint a new session, revoke the presented one, return a fresh JWT.
@@ -181,7 +241,7 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
181
241
  (c) => revokeMyDevice(c, wiring, c.req.valid("json")),
182
242
  );
183
243
 
184
- // The signed-in person deletes their own account (#622) — always soft, on the configured window. The one
244
+ // The signed-in person deletes their own account — always soft, on the configured window. The one
185
245
  // route a suspended account still reaches: the app stores require that somebody can always leave, and a
186
246
  // suspension is no reason to keep them. CSRF-guarded as a mutating route; the subject is the session's own,
187
247
  // and nothing in the body can name another.
@@ -300,9 +360,9 @@ function isSignInAttempt(path: string): boolean {
300
360
  * (`better-call@1.4.0`, `dist/router.mjs:83-89`), which renders an `APIError` as a Response and returns
301
361
  * it. The throw is swallowed one frame later by the library that asked for it.
302
362
  *
303
- * So the `emitDenied` call this replaces — gated on catching an `APIError` — had never run once. No
304
- * failed one-time code, no bad magic link, no refused OAuth callback has ever reached
305
- * `pithy_audit_events`, which is the largest class of security event this capability has (#449).
363
+ * A refusal recorded by catching an `APIError` would therefore never be recorded: no failed one-time code,
364
+ * no bad magic link, no refused OAuth callback, which is the largest class of security event this
365
+ * capability has.
306
366
  *
307
367
  * **The body is cloned, never consumed.** The Response is handed back to the caller untouched: Better
308
368
  * Auth's own flat shape is a contract adopters read through `createAuthClient`, and the browser client
@@ -332,12 +392,11 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
332
392
  /**
333
393
  * Delegate to Better Auth's fetch handler, and record what it refused.
334
394
  *
335
- * **The answer is returned exactly as Better Auth wrote it.** Re-homing its flat `{ message, code }`
336
- * into the kit envelope was tried and taken back out: `packages/auth/README.md` documents
337
- * `createAuthClient` from `better-auth/client` as a first-class client surface (#271), and
338
- * `@better-fetch/fetch` builds its error as `{ ...parsedBody, status }` — so rewriting the body would
339
- * make `error.code` `undefined` for every adopter on the documented path. The wire is Better Auth's
340
- * contract. `readFailure` in `../client/api` learns to read it instead (#449).
395
+ * **The answer is returned exactly as Better Auth wrote it, never re-homed in the kit envelope.**
396
+ * `packages/auth/README.md` documents `createAuthClient` from `better-auth/client` as a first-class client
397
+ * surface, and `@better-fetch/fetch` builds its error as `{ ...parsedBody, status }`, so rewriting the body
398
+ * would make `error.code` `undefined` for every adopter on the documented path. The wire is Better Auth's
399
+ * contract, and `readFailure` in `../client/api` reads it.
341
400
  *
342
401
  * The `catch` covers what better-call genuinely hands on: a non-`APIError` throw from an endpoint
343
402
  * (`router.mjs:88`), and a throw from a plugin's `onRequest` hook, which runs outside the router's own
@@ -347,7 +406,7 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
347
406
  async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
348
407
  const instance = await getAuthInstance(c, wiring);
349
408
 
350
- // **A suspended or deleted account does not reach Better Auth as itself (#620).** The session middleware
409
+ // **A suspended or deleted account does not reach Better Auth as itself.** The session middleware
351
410
  // has already refused it an `AuthContext`, but Better Auth resolves its own session on these endpoints and
352
411
  // would happily mint a `/token` for it. So its verdict is applied here too, on every endpoint that acts as
353
412
  // the credential's holder — and not on the ones that end a session or start a new one. `./lifecycleGate`
@@ -356,7 +415,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
356
415
  const refusal = noticedRefusal(c);
357
416
  if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
358
417
 
359
- // **The first of the two guards on the refusal redirect (#625).** `errorCallbackURL` is the caller's
418
+ // **The first of the two guards on the refusal redirect.** `errorCallbackURL` is the caller's
360
419
  // string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
361
420
  // whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
362
421
  // the kit produced, or refuses it — and carries the argument for why guarding the input is not the same
@@ -390,7 +449,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
390
449
  }
391
450
 
392
451
  // **The enumeration oracle on the social callback, closed here because here is the only place both
393
- // halves are in reach (#625).** A refused social sign-in redirects with a code that says whether an
452
+ // halves are in reach.** A refused social sign-in redirects with a code that says whether an
394
453
  // account exists at the address the provider handed over; `./providerRefusal` carries the full
395
454
  // argument and the roster. The collapse has to happen where the capability hands the response back,
396
455
  // rather than in an adopter's middleware, for a reason this line demonstrates: middleware could
@@ -408,9 +467,7 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
408
467
  // a 302 is also what a *successful* OAuth callback answers with, so `auditRefusal` — which knows
409
468
  // only a status and a JSON body — would either read every completed social sign-in as a denial or
410
469
  // have to re-derive this decision from the Location header it is not looking at. The refusal is
411
- // recorded from the one place that has already established it is a refusal and knows which one, so
412
- // these refusals reach `pithy_audit_events` for the first time (#449 closed the same gap for the
413
- // JSON refusals and could not see this one, because it is not a JSON refusal).
470
+ // recorded from the one place that has already established it is a refusal and knows which one.
414
471
  await emitDenied(c.var.emit, { ...correlation(c.req.raw.headers), detail: collapsed.reason });
415
472
  return collapsed.response;
416
473
  }
@@ -442,7 +499,7 @@ const ROTATION_REUSE_GRACE_MS = 30_000;
442
499
  * token + refresh token. This is the "refresh credential rotates on use" primitive Better Auth does not
443
500
  * provide natively.
444
501
  *
445
- * Two hardenings over a naive rotate (#59):
502
+ * Two hardenings over a naive rotate:
446
503
  * - **Reuse detection.** A presented token that no longer resolves to a live session but was previously
447
504
  * consumed is a replayed refresh token — the compromise signal for rotated refresh tokens
448
505
  * (RFC 6819 §5.2.2.3). The whole family is revoked and the attempt denied. (Covers the bearer refresh
@@ -489,7 +546,7 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
489
546
  });
490
547
  }
491
548
 
492
- // An account that may not act gets no successor (#620). `session.create.before` would refuse the mint below
549
+ // An account that may not act gets no successor. `session.create.before` would refuse the mint below
493
550
  // anyway; refusing here, from the middleware's verdict, is what keeps the presented token unspent and the
494
551
  // successor never written, so a reinstated account's device still holds a credential that works.
495
552
  const refusal = noticedRefusal(c);
@@ -509,15 +566,13 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
509
566
  // **And carry the authentication instant, which is the whole point of the column.** A rotation is the
510
567
  // same authentication continuing, not a new one — `createSession` would otherwise stamp `createdAt`
511
568
  // afresh and leave the freshness gate measuring nothing, resettable by anyone holding a stolen refresh
512
- // token (#558).
569
+ // token.
513
570
  //
514
- // **A session predating the column carries `null` forward, and must not fall back to `createdAt`.**
515
- // That looked like a reasonable lower bound and is the opposite: `internal-adapter.mjs:275` stamps
516
- // `createdAt` *after* the caller's override, so a row's `created_at` is the moment of its most recent
517
- // rotation. Substituting it would hand every legacy session an authentication instant minutes old —
518
- // freshest for exactly the actor rotating a stolen token — turning the one control that fails closed
519
- // into one that fails open, on upgrade day, for the whole pre-migration population. `null` travels
520
- // instead, the gate keeps refusing, and one real sign-in fixes it permanently.
571
+ // **A session with no authentication instant carries `null` forward, never `createdAt`.**
572
+ // `internal-adapter.mjs:275` stamps `createdAt` *after* the caller's override, so a row's `created_at` is
573
+ // the moment of its most recent rotation, and substituting it would hand that session an instant minutes
574
+ // old — freshest for exactly the actor rotating a stolen token. `null` keeps the gate refusing until one
575
+ // real sign-in.
521
576
  const authenticatedAt = session.authenticatedAt ?? null;
522
577
 
523
578
  // Mint the successor session and its access token BEFORE consuming the old one, so a transient signing
@@ -586,7 +641,7 @@ async function listMyDevices(c: Ctx, wiring: AuthWiring): Promise<Response> {
586
641
  }
587
642
 
588
643
  /**
589
- * Delete the caller's own account (#622): soft, on the configured window, audited as `auth/user_self_deleted`
644
+ * Delete the caller's own account: soft, on the configured window, audited as `auth/user_self_deleted`
590
645
  * with them as the actor, and every session they hold ended after the columns are written — through Better
591
646
  * Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
592
647
  */
@@ -674,3 +729,38 @@ async function serveMyImage(c: Ctx, wiring: AuthWiring): Promise<Response> {
674
729
  headers: { "content-type": bytes.type, ...STORED_IMAGE_HEADERS },
675
730
  });
676
731
  }
732
+
733
+ /**
734
+ * Verify an App Attest attestation against the environment's iOS apps and, when it holds, store the
735
+ * key so its later assertions verify. A failed attestation answers `auth/attestation_failed`.
736
+ */
737
+ async function registerIosKey(c: Ctx, wiring: AuthWiring, body: AppAttestKeyBody): Promise<Response> {
738
+ const environment = workerIdentity(c.env).environment;
739
+ const settings = assertAttestationBlock(wiring.config.attestation, environment);
740
+ const now = new Date();
741
+ const verdict = await registerAppAttestKey({
742
+ db: db(c, wiring),
743
+ challenge: body.challenge,
744
+ keyId: body.keyId,
745
+ attestation: body.attestation,
746
+ apps: settings.ios,
747
+ environment,
748
+ root: wiring.appAttestRoot ?? APPLE_APP_ATTESTATION_ROOT,
749
+ now,
750
+ });
751
+ if (!verdict.ok) throw new AttestationFailedError({ detail: verdict.reason });
752
+ c.header("cache-control", "no-store");
753
+ return c.json({ keyId: body.keyId, registeredAt: now.toISOString() } satisfies AppAttestKeyResponse);
754
+ }
755
+
756
+ /** Issue an attestation challenge, where this environment has a block to judge its use by. */
757
+ async function issueAttestationChallenge(c: Ctx, wiring: AuthWiring): Promise<Response> {
758
+ const { attestation } = wiring.config;
759
+ assertAttestationBlock(attestation, workerIdentity(c.env).environment);
760
+ const issued = await issueChallenge(db(c, wiring), { now: new Date(), expiresIn: attestation.challengeExpiresIn });
761
+ c.header("cache-control", "no-store");
762
+ return c.json({
763
+ challenge: issued.challenge,
764
+ expiresAt: issued.expiresAt.toISOString(),
765
+ } satisfies AttestationChallengeResponse);
766
+ }