@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
@@ -0,0 +1,149 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
5
+ import { z } from "zod";
6
+ import type { AttestationVerdict } from "../verifier";
7
+
8
+ /** How long after it was requested a token is still accepted, in seconds. */
9
+ export const PLAY_INTEGRITY_MAX_AGE_SECONDS = 300;
10
+
11
+ /** How far ahead of the Worker's clock a token's timestamp may be, in seconds. */
12
+ export const PLAY_INTEGRITY_MAX_SKEW_SECONDS = 60;
13
+
14
+ /** The device label every accepted verdict carries. */
15
+ const DEVICE_INTEGRITY = "MEETS_DEVICE_INTEGRITY";
16
+
17
+ /** The parts of `tokenPayloadExternal` auth judges. Every other field is ignored. */
18
+ export const IntegrityTokenPayload = z
19
+ .object({
20
+ requestDetails: z
21
+ .object({
22
+ requestPackageName: z.string().describe("The package name the app requested the token for."),
23
+ requestHash: z
24
+ .string()
25
+ .optional()
26
+ .describe("A standard request's binding: the base64url of SHA-256 over the challenge and the body."),
27
+ nonce: z.string().optional().describe("A classic request's binding, when the app sent one instead."),
28
+ timestampMillis: z.string().describe("When the token was requested, in milliseconds since the epoch."),
29
+ })
30
+ .describe("What the app asked for, as Google recorded it."),
31
+ appIntegrity: z
32
+ .object({
33
+ appRecognitionVerdict: z
34
+ .string()
35
+ .optional()
36
+ .describe("`PLAY_RECOGNIZED` when the binary is the one Google Play distributes."),
37
+ packageName: z
38
+ .string()
39
+ .optional()
40
+ .describe(
41
+ "The package Google Play attested the binary as. Unlike `requestPackageName`, Google vouches for it.",
42
+ ),
43
+ })
44
+ .optional()
45
+ .describe("Google Play's verdict on the app binary."),
46
+ deviceIntegrity: z
47
+ .object({
48
+ deviceRecognitionVerdict: z
49
+ .array(z.string())
50
+ .optional()
51
+ .describe("The integrity labels the device meets, such as `MEETS_DEVICE_INTEGRITY`."),
52
+ })
53
+ .optional()
54
+ .describe("Google Play's verdict on the device."),
55
+ })
56
+ .describe("A decoded Play Integrity token, as `decodeIntegrityToken` returns it in `tokenPayloadExternal`.");
57
+ export type IntegrityTokenPayload = z.output<typeof IntegrityTokenPayload>;
58
+
59
+ /** What a decoded payload is judged against. */
60
+ export interface IntegrityExpectation {
61
+ /** {@link import("../wire").requestBinding} for this request. */
62
+ binding: Uint8Array;
63
+ /** The package the token was decoded for, one this environment allows. */
64
+ packageName: string;
65
+ now: Date;
66
+ }
67
+
68
+ const stripPadding = (value: string): string => value.replace(/=+$/, "");
69
+
70
+ /** The binding check: `requestHash` on a standard request, `nonce` on a classic one, padding ignored. */
71
+ function judgeBinding(details: IntegrityTokenPayload["requestDetails"], binding: Uint8Array): AttestationVerdict {
72
+ const expected = base64UrlEncode(binding);
73
+ if (details.requestHash !== undefined) {
74
+ return stripPadding(details.requestHash) === expected
75
+ ? { ok: true }
76
+ : { ok: false, reason: "requestHash: the token is bound to another challenge or body" };
77
+ }
78
+ if (details.nonce !== undefined) {
79
+ return stripPadding(details.nonce) === expected
80
+ ? { ok: true }
81
+ : { ok: false, reason: "nonce: the token is bound to another challenge or body" };
82
+ }
83
+ return { ok: false, reason: "requestHash: the token carries neither a requestHash nor a nonce" };
84
+ }
85
+
86
+ /**
87
+ * Judge a decoded Play Integrity payload. `reason` starts with the check that failed: `format`, `requestHash` or
88
+ * `nonce`, `requestPackageName`, `appRecognitionVerdict`, `appIntegrity` (the package Google attested is another
89
+ * app's), `deviceIntegrity` or `timestamp`.
90
+ */
91
+ export function judgeIntegrityVerdict(payload: unknown, expected: IntegrityExpectation): AttestationVerdict {
92
+ const parsed = IntegrityTokenPayload.safeParse(payload);
93
+ if (!parsed.success) {
94
+ return { ok: false, reason: `format: the decoded token has the wrong shape: ${parsed.error.issues[0]?.message}` };
95
+ }
96
+ const { requestDetails, appIntegrity, deviceIntegrity } = parsed.data;
97
+
98
+ const binding = judgeBinding(requestDetails, expected.binding);
99
+ if (!binding.ok) return binding;
100
+
101
+ if (requestDetails.requestPackageName !== expected.packageName) {
102
+ return {
103
+ ok: false,
104
+ reason: `requestPackageName: the token was requested for ${requestDetails.requestPackageName}, not ${expected.packageName}`,
105
+ };
106
+ }
107
+
108
+ const recognition = appIntegrity?.appRecognitionVerdict ?? "absent";
109
+ if (recognition !== "PLAY_RECOGNIZED") {
110
+ return { ok: false, reason: `appRecognitionVerdict: Google Play calls the app ${recognition}` };
111
+ }
112
+
113
+ const attested = appIntegrity?.packageName;
114
+ if (attested !== expected.packageName) {
115
+ return {
116
+ ok: false,
117
+ reason: `appIntegrity: Google Play attested the app as ${attested ?? "no package"}, not ${expected.packageName}`,
118
+ };
119
+ }
120
+
121
+ const labels = deviceIntegrity?.deviceRecognitionVerdict ?? [];
122
+ if (!labels.includes(DEVICE_INTEGRITY)) {
123
+ return {
124
+ ok: false,
125
+ reason: `deviceIntegrity: the device does not meet ${DEVICE_INTEGRITY} (${labels.length === 0 ? "no label" : labels.join(", ")})`,
126
+ };
127
+ }
128
+
129
+ const requestedAt = /^\d+$/.test(requestDetails.timestampMillis)
130
+ ? Number(requestDetails.timestampMillis)
131
+ : Number.NaN;
132
+ if (!Number.isSafeInteger(requestedAt)) {
133
+ return { ok: false, reason: "timestamp: timestampMillis is not a number" };
134
+ }
135
+ const age = expected.now.getTime() - requestedAt;
136
+ if (age > PLAY_INTEGRITY_MAX_AGE_SECONDS * 1000) {
137
+ return {
138
+ ok: false,
139
+ reason: `timestamp: the token was requested ${Math.round(age / 1000)}s ago, over the ${PLAY_INTEGRITY_MAX_AGE_SECONDS}s window`,
140
+ };
141
+ }
142
+ if (-age > PLAY_INTEGRITY_MAX_SKEW_SECONDS * 1000) {
143
+ return {
144
+ ok: false,
145
+ reason: `timestamp: the token is stamped ${Math.round(-age / 1000)}s ahead of the Worker's clock`,
146
+ };
147
+ }
148
+ return { ok: true };
149
+ }
@@ -0,0 +1,77 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
5
+ import {
6
+ AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT,
7
+ type PlayIntegrityServiceAccount,
8
+ resolvePlayIntegrityServiceAccount,
9
+ } from "../../instance/secrets";
10
+ import { AttestationConfigError } from "../errors";
11
+ import type { AttestationVerifier } from "../verifier";
12
+ import { createGoogleAccessTokens, decodeIntegrityToken, SERVICE_ACCOUNT_ACTION } from "./google";
13
+ import { judgeIntegrityVerdict } from "./verdict";
14
+
15
+ /** What a Play Integrity verifier is built from. Both default to the Worker's own. */
16
+ export interface PlayIntegrityVerifierOptions {
17
+ /** How Google is called. */
18
+ fetch?: typeof fetch;
19
+ /** Where the service account is read from: auth's secret registry, by default. */
20
+ serviceAccount?: (env: Readonly<Record<string, unknown>>) => Promise<PlayIntegrityServiceAccount>;
21
+ }
22
+
23
+ async function readServiceAccount(
24
+ read: NonNullable<PlayIntegrityVerifierOptions["serviceAccount"]>,
25
+ env: Readonly<Record<string, unknown>>,
26
+ ): Promise<PlayIntegrityServiceAccount> {
27
+ try {
28
+ return await read(env);
29
+ } catch (error) {
30
+ throw new AttestationConfigError({
31
+ detail: `the ${AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT} secret could not be read: ${error instanceof Error ? error.message : String(error)}`,
32
+ action: SERVICE_ACCOUNT_ACTION,
33
+ });
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Google Play Integrity. Decodes the token through Google's `decodeIntegrityToken` with the environment's service
39
+ * account, for each allowed package until one decodes, then judges the verdict against the request binding.
40
+ *
41
+ * The access token is held per service account for its lifetime, across requests this isolate serves. A Google
42
+ * credential or setup fault is `auth/attestation_config`, and the token is dropped so the next request mints anew.
43
+ */
44
+ export function createPlayIntegrityVerifier(options: PlayIntegrityVerifierOptions = {}): AttestationVerifier {
45
+ const fetchImpl: typeof fetch = options.fetch ?? ((input, init) => fetch(input, init));
46
+ const read =
47
+ options.serviceAccount ?? ((env) => resolvePlayIntegrityServiceAccount(env as unknown as SecretsStoreEnv));
48
+ const tokens = createGoogleAccessTokens(fetchImpl);
49
+ return {
50
+ async verify({ presented, binding, settings, env, now }) {
51
+ if (settings.android.length === 0) {
52
+ return { ok: false, reason: "requestPackageName: no Android app is allowed to attest here" };
53
+ }
54
+ const account = await readServiceAccount(read, env);
55
+ const refusals: string[] = [];
56
+ try {
57
+ const accessToken = await tokens.get(account, now);
58
+ for (const { packageName } of settings.android) {
59
+ const decoded = await decodeIntegrityToken(fetchImpl, {
60
+ accessToken,
61
+ packageName,
62
+ token: presented.assertion,
63
+ });
64
+ if (decoded.ok) return judgeIntegrityVerdict(decoded.payload, { binding, packageName, now });
65
+ refusals.push(decoded.reason);
66
+ }
67
+ } catch (error) {
68
+ if (error instanceof AttestationConfigError) tokens.drop(account);
69
+ throw error;
70
+ }
71
+ return { ok: false, reason: `decode: ${refusals.join("; ")}` };
72
+ },
73
+ };
74
+ }
75
+
76
+ /** The Play Integrity verifier a Worker runs, calling Google with its own `fetch`. */
77
+ export const playIntegrityVerifier: AttestationVerifier = createPlayIntegrityVerifier();
@@ -0,0 +1,87 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import type { AuthDatabase } from "../data/tables";
5
+ import { appAttestVerifier } from "./appAttest/verifier";
6
+ import { type AttestationEnvironment, type AttestationPlatform, testAssertionAllowedIn } from "./config";
7
+ import { playIntegrityVerifier } from "./playIntegrity/verifier";
8
+ import type { PresentedAttestation } from "./wire";
9
+
10
+ /**
11
+ * The documented test assertion. In dev, staging or a feature deployment set to `test`, the gate accepts it from
12
+ * either platform in place of a real one, so simulators, emulators and CI get through.
13
+ */
14
+ export const ATTESTATION_TEST_ASSERTION = "pithy-test-attestation";
15
+
16
+ /** Everything a verifier is handed for one attestation. The challenge is already spent and was live. */
17
+ export interface AttestationVerification {
18
+ /** The decoded header. */
19
+ presented: PresentedAttestation;
20
+ /** {@link import("./wire").requestBinding} for this request: what the assertion must be made over. */
21
+ binding: Uint8Array;
22
+ /** The environment the Worker is stamped with, or `null` for an unstamped Worker. */
23
+ environment: string | null;
24
+ /** This environment's attestation block: the apps allowed to attest, and the mode. */
25
+ settings: AttestationEnvironment;
26
+ /** Auth's database, for a verifier that keeps state of its own, such as App Attest's registered keys. */
27
+ db: AuthDatabase;
28
+ /**
29
+ * The Worker's bindings, for a verifier that needs a credential: it reads its secret from auth's registry with
30
+ * `sharedSecretsStore(env, authSecretsRegistry)`, as Turnstile reads its own, and answers a missing or unusable
31
+ * one with `auth/attestation_config`.
32
+ */
33
+ env: Readonly<Record<string, unknown>>;
34
+ /** The instant the request is judged at. */
35
+ now: Date;
36
+ }
37
+
38
+ /** A verifier's answer. `reason` says why, for the refusal's `detail`; it never reaches the client. */
39
+ export type AttestationVerdict = { ok: true } | { ok: false; reason: string };
40
+
41
+ /**
42
+ * One platform's verification. A verdict about the attestation is answered; a fault in the server's own setup is
43
+ * thrown as `auth/attestation_config`. Runs on WebCrypto alone.
44
+ */
45
+ export interface AttestationVerifier {
46
+ verify(verification: AttestationVerification): Promise<AttestationVerdict>;
47
+ }
48
+
49
+ /** The verifier for each platform. A platform with none answers `auth/attestation_config` for a real assertion. */
50
+ export type AttestationVerifiers = Partial<Record<AttestationPlatform, AttestationVerifier>>;
51
+
52
+ /** The verifiers this release ships for real assertions. */
53
+ export const PLATFORM_VERIFIERS: AttestationVerifiers = { ios: appAttestVerifier, android: playIntegrityVerifier };
54
+
55
+ /** Whether this attestation is the documented test assertion. */
56
+ export function isTestAssertion(presented: PresentedAttestation): boolean {
57
+ return presented.assertion === ATTESTATION_TEST_ASSERTION;
58
+ }
59
+
60
+ /**
61
+ * Accepts {@link ATTESTATION_TEST_ASSERTION} from either platform, only where the environment is set to `test` and
62
+ * the Worker's own stamp is one of {@link import("./config").TEST_ASSERTION_ENVIRONMENTS}, so no config can open
63
+ * it anywhere else.
64
+ */
65
+ export const testVerifier: AttestationVerifier = {
66
+ async verify({ presented, environment, settings }) {
67
+ if (!isTestAssertion(presented)) return { ok: false, reason: "not the test assertion" };
68
+ if (!testAssertionAllowedIn(environment)) {
69
+ return {
70
+ ok: false,
71
+ reason: `the test assertion is refused where ENVIRONMENT is ${environment ?? "unstamped"}, whatever the config says: only dev, staging or feature accept it`,
72
+ };
73
+ }
74
+ if (settings.mode !== "test") {
75
+ return { ok: false, reason: `the test assertion is refused in ${environment}, which is set to enforce` };
76
+ }
77
+ return { ok: true };
78
+ },
79
+ };
80
+
81
+ /** The verifier an attestation goes to: the test verifier for the test assertion, otherwise its platform's. */
82
+ export function verifierFor(
83
+ presented: PresentedAttestation,
84
+ verifiers: AttestationVerifiers,
85
+ ): AttestationVerifier | undefined {
86
+ return isTestAssertion(presented) ? testVerifier : verifiers[presented.platform];
87
+ }
@@ -0,0 +1,79 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { base64UrlDecode, base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
5
+ import { z } from "zod";
6
+ import { AttestationPlatform } from "./config";
7
+
8
+ /**
9
+ * The one header a native app's attestation travels in, on a send route.
10
+ *
11
+ * A header rather than body fields: the send routes' bodies are Better Auth's, forwarded untouched, and the
12
+ * attestation signs over those exact bytes ({@link requestBinding}), so it cannot sit inside them.
13
+ */
14
+ export const ATTESTATION_HEADER = "x-pithy-attestation";
15
+
16
+ /** The longest header value read. A Play Integrity token or an App Attest assertion fits well inside. */
17
+ export const MAX_ATTESTATION_HEADER = 16_384;
18
+
19
+ /** What a client sends in {@link ATTESTATION_HEADER}, before its base64url encoding. */
20
+ export const PresentedAttestation = z
21
+ .object({
22
+ platform: AttestationPlatform,
23
+ challenge: z
24
+ .string()
25
+ .min(1)
26
+ .max(128)
27
+ .describe("The challenge the challenge route issued. Single use: presenting it spends it, pass or fail."),
28
+ assertion: z
29
+ .string()
30
+ .min(1)
31
+ .describe(
32
+ "What the platform produced over the request binding: an App Attest assertion from a key already registered at `POST /auth/attestation/ios/keys` on iOS, a Play Integrity token on Android, base64 as the platform hands it over. Never the App Attest attestation object, which goes only to that registration route. Or the documented test assertion, in a `test` environment.",
33
+ ),
34
+ keyId: z.string().min(1).max(256).optional().describe("The App Attest key identifier on iOS. Android has none."),
35
+ })
36
+ .describe(
37
+ "A native app attestation as a send route reads it: the platform, the challenge it answers, and the platform's assertion over the request.",
38
+ );
39
+ export type PresentedAttestation = z.output<typeof PresentedAttestation>;
40
+
41
+ /** A decoded header, or why it could not be read. */
42
+ export type DecodedAttestation = { ok: true; value: PresentedAttestation } | { ok: false; reason: string };
43
+
44
+ /** Encode an attestation for {@link ATTESTATION_HEADER}: unpadded base64url over its JSON. */
45
+ export function encodeAttestation(presented: PresentedAttestation): string {
46
+ return base64UrlEncode(new TextEncoder().encode(JSON.stringify(presented)));
47
+ }
48
+
49
+ /** Read {@link ATTESTATION_HEADER}'s value. Never throws: a header that does not read is the caller's refusal. */
50
+ export function decodeAttestation(header: string): DecodedAttestation {
51
+ if (header.length === 0) return { ok: false, reason: "the attestation header is empty" };
52
+ if (header.length > MAX_ATTESTATION_HEADER) {
53
+ return { ok: false, reason: `the attestation header is over ${MAX_ATTESTATION_HEADER} characters` };
54
+ }
55
+ let json: unknown;
56
+ try {
57
+ json = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(base64UrlDecode(header)));
58
+ } catch {
59
+ return { ok: false, reason: "the attestation header is not base64url-encoded JSON" };
60
+ }
61
+ const parsed = PresentedAttestation.safeParse(json);
62
+ if (!parsed.success) {
63
+ return { ok: false, reason: `the attestation header has the wrong shape: ${parsed.error.issues[0]?.message}` };
64
+ }
65
+ return { ok: true, value: parsed.data };
66
+ }
67
+
68
+ /**
69
+ * The bytes a platform's assertion must be made over: SHA-256 of the challenge's UTF-8 and then the request body,
70
+ * byte for byte. App Attest takes it as `clientDataHash`; Play Integrity takes its base64url as `requestHash`. It
71
+ * binds one attestation to one challenge and one body, so it cannot be lifted onto another address.
72
+ */
73
+ export async function requestBinding(challenge: string, body: Uint8Array): Promise<Uint8Array> {
74
+ const prefix = new TextEncoder().encode(challenge);
75
+ const message = new Uint8Array(prefix.length + body.length);
76
+ message.set(prefix, 0);
77
+ message.set(body, prefix.length);
78
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", message));
79
+ }
package/src/capability.ts CHANGED
@@ -18,9 +18,12 @@ import {
18
18
  } from "@pithy-sh/turnstile/src/config/config";
19
19
  import type { Context } from "hono";
20
20
  import { z } from "zod";
21
+ import { AttestationConfig, attestationFor, testAssertionAllowedIn } from "./attestation/config";
22
+ import { type AttestationVerifiers, PLATFORM_VERIFIERS } from "./attestation/verifier";
21
23
  import { AuthAuditActions } from "./audit/actions";
22
24
  import type { AuthClientProjection } from "./client/projection";
23
25
  import { authTables } from "./data/tables";
26
+ import type { HookRuntime } from "./hooks/runtime";
24
27
  import { baseURLResolver } from "./http/baseUrl";
25
28
  import { publishSameOrigin } from "./http/csrf";
26
29
  import { registerDevLoginRoute } from "./http/devLoginRoute";
@@ -31,7 +34,11 @@ import { getAuthInstance } from "./http/resolve";
31
34
  import { createAuthRoutes } from "./http/routes";
32
35
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
33
36
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
34
- import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
37
+ import {
38
+ authSecretsRegistryFor,
39
+ inapplicablePlayIntegritySecret,
40
+ inapplicableProviderSecrets,
41
+ } from "./instance/secrets";
35
42
  import { authErasureRecords } from "./lifecycle/erasure";
36
43
  import type { UserLifecycleHooks } from "./lifecycle/hooks";
37
44
  import type { McpHost, McpWiring } from "./mcp/host";
@@ -188,6 +195,9 @@ export const AuthConfig = z
188
195
  .describe(
189
196
  "Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false.",
190
197
  ),
198
+ attestation: AttestationConfig.prefault({}).describe(
199
+ "Native app attestation on the email send routes, per environment. An environment with a block takes an attestation in the `x-pithy-attestation` header in place of a Turnstile token, and requires one when turnstile is not composed. Apple App Attest and Google Play Integrity are verified, and the test assertion in a test environment. See the README's attestation section.",
200
+ ),
191
201
  plugins: z
192
202
  .array(AuthPlugin)
193
203
  .default([])
@@ -225,6 +235,16 @@ export interface AuthWiring {
225
235
  enqueueEmail: EmailCapability["enqueue"] | undefined;
226
236
  /** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
227
237
  turnstile: TurnstileLoginGate | undefined;
238
+ /**
239
+ * The verifier for each platform's real attestations. Absent means the ones this release ships,
240
+ * `PLATFORM_VERIFIERS`; a harness passes its own.
241
+ */
242
+ attestationVerifiers?: AttestationVerifiers | undefined;
243
+ /**
244
+ * The root CA an App Attest key's certificate chain must lead to, DER. Absent means Apple App Attestation Root
245
+ * CA, pinned in the package; a harness passes the root of its own test chain.
246
+ */
247
+ appAttestRoot?: Uint8Array | undefined;
228
248
  /**
229
249
  * The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
230
250
  *
@@ -289,9 +309,15 @@ export type ScopeResolver = (
289
309
  * **Handed this request's D1 binding**, because the auth instance is built per request and the listener
290
310
  * almost certainly wants to write to the same database under a different capability's view of it. Taking
291
311
  * the binding rather than a typed database keeps this seam out of the business of knowing whose tables
292
- * the listener is about to touch.
312
+ * the listener is about to touch. **And handed the request's runtime**: its env, typed as `auth<Env>()` names
313
+ * it, and its `waitUntil`, so the listener can reach another binding or keep work running past the response.
314
+ * A listener that takes only `(session, d1)` is still one.
293
315
  */
294
- export type SessionRevokedListener = (session: { id: string; userId: string }, d1: D1Database) => Promise<void>;
316
+ export type SessionRevokedListener<Env = Record<string, unknown>> = (
317
+ session: { id: string; userId: string },
318
+ d1: D1Database,
319
+ runtime: HookRuntime<Env>,
320
+ ) => Promise<void>;
295
321
 
296
322
  /**
297
323
  * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
@@ -301,8 +327,8 @@ export type SessionRevokedListener = (session: { id: string; userId: string }, d
301
327
  * `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
302
328
  * destructured off before the parse.
303
329
  */
304
- export type AuthOptions = AuthConfigInput &
305
- UserLifecycleHooks & {
330
+ export type AuthOptions<Env = Record<string, unknown>> = AuthConfigInput &
331
+ UserLifecycleHooks<Env> & {
306
332
  /**
307
333
  * Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
308
334
  *
@@ -333,7 +359,7 @@ export type AuthOptions = AuthConfigInput &
333
359
  *
334
360
  * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
335
361
  */
336
- onSessionRevoked?: SessionRevokedListener;
362
+ onSessionRevoked?: SessionRevokedListener<Env>;
337
363
  /**
338
364
  * Decide, per request, what this request's caller is — and so which scope gates it opens.
339
365
  *
@@ -414,13 +440,42 @@ function assertPluginTablesUnclaimed(
414
440
  }
415
441
  }
416
442
 
443
+ /**
444
+ * The attestation half of the client projection for one environment: its mode as the Worker will apply it, and
445
+ * which platforms can pass by attesting, or nothing where the environment has no block. A Worker accepts the test
446
+ * assertion only in the environments {@link testAssertionAllowedIn} names, so a `test` block anywhere else projects
447
+ * as `enforce`. Under `enforce` a platform passes only with an allowed app and a verifier in `verifiers`: without
448
+ * the app its assertion is refused, and without the verifier it is answered `auth/attestation_config`, so it
449
+ * projects `false` and its phones keep Turnstile. The test assertion passes from either platform.
450
+ */
451
+ export function attestationProjection(
452
+ config: AttestationConfig,
453
+ environment: string,
454
+ verifiers: AttestationVerifiers,
455
+ ): Pick<Extract<AuthClientProjection, { enabled: true }>, "attestation"> {
456
+ const block = attestationFor(config, environment);
457
+ if (block === undefined) return {};
458
+ if (block.mode === "test" && testAssertionAllowedIn(environment)) {
459
+ return { attestation: { mode: "test", platforms: { ios: true, android: true } } };
460
+ }
461
+ return {
462
+ attestation: {
463
+ mode: "enforce",
464
+ platforms: {
465
+ ios: block.ios.length > 0 && verifiers.ios !== undefined,
466
+ android: block.android.length > 0 && verifiers.android !== undefined,
467
+ },
468
+ },
469
+ };
470
+ }
471
+
417
472
  /**
418
473
  * The auth capability. Passwordless sign-in (magic link, OTP, Google, Apple), the hybrid bearer +
419
474
  * cookie token model, the per-device session registry, and the `bearer`/`session` fills for core's
420
475
  * `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
421
476
  * and emits `auth/*` through `audit` when those are composed.
422
477
  */
423
- export function auth(options: AuthOptions): AuthCapability {
478
+ export function auth<Env = Record<string, unknown>>(options: AuthOptions<Env>): AuthCapability {
424
479
  // **Destructured before the parse, and that ordering is the whole reason this is not a config field.**
425
480
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
426
481
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
@@ -432,18 +487,24 @@ export function auth(options: AuthOptions): AuthCapability {
432
487
  onUserSuspended,
433
488
  onUserReinstated,
434
489
  onUserDeleted,
490
+ onUserRestored,
435
491
  onUserPurged,
436
492
  ...config
437
493
  } = options;
438
494
  const resolved = AuthConfig.parse(config);
439
495
  // The lifecycle hooks, kept only where one was given, so an absent hook is an absent key rather than an
440
496
  // `undefined` every reader has to tell apart from a hook.
441
- const lifecycleHooks: UserLifecycleHooks = {
497
+ const typedHooks: UserLifecycleHooks<Env> = {
442
498
  ...(onUserSuspended ? { onUserSuspended } : {}),
443
499
  ...(onUserReinstated ? { onUserReinstated } : {}),
444
500
  ...(onUserDeleted ? { onUserDeleted } : {}),
501
+ ...(onUserRestored ? { onUserRestored } : {}),
445
502
  ...(onUserPurged ? { onUserPurged } : {}),
446
503
  };
504
+ // Every fire site hands these the Worker's own env, which is what `Env` names, so widening it here is the one
505
+ // place the adopter's type meets the env the kit holds untyped.
506
+ const lifecycleHooks = typedHooks as unknown as UserLifecycleHooks;
507
+ const sessionRevoked = onSessionRevoked as SessionRevokedListener | undefined;
447
508
  // What may be composed, before anything is built from the list. The four the kit composes are the
448
509
  // sign-in this product promises and what the control-plane seam verifies against, so a list naming one
449
510
  // of them is refused here by name rather than silently redefining a route at request time — and so is a
@@ -458,7 +519,7 @@ export function auth(options: AuthOptions): AuthCapability {
458
519
  resolveGithubUserInfo,
459
520
  enqueueEmail: undefined,
460
521
  turnstile: undefined,
461
- onSessionRevoked,
522
+ onSessionRevoked: sessionRevoked,
462
523
  resolveScopes,
463
524
  lifecycleHooks,
464
525
  purgeSteps: [],
@@ -490,11 +551,14 @@ export function auth(options: AuthOptions): AuthCapability {
490
551
  // Built from the config, so the session secret's overlap is this composition's session lifetime and its
491
552
  // period is the one the adopter asked for, if any.
492
553
  secretRegistry: authSecretsRegistryFor(resolved),
493
- // And which of those four credentials this composition cannot reach. A provider that is off
494
- // has no code path that reads its pair, so `pithy doctor` listing it as outstanding re-raised a
495
- // settled question on every run. Declared rather than inferred: the config key and the secret name
496
- // are spelled alike by coincidence, and this is the only place that holds both.
497
- inapplicableSecrets: inapplicableProviderSecrets(resolved),
554
+ // And which of those credentials this composition cannot reach: a provider that is off, and the Play
555
+ // Integrity service account where no environment allows an Android app. Nothing reads either, so
556
+ // `pithy doctor` does not count it as outstanding. Declared rather than inferred: the config key and the
557
+ // secret name are spelled alike by coincidence, and this is the only place that holds both.
558
+ inapplicableSecrets: {
559
+ ...inapplicableProviderSecrets(resolved),
560
+ ...inapplicablePlayIntegritySecret(resolved.attestation),
561
+ },
498
562
  requiredBindings: [
499
563
  { type: "d1", name: resolved.database },
500
564
  { type: "ratelimit", name: resolved.rateLimiterBinding },
@@ -554,7 +618,7 @@ export function auth(options: AuthOptions): AuthCapability {
554
618
  });
555
619
  }
556
620
  wiring.enqueueEmail = email.enqueue;
557
- // Auto-wire turnstile onto the login routes when it is composed (Jim's requirement: zero config).
621
+ // Turnstile gates the send routes whenever it is composed, with no config on auth's side.
558
622
  wiring.turnstile = turnstileLoginGate(capabilities.find(isTurnstileCapability));
559
623
  // And the one collision `auth()` could not see. A plugin's tables carry the plugin's own names —
560
624
  // `organization`, `member`, `invitation` — with no `pithy_auth_` prefix to keep them out of an
@@ -587,7 +651,7 @@ export function auth(options: AuthOptions): AuthCapability {
587
651
  * could say. The declared type is what makes a dropped field — and a grown one, `baseURL` projected
588
652
  * "just for a redirect" — a compile error here rather than a browser's problem.
589
653
  */
590
- client: (): AuthClientProjection => ({
654
+ client: (context): AuthClientProjection => ({
591
655
  enabled: true,
592
656
  basePath: resolved.basePath,
593
657
  // Nested, so a screen can iterate the set rather than naming four booleans — and so adding a
@@ -610,6 +674,11 @@ export function auth(options: AuthOptions): AuthCapability {
610
674
  },
611
675
  otpLength: resolved.otpLength,
612
676
  signUpEnabled: !resolved.disableSignUp,
677
+ ...attestationProjection(
678
+ resolved.attestation,
679
+ context.environment,
680
+ wiring.attestationVerifiers ?? PLATFORM_VERIFIERS,
681
+ ),
613
682
  }),
614
683
  // Order matters: the same-origin policy is published first, so it is on the request before any
615
684
  // route can gate on it; then the tier-1 edge rate limiter (before session resolution touches D1);