@pithy-sh/auth 0.15.3 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/attestation/appAttest/assertion.d.ts +32 -0
- package/dist/attestation/appAttest/assertion.d.ts.map +1 -0
- package/dist/attestation/appAttest/assertion.js +59 -0
- package/dist/attestation/appAttest/attestation.d.ts +49 -0
- package/dist/attestation/appAttest/attestation.d.ts.map +1 -0
- package/dist/attestation/appAttest/attestation.js +111 -0
- package/dist/attestation/appAttest/authData.d.ts +24 -0
- package/dist/attestation/appAttest/authData.d.ts.map +1 -0
- package/dist/attestation/appAttest/authData.js +32 -0
- package/dist/attestation/appAttest/base64.d.ts +8 -0
- package/dist/attestation/appAttest/base64.d.ts.map +1 -0
- package/dist/attestation/appAttest/base64.js +27 -0
- package/dist/attestation/appAttest/bytes.d.ts +7 -0
- package/dist/attestation/appAttest/bytes.d.ts.map +1 -0
- package/dist/attestation/appAttest/bytes.js +19 -0
- package/dist/attestation/appAttest/cbor.d.ts +20 -0
- package/dist/attestation/appAttest/cbor.d.ts.map +1 -0
- package/dist/attestation/appAttest/cbor.js +96 -0
- package/dist/attestation/appAttest/der.d.ts +38 -0
- package/dist/attestation/appAttest/der.d.ts.map +1 -0
- package/dist/attestation/appAttest/der.js +106 -0
- package/dist/attestation/appAttest/keys.d.ts +15 -0
- package/dist/attestation/appAttest/keys.d.ts.map +1 -0
- package/dist/attestation/appAttest/keys.js +37 -0
- package/dist/attestation/appAttest/root.d.ts +9 -0
- package/dist/attestation/appAttest/root.d.ts.map +1 -0
- package/dist/attestation/appAttest/root.js +12 -0
- package/dist/attestation/appAttest/verifier.d.ts +39 -0
- package/dist/attestation/appAttest/verifier.d.ts.map +1 -0
- package/dist/attestation/appAttest/verifier.js +121 -0
- package/dist/attestation/appAttest/x509.d.ts +50 -0
- package/dist/attestation/appAttest/x509.d.ts.map +1 -0
- package/dist/attestation/appAttest/x509.js +163 -0
- package/dist/attestation/challenge.d.ts +26 -0
- package/dist/attestation/challenge.d.ts.map +1 -0
- package/dist/attestation/challenge.js +47 -0
- package/dist/attestation/config.d.ts +72 -0
- package/dist/attestation/config.d.ts.map +1 -0
- package/dist/attestation/config.js +52 -0
- package/dist/attestation/errors.d.ts +30 -0
- package/dist/attestation/errors.d.ts.map +1 -0
- package/dist/attestation/errors.js +45 -0
- package/dist/attestation/gate.d.ts +27 -0
- package/dist/attestation/gate.d.ts.map +1 -0
- package/dist/attestation/gate.js +78 -0
- package/dist/attestation/playIntegrity/google.d.ts +47 -0
- package/dist/attestation/playIntegrity/google.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/google.js +178 -0
- package/dist/attestation/playIntegrity/verdict.d.ts +40 -0
- package/dist/attestation/playIntegrity/verdict.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/verdict.js +93 -0
- package/dist/attestation/playIntegrity/verifier.d.ts +22 -0
- package/dist/attestation/playIntegrity/verifier.d.ts.map +1 -0
- package/dist/attestation/playIntegrity/verifier.js +64 -0
- package/dist/attestation/verifier.d.ts +60 -0
- package/dist/attestation/verifier.d.ts.map +1 -0
- package/dist/attestation/verifier.js +46 -0
- package/dist/attestation/wire.d.ts +42 -0
- package/dist/attestation/wire.d.ts.map +1 -0
- package/dist/attestation/wire.js +72 -0
- package/dist/capability.d.ts +40 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +38 -5
- package/dist/client/api.d.ts +37 -24
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +52 -41
- package/dist/client/attestation.d.ts +148 -0
- package/dist/client/attestation.d.ts.map +1 -0
- package/dist/client/attestation.js +321 -0
- package/dist/client/projection.d.ts +29 -4
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/appAttestKey.d.ts +30 -0
- package/dist/data/appAttestKey.d.ts.map +1 -0
- package/dist/data/appAttestKey.js +25 -0
- package/dist/data/attestationChallenge.d.ts +17 -0
- package/dist/data/attestationChallenge.d.ts.map +1 -0
- package/dist/data/attestationChallenge.js +19 -0
- package/dist/data/tables.d.ts +18 -1
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +6 -2
- package/dist/http/devLoginRoute.js +3 -3
- package/dist/http/resolve.js +1 -1
- package/dist/http/responses.d.ts +12 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +11 -1
- package/dist/http/routes.d.ts +5 -1
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +92 -25
- package/dist/http/schemas.d.ts +7 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +7 -1
- package/dist/index.js +1 -1
- package/dist/instance/secrets.d.ts +86 -7
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +54 -8
- package/dist/migrations/0009_attestation_challenges.d.ts +9 -0
- package/dist/migrations/0009_attestation_challenges.d.ts.map +1 -0
- package/dist/migrations/0009_attestation_challenges.js +21 -0
- package/dist/migrations/0010_app_attest_keys.d.ts +9 -0
- package/dist/migrations/0010_app_attest_keys.d.ts.map +1 -0
- package/dist/migrations/0010_app_attest_keys.js +17 -0
- package/dist/migrations/set.d.ts +3 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +6 -2
- package/dist/seeds/devSession.js +1 -1
- package/dist/test-utils/appAttestDevice.d.ts +92 -0
- package/dist/test-utils/appAttestDevice.d.ts.map +1 -0
- package/dist/test-utils/appAttestDevice.js +282 -0
- package/dist/test-utils/appAttestSample.d.ts +22 -0
- package/dist/test-utils/appAttestSample.d.ts.map +1 -0
- package/dist/test-utils/appAttestSample.js +24 -0
- package/dist/test-utils/googlePlay.d.ts +47 -0
- package/dist/test-utils/googlePlay.d.ts.map +1 -0
- package/dist/test-utils/googlePlay.js +117 -0
- package/dist/test-utils/liveApp.d.ts +76 -36
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +16 -5
- package/dist/test-utils/rollbackThrough.d.ts +11 -0
- package/dist/test-utils/rollbackThrough.d.ts.map +1 -0
- package/dist/test-utils/rollbackThrough.js +16 -0
- package/dist/test-utils/scopedBackend.d.ts +25 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +1 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/attestation.md +173 -0
- package/package.json +5 -5
- package/pithy.manifest.json +14 -0
- package/src/attestation/appAttest/assertion.ts +65 -0
- package/src/attestation/appAttest/attestation.ts +159 -0
- package/src/attestation/appAttest/authData.ts +45 -0
- package/src/attestation/appAttest/base64.ts +29 -0
- package/src/attestation/appAttest/bytes.ts +18 -0
- package/src/attestation/appAttest/cbor.ts +116 -0
- package/src/attestation/appAttest/der.ts +126 -0
- package/src/attestation/appAttest/keys.ts +57 -0
- package/src/attestation/appAttest/root.ts +13 -0
- package/src/attestation/appAttest/verifier.ts +113 -0
- package/src/attestation/appAttest/x509.ts +209 -0
- package/src/attestation/challenge.ts +56 -0
- package/src/attestation/config.ts +118 -0
- package/src/attestation/errors.ts +60 -0
- package/src/attestation/gate.ts +105 -0
- package/src/attestation/playIntegrity/google.ts +239 -0
- package/src/attestation/playIntegrity/verdict.ts +149 -0
- package/src/attestation/playIntegrity/verifier.ts +77 -0
- package/src/attestation/verifier.ts +87 -0
- package/src/attestation/wire.ts +79 -0
- package/src/capability.ts +64 -8
- package/src/client/api.ts +73 -40
- package/src/client/attestation.ts +404 -0
- package/src/client/projection.ts +29 -4
- package/src/data/appAttestKey.ts +45 -0
- package/src/data/attestationChallenge.ts +23 -0
- package/src/data/tables.ts +5 -1
- package/src/http/responses.ts +22 -0
- package/src/http/routes.ts +128 -38
- package/src/http/schemas.ts +24 -0
- package/src/instance/secrets.ts +88 -9
- package/src/migrations/0009_attestation_challenges.ts +28 -0
- package/src/migrations/0010_app_attest_keys.ts +27 -0
- package/src/migrations/set.ts +5 -1
- package/src/test-utils/appAttestDevice.ts +399 -0
- package/src/test-utils/appAttestSample.ts +20 -0
- package/src/test-utils/googlePlay.ts +144 -0
- package/src/test-utils/liveApp.ts +31 -5
- package/src/test-utils/rollbackThrough.ts +24 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
|
|
5
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
6
|
+
import { AttestationChallenge } from "../data/attestationChallenge";
|
|
7
|
+
import type { AuthDatabase } from "../data/tables";
|
|
8
|
+
|
|
9
|
+
/** A challenge as the challenge route hands it out. */
|
|
10
|
+
export interface IssuedChallenge {
|
|
11
|
+
challenge: string;
|
|
12
|
+
expiresAt: Date;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** What presenting a challenge established. */
|
|
16
|
+
export type ChallengeUse = { ok: true } | { ok: false; reason: string };
|
|
17
|
+
|
|
18
|
+
async function digest(challenge: string): Promise<string> {
|
|
19
|
+
return base64UrlEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(challenge))));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Issue a challenge good for `expiresIn` seconds from `now`, pruning every one that has already run out. */
|
|
23
|
+
export async function issueChallenge(
|
|
24
|
+
db: AuthDatabase,
|
|
25
|
+
options: { now: Date; expiresIn: number },
|
|
26
|
+
): Promise<IssuedChallenge> {
|
|
27
|
+
const challenge = base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)));
|
|
28
|
+
const expiresAt = new Date(options.now.getTime() + options.expiresIn * 1000);
|
|
29
|
+
await db
|
|
30
|
+
.deleteFrom("pithyAuthAttestationChallenges")
|
|
31
|
+
.where("expiresAt", "<=", SQLiteDate.encode(options.now))
|
|
32
|
+
.execute();
|
|
33
|
+
await db
|
|
34
|
+
.insertInto("pithyAuthAttestationChallenges")
|
|
35
|
+
.values(AttestationChallenge.encode({ id: await digest(challenge), issuedAt: options.now, expiresAt }))
|
|
36
|
+
.execute();
|
|
37
|
+
return { challenge, expiresAt };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Spend a challenge. One `DELETE … RETURNING`, so two requests racing on one challenge cannot both find it live:
|
|
42
|
+
* the first takes the row and the second finds none. An expired challenge is spent and refused.
|
|
43
|
+
*/
|
|
44
|
+
export async function consumeChallenge(db: AuthDatabase, challenge: string, now: Date): Promise<ChallengeUse> {
|
|
45
|
+
const row = await db
|
|
46
|
+
.deleteFrom("pithyAuthAttestationChallenges")
|
|
47
|
+
.where("id", "=", await digest(challenge))
|
|
48
|
+
.returning(["id", "issuedAt", "expiresAt"])
|
|
49
|
+
.executeTakeFirst();
|
|
50
|
+
if (row === undefined) return { ok: false, reason: "the challenge was already used or never issued" };
|
|
51
|
+
const { expiresAt } = AttestationChallenge.parse(row);
|
|
52
|
+
if (expiresAt.getTime() <= now.getTime()) {
|
|
53
|
+
return { ok: false, reason: `the challenge expired at ${expiresAt.toISOString()}` };
|
|
54
|
+
}
|
|
55
|
+
return { ok: true };
|
|
56
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { FEATURE_ENVIRONMENT, isValidEnvironment, LOCAL_ENVIRONMENT } from "@pithy-sh/core/src/naming/environment";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/** The platforms a native app attestation can come from. */
|
|
8
|
+
export const AttestationPlatform = z
|
|
9
|
+
.enum(["ios", "android"])
|
|
10
|
+
.describe("Where an attestation comes from: `ios`, Apple App Attest; `android`, Google Play Integrity.");
|
|
11
|
+
export type AttestationPlatform = z.output<typeof AttestationPlatform>;
|
|
12
|
+
|
|
13
|
+
/** How an environment treats attestations. */
|
|
14
|
+
export const AttestationMode = z
|
|
15
|
+
.enum(["enforce", "test"])
|
|
16
|
+
.describe(
|
|
17
|
+
"`enforce` accepts only a real attestation, judged by its platform's verifier; a platform with no verifier in this release answers `auth/attestation_config`. `test` also accepts the documented test assertion, so simulators, emulators and CI get through. The Worker accepts it only where its `ENVIRONMENT` is `dev`, `staging` or `feature`, whatever this says, and `pithy deploy` refuses a production environment set to `test`.",
|
|
18
|
+
);
|
|
19
|
+
export type AttestationMode = z.output<typeof AttestationMode>;
|
|
20
|
+
|
|
21
|
+
/** An iOS app allowed to attest, as App Attest names it. */
|
|
22
|
+
export const AppleAppIdentity = z
|
|
23
|
+
.object({
|
|
24
|
+
teamId: z
|
|
25
|
+
.string()
|
|
26
|
+
.regex(/^[A-Z0-9]{10}$/, "An Apple Team ID is ten uppercase letters or digits.")
|
|
27
|
+
.describe("The Apple Developer Team ID that signs the app: ten uppercase letters or digits."),
|
|
28
|
+
bundleId: z
|
|
29
|
+
.string()
|
|
30
|
+
.min(1)
|
|
31
|
+
.max(255)
|
|
32
|
+
.describe("The app's bundle identifier, such as `com.example.app`. With the Team ID it is the App ID."),
|
|
33
|
+
})
|
|
34
|
+
.describe("An iOS app allowed to attest: its Team ID and bundle identifier.");
|
|
35
|
+
export type AppleAppIdentity = z.output<typeof AppleAppIdentity>;
|
|
36
|
+
|
|
37
|
+
/** An Android app allowed to attest, as Play Integrity names it. */
|
|
38
|
+
export const AndroidAppIdentity = z
|
|
39
|
+
.object({
|
|
40
|
+
packageName: z
|
|
41
|
+
.string()
|
|
42
|
+
.regex(/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/, "An Android package name is a dotted Java name.")
|
|
43
|
+
.describe("The app's package name as Google Play knows it, such as `com.example.app`."),
|
|
44
|
+
})
|
|
45
|
+
.describe("An Android app allowed to attest: its package name.");
|
|
46
|
+
export type AndroidAppIdentity = z.output<typeof AndroidAppIdentity>;
|
|
47
|
+
|
|
48
|
+
/** One environment's attestation settings. */
|
|
49
|
+
export const AttestationEnvironment = z
|
|
50
|
+
.object({
|
|
51
|
+
mode: AttestationMode.default("enforce"),
|
|
52
|
+
ios: z
|
|
53
|
+
.array(AppleAppIdentity)
|
|
54
|
+
.default([])
|
|
55
|
+
.describe("The iOS apps allowed to attest in this environment. Empty refuses every iOS attestation."),
|
|
56
|
+
android: z
|
|
57
|
+
.array(AndroidAppIdentity)
|
|
58
|
+
.default([])
|
|
59
|
+
.describe("The Android apps allowed to attest in this environment. Empty refuses every Android attestation."),
|
|
60
|
+
})
|
|
61
|
+
.refine((block) => block.mode === "test" || block.ios.length + block.android.length > 0, {
|
|
62
|
+
message: "An enforce block must allow at least one app, or no attestation could ever pass it.",
|
|
63
|
+
})
|
|
64
|
+
.describe(
|
|
65
|
+
"One environment's attestation: the apps allowed to attest and the mode. With a block, the send routes accept an attestation in place of a Turnstile token, and require one when turnstile is not composed.",
|
|
66
|
+
);
|
|
67
|
+
export type AttestationEnvironment = z.output<typeof AttestationEnvironment>;
|
|
68
|
+
|
|
69
|
+
/** Auth's `attestation` block. */
|
|
70
|
+
export const AttestationConfig = z
|
|
71
|
+
.object({
|
|
72
|
+
challengeExpiresIn: z
|
|
73
|
+
.number()
|
|
74
|
+
.int()
|
|
75
|
+
.positive()
|
|
76
|
+
.max(600)
|
|
77
|
+
.default(300)
|
|
78
|
+
.describe("How long a challenge from the challenge route stays usable, in seconds. Defaults to 5 minutes."),
|
|
79
|
+
environments: z
|
|
80
|
+
.record(
|
|
81
|
+
z.string().refine(isValidEnvironment, "Not an environment name.").describe("An environment name."),
|
|
82
|
+
AttestationEnvironment,
|
|
83
|
+
)
|
|
84
|
+
.default({})
|
|
85
|
+
.describe(
|
|
86
|
+
"The attestation block per environment, keyed by the name the Worker is stamped with: `dev`, `staging`, `prod`, `feature` or one you declared. An environment with no block gates its send routes as before.",
|
|
87
|
+
),
|
|
88
|
+
})
|
|
89
|
+
.describe(
|
|
90
|
+
"Native app attestation on the email send routes, per environment: Apple App Attest and Google Play Integrity in place of a Turnstile token.",
|
|
91
|
+
);
|
|
92
|
+
export type AttestationConfig = z.output<typeof AttestationConfig>;
|
|
93
|
+
|
|
94
|
+
/** Whether any environment has an attestation block. Without one, nothing attestation adds is mounted. */
|
|
95
|
+
export function attestationIsConfigured(config: AttestationConfig): boolean {
|
|
96
|
+
return Object.keys(config.environments).length > 0;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The block for the environment this Worker is stamped with, or `undefined` for none and for an unstamped Worker. */
|
|
100
|
+
export function attestationFor(
|
|
101
|
+
config: AttestationConfig,
|
|
102
|
+
environment: string | null,
|
|
103
|
+
): AttestationEnvironment | undefined {
|
|
104
|
+
if (environment === null || !Object.hasOwn(config.environments, environment)) return undefined;
|
|
105
|
+
return config.environments[environment];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The environments a Worker accepts the test assertion in, when their block is set to `test`: dev, staging and a
|
|
110
|
+
* feature deployment. An allowlist, because the Worker cannot read `seed.productionEnvironments`: a name a project
|
|
111
|
+
* declares, such as `live`, could be production, so the Worker holds it to `enforce` whatever its block says.
|
|
112
|
+
*/
|
|
113
|
+
export const TEST_ASSERTION_ENVIRONMENTS = [LOCAL_ENVIRONMENT, "staging", FEATURE_ENVIRONMENT] as const;
|
|
114
|
+
|
|
115
|
+
/** Whether a Worker stamped with `environment` may accept the test assertion. An unstamped Worker may not. */
|
|
116
|
+
export function testAssertionAllowedIn(environment: string | null): boolean {
|
|
117
|
+
return environment !== null && (TEST_ASSERTION_ENVIRONMENTS as readonly string[]).includes(environment);
|
|
118
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { PithyError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
import type { MessageParams } from "@pithy-sh/core/src/i18n/catalog";
|
|
6
|
+
import type { UnmarkedString } from "@pithy-sh/core/src/privacy/types";
|
|
7
|
+
|
|
8
|
+
/** What each refusal takes. `detail` says why, for the operator's log; it never reaches the client. */
|
|
9
|
+
interface AttestationErrorArgs {
|
|
10
|
+
/** Override the public, safe-to-expose message. */
|
|
11
|
+
message?: UnmarkedString;
|
|
12
|
+
/** The operator's remedy (CLI action line). */
|
|
13
|
+
action?: UnmarkedString;
|
|
14
|
+
/** Why it was refused, for logs. Never serialized to clients. */
|
|
15
|
+
detail?: UnmarkedString;
|
|
16
|
+
/** Values a translating client interpolates into its own wording for this code. */
|
|
17
|
+
params?: MessageParams;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** `auth/attestation_missing` (400): attestation is this route's only gate, and the request carried none. */
|
|
21
|
+
export class AttestationMissingError extends PithyError {
|
|
22
|
+
constructor(args: AttestationErrorArgs) {
|
|
23
|
+
super({
|
|
24
|
+
code: "auth/attestation_missing",
|
|
25
|
+
status: 400,
|
|
26
|
+
message: args.message ?? "This app must attest before it can sign in.",
|
|
27
|
+
action: args.action,
|
|
28
|
+
detail: args.detail,
|
|
29
|
+
params: args.params,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `auth/attestation_failed` (403): the attestation did not verify. Never falls through to Turnstile. */
|
|
35
|
+
export class AttestationFailedError extends PithyError {
|
|
36
|
+
constructor(args: AttestationErrorArgs) {
|
|
37
|
+
super({
|
|
38
|
+
code: "auth/attestation_failed",
|
|
39
|
+
status: 403,
|
|
40
|
+
message: args.message ?? "The app's attestation did not verify. Ask for a new challenge and try again.",
|
|
41
|
+
action: args.action,
|
|
42
|
+
detail: args.detail,
|
|
43
|
+
params: args.params,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `auth/attestation_config` (500): the server's attestation setup cannot judge this request. */
|
|
49
|
+
export class AttestationConfigError extends PithyError {
|
|
50
|
+
constructor(args: AttestationErrorArgs) {
|
|
51
|
+
super({
|
|
52
|
+
code: "auth/attestation_config",
|
|
53
|
+
status: 500,
|
|
54
|
+
message: args.message ?? "App attestation is not configured.",
|
|
55
|
+
action: args.action,
|
|
56
|
+
detail: args.detail,
|
|
57
|
+
params: args.params,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { workerIdentity } from "@pithy-sh/core/src/worker/identity";
|
|
5
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
6
|
+
import { authDatabase } from "../data/tables";
|
|
7
|
+
import { resolveDb } from "../http/resolve";
|
|
8
|
+
import { consumeChallenge } from "./challenge";
|
|
9
|
+
import { type AttestationConfig, type AttestationEnvironment, attestationFor } from "./config";
|
|
10
|
+
import { AttestationConfigError, AttestationFailedError, AttestationMissingError } from "./errors";
|
|
11
|
+
import { type AttestationVerifiers, isTestAssertion, verifierFor } from "./verifier";
|
|
12
|
+
import { ATTESTATION_HEADER, decodeAttestation, requestBinding } from "./wire";
|
|
13
|
+
|
|
14
|
+
/** What the send-route gate closes over. */
|
|
15
|
+
export interface SendGateOptions {
|
|
16
|
+
/** Auth's resolved `attestation` block. */
|
|
17
|
+
attestation: AttestationConfig;
|
|
18
|
+
/** The D1 binding auth's tables live in. */
|
|
19
|
+
database: string;
|
|
20
|
+
/** The verifier for each platform's real assertions. */
|
|
21
|
+
verifiers: AttestationVerifiers;
|
|
22
|
+
/** The Turnstile guard a request with no attestation goes to, when turnstile is composed. */
|
|
23
|
+
turnstile: MiddlewareHandler | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The refusal for an environment that has no block to judge an attestation by. */
|
|
27
|
+
function noBlock(environment: string | null): AttestationConfigError {
|
|
28
|
+
const where = environment === null ? "an unstamped Worker" : `the ${environment} environment`;
|
|
29
|
+
return new AttestationConfigError({
|
|
30
|
+
detail: `${where} has no attestation block in auth's config`,
|
|
31
|
+
action: `Add an \`attestation.environments.${environment ?? "<env>"}\` block to auth() in this Worker's pithy.config.ts, then redeploy.`,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Judge one presented attestation. Returns when it verified; throws the refusal otherwise. */
|
|
36
|
+
async function verifyAttestation(
|
|
37
|
+
c: Context,
|
|
38
|
+
header: string,
|
|
39
|
+
settings: AttestationEnvironment,
|
|
40
|
+
environment: string | null,
|
|
41
|
+
options: SendGateOptions,
|
|
42
|
+
): Promise<void> {
|
|
43
|
+
const decoded = decodeAttestation(header);
|
|
44
|
+
if (!decoded.ok) throw new AttestationFailedError({ detail: decoded.reason });
|
|
45
|
+
const presented = decoded.value;
|
|
46
|
+
const env = c.env as Record<string, unknown>;
|
|
47
|
+
const db = authDatabase(resolveDb(env, options.database));
|
|
48
|
+
const now = new Date();
|
|
49
|
+
|
|
50
|
+
// Spent before anything else is judged, so a failed attempt cannot be retried on the same challenge.
|
|
51
|
+
const use = await consumeChallenge(db, presented.challenge, now);
|
|
52
|
+
if (!use.ok) throw new AttestationFailedError({ detail: `challenge: ${use.reason}` });
|
|
53
|
+
|
|
54
|
+
if (!isTestAssertion(presented) && settings[presented.platform].length === 0) {
|
|
55
|
+
throw new AttestationFailedError({
|
|
56
|
+
detail: `no ${presented.platform} app is allowed to attest in ${environment ?? "an unstamped Worker"}`,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
const verifier = verifierFor(presented, options.verifiers);
|
|
60
|
+
if (verifier === undefined) {
|
|
61
|
+
throw new AttestationConfigError({
|
|
62
|
+
detail: `no ${presented.platform} attestation verifier is available to this Worker`,
|
|
63
|
+
action: `Upgrade @pithy-sh/auth to a release that verifies ${presented.platform} attestations, or set this environment to test and send the test assertion.`,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
// The body is read off a clone: the route behind this gate is Better Auth's, and it reads the original.
|
|
67
|
+
const body = new Uint8Array(await c.req.raw.clone().arrayBuffer());
|
|
68
|
+
const binding = await requestBinding(presented.challenge, body);
|
|
69
|
+
const verdict = await verifier.verify({ presented, binding, environment, settings, db, env, now });
|
|
70
|
+
if (!verdict.ok) throw new AttestationFailedError({ detail: verdict.reason });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The gate on auth's send routes once any environment has an attestation block.
|
|
75
|
+
*
|
|
76
|
+
* Either passes. A request carrying {@link ATTESTATION_HEADER} is judged by attestation alone, and a failure
|
|
77
|
+
* there is final. A request without one goes to Turnstile when it is composed; with no Turnstile, it is refused
|
|
78
|
+
* where this environment has a block, and passes where it has none, as it did before attestation existed.
|
|
79
|
+
*/
|
|
80
|
+
export function sendGate(options: SendGateOptions): MiddlewareHandler {
|
|
81
|
+
return async (c, next) => {
|
|
82
|
+
const environment = workerIdentity(c.env).environment;
|
|
83
|
+
const settings = attestationFor(options.attestation, environment);
|
|
84
|
+
const header = c.req.header(ATTESTATION_HEADER);
|
|
85
|
+
if (header !== undefined) {
|
|
86
|
+
if (settings === undefined) throw noBlock(environment);
|
|
87
|
+
await verifyAttestation(c, header, settings, environment, options);
|
|
88
|
+
return next();
|
|
89
|
+
}
|
|
90
|
+
if (options.turnstile !== undefined) return options.turnstile(c, next);
|
|
91
|
+
if (settings !== undefined) {
|
|
92
|
+
throw new AttestationMissingError({
|
|
93
|
+
detail: `no ${ATTESTATION_HEADER} header, and turnstile is not composed to take the request instead`,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return next();
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The challenge route's refusal where this environment has no block. Exported for the route. */
|
|
101
|
+
export function assertAttestationBlock(config: AttestationConfig, environment: string | null): AttestationEnvironment {
|
|
102
|
+
const settings = attestationFor(config, environment);
|
|
103
|
+
if (settings === undefined) throw noBlock(environment);
|
|
104
|
+
return settings;
|
|
105
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { pithyCommand } from "@pithy-sh/core/src/cli/command";
|
|
5
|
+
import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
|
|
6
|
+
import { UpstreamError, UpstreamTimeoutError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT, type PlayIntegrityServiceAccount } from "../../instance/secrets";
|
|
9
|
+
import { AttestationConfigError } from "../errors";
|
|
10
|
+
|
|
11
|
+
/** The OAuth scope `decodeIntegrityToken` takes. */
|
|
12
|
+
export const PLAY_INTEGRITY_SCOPE = "https://www.googleapis.com/auth/playintegrity";
|
|
13
|
+
|
|
14
|
+
/** Google's token endpoint, where a service account's file names none. */
|
|
15
|
+
export const GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token";
|
|
16
|
+
|
|
17
|
+
/** How long one call to Google may take, in milliseconds. */
|
|
18
|
+
export const GOOGLE_DEADLINE_MS = 10_000;
|
|
19
|
+
|
|
20
|
+
/** The longest-lived assertion Google's token endpoint accepts, in seconds. */
|
|
21
|
+
const ASSERTION_LIFETIME_SECONDS = 3600;
|
|
22
|
+
|
|
23
|
+
/** How long before its stated expiry a cached access token is replaced, in milliseconds. */
|
|
24
|
+
const TOKEN_EARLY_REFRESH_MS = 60_000;
|
|
25
|
+
|
|
26
|
+
const PLAY_INTEGRITY_API = "https://playintegrity.googleapis.com/v1";
|
|
27
|
+
|
|
28
|
+
/** The operator's remedy for a service account that is missing, malformed or refused. */
|
|
29
|
+
export const SERVICE_ACCOUNT_ACTION = `Store the Google Cloud service account's JSON key with \`${pithyCommand("secrets create", { args: [AUTH_PLAY_INTEGRITY_SERVICE_ACCOUNT] })}\` for this environment, and link its Google Cloud project to the app in Play Console. See the auth package's docs/attestation.md.`;
|
|
30
|
+
|
|
31
|
+
/** The token endpoint's answer, as far as auth reads it. */
|
|
32
|
+
const AccessTokenAnswer = z
|
|
33
|
+
.object({
|
|
34
|
+
access_token: z.string().min(1).describe("The OAuth access token."),
|
|
35
|
+
expires_in: z.number().positive().describe("How long the token lives, in seconds."),
|
|
36
|
+
})
|
|
37
|
+
.describe("Google's answer to a jwt-bearer grant.");
|
|
38
|
+
|
|
39
|
+
/** `decodeIntegrityToken`'s answer, as far as auth reads it. */
|
|
40
|
+
const DecodeAnswer = z
|
|
41
|
+
.object({
|
|
42
|
+
tokenPayloadExternal: z.record(z.string(), z.unknown()).describe("The decoded token payload."),
|
|
43
|
+
})
|
|
44
|
+
.describe("Google's answer to decodeIntegrityToken.");
|
|
45
|
+
|
|
46
|
+
function decodePem(pem: string): Uint8Array | undefined {
|
|
47
|
+
const body = pem
|
|
48
|
+
.replace(/-----BEGIN PRIVATE KEY-----/, "")
|
|
49
|
+
.replace(/-----END PRIVATE KEY-----/, "")
|
|
50
|
+
.replace(/\s+/g, "");
|
|
51
|
+
if (body.length === 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return undefined;
|
|
52
|
+
try {
|
|
53
|
+
return Uint8Array.from(atob(body), (char) => char.charCodeAt(0));
|
|
54
|
+
} catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function importPrivateKey(account: PlayIntegrityServiceAccount): Promise<CryptoKey> {
|
|
60
|
+
const der = decodePem(account.private_key);
|
|
61
|
+
try {
|
|
62
|
+
if (der === undefined) throw new TypeError("not a PEM");
|
|
63
|
+
return await crypto.subtle.importKey(
|
|
64
|
+
"pkcs8",
|
|
65
|
+
der as Uint8Array<ArrayBuffer>,
|
|
66
|
+
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
|
|
67
|
+
false,
|
|
68
|
+
["sign"],
|
|
69
|
+
);
|
|
70
|
+
} catch {
|
|
71
|
+
throw new AttestationConfigError({
|
|
72
|
+
detail: `the Play Integrity service account ${account.client_email} has a private_key that is not an RSA PKCS#8 PEM`,
|
|
73
|
+
action: SERVICE_ACCOUNT_ACTION,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function encodeJson(value: Record<string, unknown>): string {
|
|
79
|
+
return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Sign the RS256 assertion a service account exchanges for an access token. */
|
|
83
|
+
export async function signServiceAccountAssertion(
|
|
84
|
+
account: PlayIntegrityServiceAccount,
|
|
85
|
+
options: { scope: string; now: Date },
|
|
86
|
+
): Promise<string> {
|
|
87
|
+
const key = await importPrivateKey(account);
|
|
88
|
+
const iat = Math.floor(options.now.getTime() / 1000);
|
|
89
|
+
const header = { alg: "RS256", typ: "JWT", ...(account.private_key_id ? { kid: account.private_key_id } : {}) };
|
|
90
|
+
const claims = {
|
|
91
|
+
iss: account.client_email,
|
|
92
|
+
scope: options.scope,
|
|
93
|
+
aud: account.token_uri ?? GOOGLE_TOKEN_URI,
|
|
94
|
+
iat,
|
|
95
|
+
exp: iat + ASSERTION_LIFETIME_SECONDS,
|
|
96
|
+
};
|
|
97
|
+
const signingInput = `${encodeJson(header)}.${encodeJson(claims)}`;
|
|
98
|
+
const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, new TextEncoder().encode(signingInput));
|
|
99
|
+
return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** One call to Google under {@link GOOGLE_DEADLINE_MS}. A call that never answers is the upstream pair's. */
|
|
103
|
+
async function callGoogle(fetchImpl: typeof fetch, url: string, init: RequestInit, what: string): Promise<Response> {
|
|
104
|
+
try {
|
|
105
|
+
return await fetchImpl(url, { ...init, signal: AbortSignal.timeout(GOOGLE_DEADLINE_MS) });
|
|
106
|
+
} catch (error) {
|
|
107
|
+
const name = error instanceof Error || error instanceof DOMException ? error.name : "";
|
|
108
|
+
if (name === "TimeoutError") {
|
|
109
|
+
throw new UpstreamTimeoutError({ detail: `${what}: Google did not answer within ${GOOGLE_DEADLINE_MS}ms` });
|
|
110
|
+
}
|
|
111
|
+
throw new UpstreamError({ detail: `${what}: Google could not be reached: ${String(error)}` });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Google's own wording for a refusal, from an `{ error }` or `{ error: { message } }` body. */
|
|
116
|
+
async function googleReason(response: Response): Promise<string> {
|
|
117
|
+
const text = await response.text().catch(() => "");
|
|
118
|
+
try {
|
|
119
|
+
const body = JSON.parse(text) as { error?: unknown; error_description?: unknown };
|
|
120
|
+
if (typeof body.error === "string") {
|
|
121
|
+
return typeof body.error_description === "string" ? `${body.error}: ${body.error_description}` : body.error;
|
|
122
|
+
}
|
|
123
|
+
if (typeof body.error === "object" && body.error !== null) {
|
|
124
|
+
const message = (body.error as { message?: unknown }).message;
|
|
125
|
+
if (typeof message === "string") return message;
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// Not JSON: the status alone is the reason.
|
|
129
|
+
}
|
|
130
|
+
return `HTTP ${response.status}`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The access tokens a verifier holds, one per service account, each kept until shortly before it expires. */
|
|
134
|
+
export interface GoogleAccessTokens {
|
|
135
|
+
/** A live access token for `account`, minted when none is held. */
|
|
136
|
+
get(account: PlayIntegrityServiceAccount, now: Date): Promise<string>;
|
|
137
|
+
/** Forget `account`'s token, so the next {@link get} mints a new one. */
|
|
138
|
+
drop(account: PlayIntegrityServiceAccount): void;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function cacheKey(account: PlayIntegrityServiceAccount): string {
|
|
142
|
+
return `${account.client_email}\n${account.private_key_id ?? ""}\n${account.token_uri ?? GOOGLE_TOKEN_URI}`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Access tokens for the Play Integrity scope. Google refusing the account is `auth/attestation_config`; Google
|
|
147
|
+
* failing, or answering something that is not a token, is `core/upstream_failed` or `core/upstream_timeout`.
|
|
148
|
+
*/
|
|
149
|
+
export function createGoogleAccessTokens(fetchImpl: typeof fetch): GoogleAccessTokens {
|
|
150
|
+
const held = new Map<string, { token: string; expiresAt: number }>();
|
|
151
|
+
return {
|
|
152
|
+
async get(account, now) {
|
|
153
|
+
const key = cacheKey(account);
|
|
154
|
+
const cached = held.get(key);
|
|
155
|
+
if (cached !== undefined && now.getTime() < cached.expiresAt) return cached.token;
|
|
156
|
+
|
|
157
|
+
const assertion = await signServiceAccountAssertion(account, { scope: PLAY_INTEGRITY_SCOPE, now });
|
|
158
|
+
const tokenUri = account.token_uri ?? GOOGLE_TOKEN_URI;
|
|
159
|
+
const response = await callGoogle(
|
|
160
|
+
fetchImpl,
|
|
161
|
+
tokenUri,
|
|
162
|
+
{
|
|
163
|
+
method: "POST",
|
|
164
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
165
|
+
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }),
|
|
166
|
+
},
|
|
167
|
+
"token",
|
|
168
|
+
);
|
|
169
|
+
if (response.status === 400 || response.status === 401 || response.status === 403) {
|
|
170
|
+
throw new AttestationConfigError({
|
|
171
|
+
detail: `Google refused the Play Integrity service account ${account.client_email} at ${tokenUri} (${response.status}): ${await googleReason(response)}`,
|
|
172
|
+
action: SERVICE_ACCOUNT_ACTION,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
throw new UpstreamError({
|
|
177
|
+
detail: `token: ${tokenUri} answered ${response.status}: ${await googleReason(response)}`,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const answer = AccessTokenAnswer.safeParse(await response.json().catch(() => undefined));
|
|
181
|
+
if (!answer.success) throw new UpstreamError({ detail: `token: ${tokenUri} answered 200 with no access token` });
|
|
182
|
+
held.set(key, {
|
|
183
|
+
token: answer.data.access_token,
|
|
184
|
+
expiresAt: now.getTime() + answer.data.expires_in * 1000 - TOKEN_EARLY_REFRESH_MS,
|
|
185
|
+
});
|
|
186
|
+
return answer.data.access_token;
|
|
187
|
+
},
|
|
188
|
+
drop(account) {
|
|
189
|
+
held.delete(cacheKey(account));
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A token decoded, or refused by Google for this package. */
|
|
195
|
+
export type DecodedIntegrityToken = { ok: true; payload: Record<string, unknown> } | { ok: false; reason: string };
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Call `decodeIntegrityToken` for `packageName`. A 400 is the token refused for this package; a 401, 403 or 404 is
|
|
199
|
+
* the server's credential or project setup, `auth/attestation_config`; anything else Google gets wrong is the
|
|
200
|
+
* upstream pair's.
|
|
201
|
+
*/
|
|
202
|
+
export async function decodeIntegrityToken(
|
|
203
|
+
fetchImpl: typeof fetch,
|
|
204
|
+
input: { accessToken: string; packageName: string; token: string },
|
|
205
|
+
): Promise<DecodedIntegrityToken> {
|
|
206
|
+
const url = `${PLAY_INTEGRITY_API}/${encodeURIComponent(input.packageName)}:decodeIntegrityToken`;
|
|
207
|
+
const response = await callGoogle(
|
|
208
|
+
fetchImpl,
|
|
209
|
+
url,
|
|
210
|
+
{
|
|
211
|
+
method: "POST",
|
|
212
|
+
headers: { authorization: `Bearer ${input.accessToken}`, "content-type": "application/json" },
|
|
213
|
+
body: JSON.stringify({ integrity_token: input.token }),
|
|
214
|
+
},
|
|
215
|
+
"decode",
|
|
216
|
+
);
|
|
217
|
+
if (response.status === 400) {
|
|
218
|
+
return {
|
|
219
|
+
ok: false,
|
|
220
|
+
reason: `Google would not decode it for ${input.packageName}: ${await googleReason(response)}`,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (response.status === 401 || response.status === 403 || response.status === 404) {
|
|
224
|
+
throw new AttestationConfigError({
|
|
225
|
+
detail: `decodeIntegrityToken for ${input.packageName} answered ${response.status}: ${await googleReason(response)}`,
|
|
226
|
+
action: `Enable the Play Integrity API in the service account's Google Cloud project, and link that project to ${input.packageName} in Play Console under Test and release > App integrity.`,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
if (!response.ok) {
|
|
230
|
+
throw new UpstreamError({
|
|
231
|
+
detail: `decode: decodeIntegrityToken for ${input.packageName} answered ${response.status}: ${await googleReason(response)}`,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
const answer = DecodeAnswer.safeParse(await response.json().catch(() => undefined));
|
|
235
|
+
if (!answer.success) {
|
|
236
|
+
throw new UpstreamError({ detail: `decode: decodeIntegrityToken answered 200 with no tokenPayloadExternal` });
|
|
237
|
+
}
|
|
238
|
+
return { ok: true, payload: answer.data.tokenPayloadExternal };
|
|
239
|
+
}
|