@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,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,6 +18,8 @@ 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";
|
|
@@ -31,7 +33,11 @@ import { getAuthInstance } from "./http/resolve";
|
|
|
31
33
|
import { createAuthRoutes } from "./http/routes";
|
|
32
34
|
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
33
35
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
34
|
-
import {
|
|
36
|
+
import {
|
|
37
|
+
authSecretsRegistryFor,
|
|
38
|
+
inapplicablePlayIntegritySecret,
|
|
39
|
+
inapplicableProviderSecrets,
|
|
40
|
+
} from "./instance/secrets";
|
|
35
41
|
import { authErasureRecords } from "./lifecycle/erasure";
|
|
36
42
|
import type { UserLifecycleHooks } from "./lifecycle/hooks";
|
|
37
43
|
import type { McpHost, McpWiring } from "./mcp/host";
|
|
@@ -188,6 +194,9 @@ export const AuthConfig = z
|
|
|
188
194
|
.describe(
|
|
189
195
|
"Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false.",
|
|
190
196
|
),
|
|
197
|
+
attestation: AttestationConfig.prefault({}).describe(
|
|
198
|
+
"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.",
|
|
199
|
+
),
|
|
191
200
|
plugins: z
|
|
192
201
|
.array(AuthPlugin)
|
|
193
202
|
.default([])
|
|
@@ -225,6 +234,16 @@ export interface AuthWiring {
|
|
|
225
234
|
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
226
235
|
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
227
236
|
turnstile: TurnstileLoginGate | undefined;
|
|
237
|
+
/**
|
|
238
|
+
* The verifier for each platform's real attestations. Absent means the ones this release ships,
|
|
239
|
+
* `PLATFORM_VERIFIERS`; a harness passes its own.
|
|
240
|
+
*/
|
|
241
|
+
attestationVerifiers?: AttestationVerifiers | undefined;
|
|
242
|
+
/**
|
|
243
|
+
* The root CA an App Attest key's certificate chain must lead to, DER. Absent means Apple App Attestation Root
|
|
244
|
+
* CA, pinned in the package; a harness passes the root of its own test chain.
|
|
245
|
+
*/
|
|
246
|
+
appAttestRoot?: Uint8Array | undefined;
|
|
228
247
|
/**
|
|
229
248
|
* The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
|
|
230
249
|
*
|
|
@@ -414,6 +433,35 @@ function assertPluginTablesUnclaimed(
|
|
|
414
433
|
}
|
|
415
434
|
}
|
|
416
435
|
|
|
436
|
+
/**
|
|
437
|
+
* The attestation half of the client projection for one environment: its mode as the Worker will apply it, and
|
|
438
|
+
* which platforms can pass by attesting, or nothing where the environment has no block. A Worker accepts the test
|
|
439
|
+
* assertion only in the environments {@link testAssertionAllowedIn} names, so a `test` block anywhere else projects
|
|
440
|
+
* as `enforce`. Under `enforce` a platform passes only with an allowed app and a verifier in `verifiers`: without
|
|
441
|
+
* the app its assertion is refused, and without the verifier it is answered `auth/attestation_config`, so it
|
|
442
|
+
* projects `false` and its phones keep Turnstile. The test assertion passes from either platform.
|
|
443
|
+
*/
|
|
444
|
+
export function attestationProjection(
|
|
445
|
+
config: AttestationConfig,
|
|
446
|
+
environment: string,
|
|
447
|
+
verifiers: AttestationVerifiers,
|
|
448
|
+
): Pick<Extract<AuthClientProjection, { enabled: true }>, "attestation"> {
|
|
449
|
+
const block = attestationFor(config, environment);
|
|
450
|
+
if (block === undefined) return {};
|
|
451
|
+
if (block.mode === "test" && testAssertionAllowedIn(environment)) {
|
|
452
|
+
return { attestation: { mode: "test", platforms: { ios: true, android: true } } };
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
attestation: {
|
|
456
|
+
mode: "enforce",
|
|
457
|
+
platforms: {
|
|
458
|
+
ios: block.ios.length > 0 && verifiers.ios !== undefined,
|
|
459
|
+
android: block.android.length > 0 && verifiers.android !== undefined,
|
|
460
|
+
},
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
417
465
|
/**
|
|
418
466
|
* The auth capability. Passwordless sign-in (magic link, OTP, Google, Apple), the hybrid bearer +
|
|
419
467
|
* cookie token model, the per-device session registry, and the `bearer`/`session` fills for core's
|
|
@@ -490,11 +538,14 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
490
538
|
// Built from the config, so the session secret's overlap is this composition's session lifetime and its
|
|
491
539
|
// period is the one the adopter asked for, if any.
|
|
492
540
|
secretRegistry: authSecretsRegistryFor(resolved),
|
|
493
|
-
// And which of those
|
|
494
|
-
//
|
|
495
|
-
//
|
|
496
|
-
// are spelled alike by coincidence, and this is the only place that holds both.
|
|
497
|
-
inapplicableSecrets:
|
|
541
|
+
// And which of those credentials this composition cannot reach: a provider that is off, and the Play
|
|
542
|
+
// Integrity service account where no environment allows an Android app. Nothing reads either, so
|
|
543
|
+
// `pithy doctor` does not count it as outstanding. Declared rather than inferred: the config key and the
|
|
544
|
+
// secret name are spelled alike by coincidence, and this is the only place that holds both.
|
|
545
|
+
inapplicableSecrets: {
|
|
546
|
+
...inapplicableProviderSecrets(resolved),
|
|
547
|
+
...inapplicablePlayIntegritySecret(resolved.attestation),
|
|
548
|
+
},
|
|
498
549
|
requiredBindings: [
|
|
499
550
|
{ type: "d1", name: resolved.database },
|
|
500
551
|
{ type: "ratelimit", name: resolved.rateLimiterBinding },
|
|
@@ -554,7 +605,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
554
605
|
});
|
|
555
606
|
}
|
|
556
607
|
wiring.enqueueEmail = email.enqueue;
|
|
557
|
-
//
|
|
608
|
+
// Turnstile gates the send routes whenever it is composed, with no config on auth's side.
|
|
558
609
|
wiring.turnstile = turnstileLoginGate(capabilities.find(isTurnstileCapability));
|
|
559
610
|
// And the one collision `auth()` could not see. A plugin's tables carry the plugin's own names —
|
|
560
611
|
// `organization`, `member`, `invitation` — with no `pithy_auth_` prefix to keep them out of an
|
|
@@ -587,7 +638,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
587
638
|
* could say. The declared type is what makes a dropped field — and a grown one, `baseURL` projected
|
|
588
639
|
* "just for a redirect" — a compile error here rather than a browser's problem.
|
|
589
640
|
*/
|
|
590
|
-
client: (): AuthClientProjection => ({
|
|
641
|
+
client: (context): AuthClientProjection => ({
|
|
591
642
|
enabled: true,
|
|
592
643
|
basePath: resolved.basePath,
|
|
593
644
|
// Nested, so a screen can iterate the set rather than naming four booleans — and so adding a
|
|
@@ -610,6 +661,11 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
610
661
|
},
|
|
611
662
|
otpLength: resolved.otpLength,
|
|
612
663
|
signUpEnabled: !resolved.disableSignUp,
|
|
664
|
+
...attestationProjection(
|
|
665
|
+
resolved.attestation,
|
|
666
|
+
context.environment,
|
|
667
|
+
wiring.attestationVerifiers ?? PLATFORM_VERIFIERS,
|
|
668
|
+
),
|
|
613
669
|
}),
|
|
614
670
|
// Order matters: the same-origin policy is published first, so it is on the request before any
|
|
615
671
|
// route can gate on it; then the tier-1 edge rate limiter (before session resolution touches D1);
|