@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.
- 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 +49 -6
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +42 -7
- 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 +19 -1
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +6 -2
- package/dist/data/userLifecycle.d.ts +1 -0
- package/dist/data/userLifecycle.d.ts.map +1 -1
- package/dist/data/userLifecycle.js +3 -2
- package/dist/hooks/runtime.d.ts +32 -0
- package/dist/hooks/runtime.d.ts.map +1 -0
- package/dist/hooks/runtime.js +25 -0
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +4 -2
- package/dist/http/devLoginRoute.js +3 -3
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +3 -2
- package/dist/http/responses.d.ts +15 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +13 -2
- 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/lifecycle/erasure.d.ts.map +1 -1
- package/dist/lifecycle/erasure.js +2 -1
- package/dist/lifecycle/hooks.d.ts +18 -10
- package/dist/lifecycle/hooks.d.ts.map +1 -1
- package/dist/lifecycle/request.d.ts +2 -1
- package/dist/lifecycle/request.d.ts.map +1 -1
- package/dist/lifecycle/request.js +4 -1
- package/dist/lifecycle/transitions.d.ts +24 -16
- package/dist/lifecycle/transitions.d.ts.map +1 -1
- package/dist/lifecycle/transitions.js +27 -16
- 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/0011_retained_basis_key.d.ts +10 -0
- package/dist/migrations/0011_retained_basis_key.d.ts.map +1 -0
- package/dist/migrations/0011_retained_basis_key.js +18 -0
- package/dist/migrations/set.d.ts +4 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +8 -2
- package/dist/purge/run.d.ts +11 -11
- package/dist/purge/run.d.ts.map +1 -1
- package/dist/purge/run.js +9 -8
- package/dist/purge/workflow.d.ts +7 -1
- package/dist/purge/workflow.d.ts.map +1 -1
- package/dist/purge/workflow.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/account-lifecycle.md +46 -10
- 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 +85 -16
- 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/data/userLifecycle.ts +9 -2
- package/src/hooks/runtime.ts +41 -0
- package/src/http/adminRoutes.ts +14 -7
- package/src/http/resolve.ts +8 -4
- package/src/http/responses.ts +29 -1
- package/src/http/routes.ts +128 -38
- package/src/http/schemas.ts +24 -0
- package/src/instance/secrets.ts +88 -9
- package/src/lifecycle/erasure.ts +2 -1
- package/src/lifecycle/hooks.ts +22 -10
- package/src/lifecycle/request.ts +4 -1
- package/src/lifecycle/transitions.ts +47 -28
- package/src/migrations/0009_attestation_challenges.ts +28 -0
- package/src/migrations/0010_app_attest_keys.ts +27 -0
- package/src/migrations/0011_retained_basis_key.ts +19 -0
- package/src/migrations/set.ts +7 -1
- package/src/purge/run.ts +29 -17
- package/src/purge/workflow.ts +7 -3
- 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,116 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A CBOR reader for what App Attest sends (RFC 8949): unsigned and negative integers, byte and text strings,
|
|
6
|
+
* arrays, maps, `true`, `false` and `null`, all of definite length. Anything else, and any byte left over, is
|
|
7
|
+
* a {@link CborError}, because every input here is attacker-supplied.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** A decoded CBOR value. Maps keep their keys' own types, so an integer key never collides with a text one. */
|
|
11
|
+
export type CborValue = number | boolean | null | string | Uint8Array | CborValue[] | Map<CborValue, CborValue>;
|
|
12
|
+
|
|
13
|
+
/** The input is not CBOR this reader accepts. */
|
|
14
|
+
export class CborError extends Error {
|
|
15
|
+
override name = "CborError";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const MAX_DEPTH = 16;
|
|
19
|
+
|
|
20
|
+
class Reader {
|
|
21
|
+
offset = 0;
|
|
22
|
+
private readonly bytes: Uint8Array;
|
|
23
|
+
constructor(bytes: Uint8Array) {
|
|
24
|
+
this.bytes = bytes;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
take(length: number): Uint8Array {
|
|
28
|
+
if (length > this.bytes.length - this.offset) throw new CborError("CBOR runs past the end of its input");
|
|
29
|
+
const slice = this.bytes.subarray(this.offset, this.offset + length);
|
|
30
|
+
this.offset += length;
|
|
31
|
+
return slice;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
byte(): number {
|
|
35
|
+
return this.take(1)[0] as number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
argument(additional: number): number {
|
|
39
|
+
if (additional < 24) return additional;
|
|
40
|
+
const width = additional === 24 ? 1 : additional === 25 ? 2 : additional === 26 ? 4 : additional === 27 ? 8 : 0;
|
|
41
|
+
if (width === 0) throw new CborError(`CBOR additional information ${additional} is not supported`);
|
|
42
|
+
let value = 0;
|
|
43
|
+
for (const byte of this.take(width)) value = value * 256 + byte;
|
|
44
|
+
if (!Number.isSafeInteger(value)) throw new CborError("CBOR integer is past 2^53");
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
value(depth: number): CborValue {
|
|
49
|
+
if (depth > MAX_DEPTH) throw new CborError("CBOR is nested too deep");
|
|
50
|
+
const initial = this.byte();
|
|
51
|
+
const major = initial >> 5;
|
|
52
|
+
const additional = initial & 0x1f;
|
|
53
|
+
if (major === 7) {
|
|
54
|
+
if (additional === 20) return false;
|
|
55
|
+
if (additional === 21) return true;
|
|
56
|
+
if (additional === 22) return null;
|
|
57
|
+
throw new CborError(`CBOR simple value or float ${additional} is not supported`);
|
|
58
|
+
}
|
|
59
|
+
if (major === 6) throw new CborError("CBOR tags are not supported");
|
|
60
|
+
const argument = this.argument(additional);
|
|
61
|
+
switch (major) {
|
|
62
|
+
case 0:
|
|
63
|
+
return argument;
|
|
64
|
+
case 1:
|
|
65
|
+
return -1 - argument;
|
|
66
|
+
case 2:
|
|
67
|
+
return this.take(argument).slice();
|
|
68
|
+
case 3:
|
|
69
|
+
try {
|
|
70
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(this.take(argument));
|
|
71
|
+
} catch (cause) {
|
|
72
|
+
if (cause instanceof CborError) throw cause;
|
|
73
|
+
throw new CborError("CBOR text string is not UTF-8");
|
|
74
|
+
}
|
|
75
|
+
case 4: {
|
|
76
|
+
// Every item is at least one byte, so a count past what is left cannot be real.
|
|
77
|
+
if (argument > this.bytes.length - this.offset)
|
|
78
|
+
throw new CborError("CBOR array runs past the end of its input");
|
|
79
|
+
const items: CborValue[] = [];
|
|
80
|
+
for (let i = 0; i < argument; i++) items.push(this.value(depth + 1));
|
|
81
|
+
return items;
|
|
82
|
+
}
|
|
83
|
+
default: {
|
|
84
|
+
if (argument * 2 > this.bytes.length - this.offset)
|
|
85
|
+
throw new CborError("CBOR map runs past the end of its input");
|
|
86
|
+
const map = new Map<CborValue, CborValue>();
|
|
87
|
+
for (let i = 0; i < argument; i++) {
|
|
88
|
+
const key = this.value(depth + 1);
|
|
89
|
+
if (map.has(key)) throw new CborError("CBOR map repeats a key");
|
|
90
|
+
map.set(key, this.value(depth + 1));
|
|
91
|
+
}
|
|
92
|
+
return map;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Decode exactly one CBOR item that fills `bytes`. Throws {@link CborError} on anything else. */
|
|
99
|
+
export function decodeCbor(bytes: Uint8Array): CborValue {
|
|
100
|
+
const reader = new Reader(bytes);
|
|
101
|
+
const value = reader.value(0);
|
|
102
|
+
if (reader.offset !== bytes.length) throw new CborError("CBOR has bytes after its one item");
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The byte-string field `key` of a decoded map, or `undefined` when it is absent, or not a map or bytes. */
|
|
107
|
+
export function cborBytes(value: CborValue, key: string): Uint8Array | undefined {
|
|
108
|
+
const field = value instanceof Map ? value.get(key) : undefined;
|
|
109
|
+
return field instanceof Uint8Array ? field : undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The text field `key` of a decoded map, or `undefined` when it is absent, or not a map or text. */
|
|
113
|
+
export function cborText(value: CborValue, key: string): string | undefined {
|
|
114
|
+
const field = value instanceof Map ? value.get(key) : undefined;
|
|
115
|
+
return typeof field === "string" ? field : undefined;
|
|
116
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A DER reader (X.690) for the certificates App Attest sends: definite, minimal lengths, low tag numbers. Anything
|
|
6
|
+
* else is a {@link DerError}, because every input here is attacker-supplied.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The input is not DER this reader accepts. */
|
|
10
|
+
export class DerError extends Error {
|
|
11
|
+
override name = "DerError";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** One DER element. */
|
|
15
|
+
export interface DerNode {
|
|
16
|
+
/** The identifier octet: class, constructed bit and tag number. */
|
|
17
|
+
tag: number;
|
|
18
|
+
/** The content octets. */
|
|
19
|
+
content: Uint8Array;
|
|
20
|
+
/** The whole element, identifier and length included: what a signature over it covers. */
|
|
21
|
+
raw: Uint8Array;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const DER_INTEGER = 0x02;
|
|
25
|
+
export const DER_BIT_STRING = 0x03;
|
|
26
|
+
export const DER_OCTET_STRING = 0x04;
|
|
27
|
+
export const DER_OID = 0x06;
|
|
28
|
+
export const DER_BOOLEAN = 0x01;
|
|
29
|
+
export const DER_SEQUENCE = 0x30;
|
|
30
|
+
const UTC_TIME = 0x17;
|
|
31
|
+
const GENERALIZED_TIME = 0x18;
|
|
32
|
+
|
|
33
|
+
/** Read the element at `offset`, and answer it with the offset just past it. */
|
|
34
|
+
function readAt(bytes: Uint8Array, offset: number): { node: DerNode; end: number } {
|
|
35
|
+
if (offset + 2 > bytes.length) throw new DerError("DER element runs past the end of its input");
|
|
36
|
+
const tag = bytes[offset] as number;
|
|
37
|
+
if ((tag & 0x1f) === 0x1f) throw new DerError("DER high tag numbers are not supported");
|
|
38
|
+
let length = bytes[offset + 1] as number;
|
|
39
|
+
let header = 2;
|
|
40
|
+
if (length & 0x80) {
|
|
41
|
+
const width = length & 0x7f;
|
|
42
|
+
if (width === 0) throw new DerError("DER indefinite lengths are not allowed");
|
|
43
|
+
if (width > 4) throw new DerError("DER length is wider than four bytes");
|
|
44
|
+
if (offset + 2 + width > bytes.length) throw new DerError("DER length runs past the end of its input");
|
|
45
|
+
length = 0;
|
|
46
|
+
for (let i = 0; i < width; i++) length = length * 256 + (bytes[offset + 2 + i] as number);
|
|
47
|
+
if (length < 0x80 || (bytes[offset + 2] as number) === 0) throw new DerError("DER length is not minimal");
|
|
48
|
+
header += width;
|
|
49
|
+
}
|
|
50
|
+
const end = offset + header + length;
|
|
51
|
+
if (end > bytes.length) throw new DerError("DER content runs past the end of its input");
|
|
52
|
+
return {
|
|
53
|
+
node: { tag, content: bytes.subarray(offset + header, end), raw: bytes.subarray(offset, end) },
|
|
54
|
+
end,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Read exactly one element that fills `bytes`. */
|
|
59
|
+
export function readDer(bytes: Uint8Array): DerNode {
|
|
60
|
+
const { node, end } = readAt(bytes, 0);
|
|
61
|
+
if (end !== bytes.length) throw new DerError("DER has bytes after its one element");
|
|
62
|
+
return node;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The elements inside a constructed element, in order. */
|
|
66
|
+
export function derChildren(node: DerNode): DerNode[] {
|
|
67
|
+
if ((node.tag & 0x20) === 0) throw new DerError("DER element is primitive and has no children");
|
|
68
|
+
const children: DerNode[] = [];
|
|
69
|
+
let offset = 0;
|
|
70
|
+
while (offset < node.content.length) {
|
|
71
|
+
const { node: child, end } = readAt(node.content, offset);
|
|
72
|
+
children.push(child);
|
|
73
|
+
offset = end;
|
|
74
|
+
}
|
|
75
|
+
return children;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Assert `node` carries `tag`, naming `what` when it does not. */
|
|
79
|
+
export function expectTag(node: DerNode | undefined, tag: number, what: string): DerNode {
|
|
80
|
+
if (node === undefined || node.tag !== tag) throw new DerError(`${what} is missing or has the wrong DER type`);
|
|
81
|
+
return node;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** An INTEGER's content octets, two's complement big-endian. */
|
|
85
|
+
export function derInteger(node: DerNode | undefined): Uint8Array {
|
|
86
|
+
return expectTag(node, DER_INTEGER, "the integer").content;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** An OBJECT IDENTIFIER in dotted form. */
|
|
90
|
+
export function derOid(node: DerNode | undefined): string {
|
|
91
|
+
const content = expectTag(node, DER_OID, "the object identifier").content;
|
|
92
|
+
if (content.length === 0) throw new DerError("DER object identifier is empty");
|
|
93
|
+
const arcs: number[] = [];
|
|
94
|
+
let value = 0;
|
|
95
|
+
for (const byte of content) {
|
|
96
|
+
value = value * 128 + (byte & 0x7f);
|
|
97
|
+
if (!Number.isSafeInteger(value)) throw new DerError("DER object identifier arc is too large");
|
|
98
|
+
if ((byte & 0x80) === 0) {
|
|
99
|
+
arcs.push(value);
|
|
100
|
+
value = 0;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if ((content[content.length - 1] as number) & 0x80) throw new DerError("DER object identifier is truncated");
|
|
104
|
+
const first = arcs.shift() as number;
|
|
105
|
+
const head = first < 40 ? [0, first] : first < 80 ? [1, first - 40] : [2, first - 80];
|
|
106
|
+
return [...head, ...arcs].join(".");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** A UTCTime or GeneralizedTime, which RFC 5280 requires in UTC to the second. */
|
|
110
|
+
export function derTime(node: DerNode | undefined): Date {
|
|
111
|
+
if (node === undefined) throw new DerError("DER time is missing");
|
|
112
|
+
const text = new TextDecoder().decode(node.content);
|
|
113
|
+
const match =
|
|
114
|
+
node.tag === UTC_TIME
|
|
115
|
+
? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(text)
|
|
116
|
+
: node.tag === GENERALIZED_TIME
|
|
117
|
+
? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(text)
|
|
118
|
+
: null;
|
|
119
|
+
if (match === null) throw new DerError("DER time is not a UTC UTCTime or GeneralizedTime to the second");
|
|
120
|
+
const [, y, mo, d, h, mi, s] = match.map(Number) as number[];
|
|
121
|
+
// RFC 5280 §4.1.2.5.1: a two-digit year of 50 or more is 19YY, below 50 is 20YY.
|
|
122
|
+
const year = node.tag === UTC_TIME ? (y as number) + ((y as number) >= 50 ? 1900 : 2000) : (y as number);
|
|
123
|
+
const time = Date.UTC(year, (mo as number) - 1, d, h, mi, s);
|
|
124
|
+
if (Number.isNaN(time)) throw new DerError("DER time is not a real date");
|
|
125
|
+
return new Date(time);
|
|
126
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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 { AppAttestKey } from "../../data/appAttestKey";
|
|
7
|
+
import type { AuthDatabase } from "../../data/tables";
|
|
8
|
+
import type { AttestedAppAttestKey } from "./attestation";
|
|
9
|
+
|
|
10
|
+
/** Store a key an attestation proved, at counter zero. Answers false when the key id is already registered. */
|
|
11
|
+
export async function storeAppAttestKey(db: AuthDatabase, key: AttestedAppAttestKey, now: Date): Promise<boolean> {
|
|
12
|
+
const result = await db
|
|
13
|
+
.insertInto("pithyAuthAppAttestKeys")
|
|
14
|
+
.values(
|
|
15
|
+
AppAttestKey.encode({
|
|
16
|
+
id: base64UrlEncode(key.keyId),
|
|
17
|
+
publicKey: base64UrlEncode(key.publicKey),
|
|
18
|
+
appId: key.appId,
|
|
19
|
+
environment: key.environment,
|
|
20
|
+
counter: 0,
|
|
21
|
+
createdAt: now,
|
|
22
|
+
lastUsedAt: null,
|
|
23
|
+
}),
|
|
24
|
+
)
|
|
25
|
+
.onConflict((conflict) => conflict.column("id").doNothing())
|
|
26
|
+
.executeTakeFirst();
|
|
27
|
+
return Number(result.numInsertedOrUpdatedRows ?? 0n) === 1;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The registered key with this id, or `undefined`. */
|
|
31
|
+
export async function findAppAttestKey(db: AuthDatabase, keyId: Uint8Array): Promise<AppAttestKey | undefined> {
|
|
32
|
+
const row = await db
|
|
33
|
+
.selectFrom("pithyAuthAppAttestKeys")
|
|
34
|
+
.selectAll()
|
|
35
|
+
.where("id", "=", base64UrlEncode(keyId))
|
|
36
|
+
.executeTakeFirst();
|
|
37
|
+
return row === undefined ? undefined : AppAttestKey.parse(row);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Store an assertion's counter, only if it is still above the stored one. One conditional `UPDATE`, so two
|
|
42
|
+
* requests racing on one counter cannot both move it: answers false for the one that lost.
|
|
43
|
+
*/
|
|
44
|
+
export async function advanceAppAttestCounter(
|
|
45
|
+
db: AuthDatabase,
|
|
46
|
+
keyId: Uint8Array,
|
|
47
|
+
counter: number,
|
|
48
|
+
now: Date,
|
|
49
|
+
): Promise<boolean> {
|
|
50
|
+
const result = await db
|
|
51
|
+
.updateTable("pithyAuthAppAttestKeys")
|
|
52
|
+
.set({ counter, lastUsedAt: SQLiteDate.encode(now) })
|
|
53
|
+
.where("id", "=", base64UrlEncode(keyId))
|
|
54
|
+
.where("counter", "<", counter)
|
|
55
|
+
.executeTakeFirst();
|
|
56
|
+
return Number(result.numUpdatedRows) === 1;
|
|
57
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { decodeBase64 } from "./base64";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Apple App Attestation Root CA, DER, as Apple publishes it at
|
|
8
|
+
* https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. Valid to 2045-03-15. Its SHA-256
|
|
9
|
+
* fingerprint is `1CB9823BA28BA6AD2D33A006941DE2AE4F513EF1D4E831B9F7E0FA7B6242C932`, which `root.workers.test.ts` pins.
|
|
10
|
+
*/
|
|
11
|
+
export const APPLE_APP_ATTESTATION_ROOT: Uint8Array = decodeBase64(
|
|
12
|
+
"MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYwJAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNaFw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlvbiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdhNbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9auYen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijVoyFraWVIyd/dganmrduC1bmTBGwD",
|
|
13
|
+
) as Uint8Array;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { AuthDatabase } from "../../data/tables";
|
|
5
|
+
import { consumeChallenge } from "../challenge";
|
|
6
|
+
import { type AppleAppIdentity, testAssertionAllowedIn } from "../config";
|
|
7
|
+
import type { AttestationVerdict, AttestationVerifier } from "../verifier";
|
|
8
|
+
import { requestBinding } from "../wire";
|
|
9
|
+
import { verifyAppAttestAssertion } from "./assertion";
|
|
10
|
+
import { verifyAppAttestation } from "./attestation";
|
|
11
|
+
import { decodeBase64 } from "./base64";
|
|
12
|
+
import { advanceAppAttestCounter, findAppAttestKey, storeAppAttestKey } from "./keys";
|
|
13
|
+
|
|
14
|
+
/** The App ID App Attest hashes into `rpIdHash`: `<TeamID>.<bundleId>`. */
|
|
15
|
+
export function appIdOf(app: AppleAppIdentity): string {
|
|
16
|
+
return `${app.teamId}.${app.bundleId}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Whether a development key is accepted where the Worker is stamped `environment`: in dev, staging and a feature
|
|
21
|
+
* deployment, as the test assertion is, and nowhere else. A production key is accepted everywhere.
|
|
22
|
+
*/
|
|
23
|
+
export function developmentKeysAllowedIn(environment: string | null): boolean {
|
|
24
|
+
return testAssertionAllowedIn(environment);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A key id as `generateKey` hands it over, decoded, or `undefined` when it is not 32 bytes of base64. */
|
|
28
|
+
function decodeKeyId(keyId: string): Uint8Array | undefined {
|
|
29
|
+
const bytes = decodeBase64(keyId);
|
|
30
|
+
return bytes?.length === 32 ? bytes : undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What registering a key takes. */
|
|
34
|
+
export interface AppAttestRegistration {
|
|
35
|
+
db: AuthDatabase;
|
|
36
|
+
/** The challenge the app attested over. Spent first, pass or fail. */
|
|
37
|
+
challenge: string;
|
|
38
|
+
/** The key id, base64, as `generateKey` hands it over. */
|
|
39
|
+
keyId: string;
|
|
40
|
+
/** The attestation object, base64, as `attestKey` hands it over. */
|
|
41
|
+
attestation: string;
|
|
42
|
+
/** The iOS apps this environment allows. */
|
|
43
|
+
apps: readonly AppleAppIdentity[];
|
|
44
|
+
environment: string | null;
|
|
45
|
+
/** The root CA the chain must lead to, DER. */
|
|
46
|
+
root: Uint8Array;
|
|
47
|
+
now: Date;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Register an App Attest key. The challenge is spent before anything is judged; the app attested over
|
|
52
|
+
* {@link requestBinding} of the challenge and an empty body, which is SHA-256 of the challenge's characters.
|
|
53
|
+
*/
|
|
54
|
+
export async function registerAppAttestKey(input: AppAttestRegistration): Promise<AttestationVerdict> {
|
|
55
|
+
const use = await consumeChallenge(input.db, input.challenge, input.now);
|
|
56
|
+
if (!use.ok) return { ok: false, reason: `challenge: ${use.reason}` };
|
|
57
|
+
if (input.apps.length === 0) return { ok: false, reason: "rpIdHash: no iOS app is allowed to attest here" };
|
|
58
|
+
const keyId = decodeKeyId(input.keyId);
|
|
59
|
+
if (keyId === undefined) return { ok: false, reason: "keyId: the key id is not 32 bytes of base64" };
|
|
60
|
+
const attestation = decodeBase64(input.attestation);
|
|
61
|
+
if (attestation === undefined) return { ok: false, reason: "format: the attestation object is not base64" };
|
|
62
|
+
|
|
63
|
+
const result = await verifyAppAttestation({
|
|
64
|
+
attestation,
|
|
65
|
+
keyId,
|
|
66
|
+
clientDataHash: await requestBinding(input.challenge, new Uint8Array(0)),
|
|
67
|
+
apps: input.apps,
|
|
68
|
+
allowDevelopment: developmentKeysAllowedIn(input.environment),
|
|
69
|
+
root: input.root,
|
|
70
|
+
now: input.now,
|
|
71
|
+
});
|
|
72
|
+
if (!result.ok) return { ok: false, reason: `${result.check}: ${result.reason}` };
|
|
73
|
+
if (!(await storeAppAttestKey(input.db, result.key, input.now))) {
|
|
74
|
+
return { ok: false, reason: "keyId: this key is already registered" };
|
|
75
|
+
}
|
|
76
|
+
return { ok: true };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Apple App Attest. Verifies an assertion from a registered key over the request binding: the key is known, its
|
|
81
|
+
* app is still allowed, the signature verifies, and the counter rises. Then stores the counter.
|
|
82
|
+
*/
|
|
83
|
+
export const appAttestVerifier: AttestationVerifier = {
|
|
84
|
+
async verify({ presented, binding, environment, settings, db, now }) {
|
|
85
|
+
if (presented.keyId === undefined) return { ok: false, reason: "keyId: no App Attest key id was presented" };
|
|
86
|
+
const keyId = decodeKeyId(presented.keyId);
|
|
87
|
+
if (keyId === undefined) return { ok: false, reason: "keyId: the key id is not 32 bytes of base64" };
|
|
88
|
+
const key = await findAppAttestKey(db, keyId);
|
|
89
|
+
if (key === undefined) return { ok: false, reason: "key: no App Attest key with this id is registered" };
|
|
90
|
+
if (!settings.ios.some((app) => appIdOf(app) === key.appId)) {
|
|
91
|
+
return { ok: false, reason: `rpIdHash: the key's app ${key.appId} is not allowed to attest here` };
|
|
92
|
+
}
|
|
93
|
+
if (key.environment === "development" && !developmentKeysAllowedIn(environment)) {
|
|
94
|
+
return { ok: false, reason: "aaguid: a development key is refused here: only production keys are accepted" };
|
|
95
|
+
}
|
|
96
|
+
const assertion = decodeBase64(presented.assertion);
|
|
97
|
+
if (assertion === undefined) return { ok: false, reason: "format: the assertion is not base64" };
|
|
98
|
+
const publicKey = decodeBase64(key.publicKey) as Uint8Array;
|
|
99
|
+
|
|
100
|
+
const result = await verifyAppAttestAssertion({
|
|
101
|
+
assertion,
|
|
102
|
+
publicKey,
|
|
103
|
+
appId: key.appId,
|
|
104
|
+
clientDataHash: binding,
|
|
105
|
+
counter: key.counter,
|
|
106
|
+
});
|
|
107
|
+
if (!result.ok) return { ok: false, reason: `${result.check}: ${result.reason}` };
|
|
108
|
+
if (!(await advanceAppAttestCounter(db, keyId, result.counter, now))) {
|
|
109
|
+
return { ok: false, reason: `counter: ${result.counter} was overtaken by another assertion from this key` };
|
|
110
|
+
}
|
|
111
|
+
return { ok: true };
|
|
112
|
+
},
|
|
113
|
+
};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { equalBytes } from "./bytes";
|
|
5
|
+
import {
|
|
6
|
+
DER_BIT_STRING,
|
|
7
|
+
DER_BOOLEAN,
|
|
8
|
+
DER_OCTET_STRING,
|
|
9
|
+
DER_SEQUENCE,
|
|
10
|
+
DerError,
|
|
11
|
+
type DerNode,
|
|
12
|
+
derChildren,
|
|
13
|
+
derInteger,
|
|
14
|
+
derOid,
|
|
15
|
+
derTime,
|
|
16
|
+
expectTag,
|
|
17
|
+
readDer,
|
|
18
|
+
} from "./der";
|
|
19
|
+
|
|
20
|
+
/** The elliptic curves an App Attest chain uses: P-384 for the root and intermediate, P-256 for the key. */
|
|
21
|
+
export type Curve = "P-256" | "P-384";
|
|
22
|
+
|
|
23
|
+
/** An EC public key as a certificate carries it. */
|
|
24
|
+
export interface EcPublicKey {
|
|
25
|
+
curve: Curve;
|
|
26
|
+
/** The X9.62 uncompressed point: `0x04`, then X and Y. */
|
|
27
|
+
point: Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The parts of an X.509 certificate this verifier reads. */
|
|
31
|
+
export interface Certificate {
|
|
32
|
+
/** The DER `tbsCertificate`: what the issuer signed. */
|
|
33
|
+
tbs: Uint8Array;
|
|
34
|
+
/** The signature algorithm's hash. */
|
|
35
|
+
hash: "SHA-256" | "SHA-384";
|
|
36
|
+
/** The DER ECDSA signature. */
|
|
37
|
+
signature: Uint8Array;
|
|
38
|
+
/** The DER issuer name, compared byte for byte against the issuer's subject. */
|
|
39
|
+
issuer: Uint8Array;
|
|
40
|
+
/** The DER subject name. */
|
|
41
|
+
subject: Uint8Array;
|
|
42
|
+
notBefore: Date;
|
|
43
|
+
notAfter: Date;
|
|
44
|
+
publicKey: EcPublicKey;
|
|
45
|
+
/** Each extension's `extnValue` contents, by OID. */
|
|
46
|
+
extensions: Map<string, Uint8Array>;
|
|
47
|
+
/** Whether basic constraints mark it a CA. */
|
|
48
|
+
isCA: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const EC_PUBLIC_KEY = "1.2.840.10045.2.1";
|
|
52
|
+
const CURVES: Record<string, Curve> = { "1.2.840.10045.3.1.7": "P-256", "1.3.132.0.34": "P-384" };
|
|
53
|
+
const SIGNATURE_HASHES: Record<string, Certificate["hash"]> = {
|
|
54
|
+
"1.2.840.10045.4.3.2": "SHA-256",
|
|
55
|
+
"1.2.840.10045.4.3.3": "SHA-384",
|
|
56
|
+
};
|
|
57
|
+
const BASIC_CONSTRAINTS = "2.5.29.19";
|
|
58
|
+
const FIELD_BYTES: Record<Curve, number> = { "P-256": 32, "P-384": 48 };
|
|
59
|
+
|
|
60
|
+
function bitStringBytes(node: DerNode | undefined, what: string): Uint8Array {
|
|
61
|
+
const content = expectTag(node, DER_BIT_STRING, what).content;
|
|
62
|
+
if (content[0] !== 0) throw new DerError(`${what} has unused bits`);
|
|
63
|
+
return content.subarray(1);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function signatureHash(node: DerNode | undefined): Certificate["hash"] {
|
|
67
|
+
const [identifier] = derChildren(expectTag(node, DER_SEQUENCE, "the signature algorithm"));
|
|
68
|
+
const oid = derOid(identifier);
|
|
69
|
+
const hash = SIGNATURE_HASHES[oid];
|
|
70
|
+
if (hash === undefined) throw new DerError(`signature algorithm ${oid} is not ECDSA with SHA-256 or SHA-384`);
|
|
71
|
+
return hash;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function publicKey(node: DerNode | undefined): EcPublicKey {
|
|
75
|
+
const [algorithm, key] = derChildren(expectTag(node, DER_SEQUENCE, "the subject public key info"));
|
|
76
|
+
const [type, parameters] = derChildren(expectTag(algorithm, DER_SEQUENCE, "the public key algorithm"));
|
|
77
|
+
if (derOid(type) !== EC_PUBLIC_KEY) throw new DerError("the public key is not an EC key");
|
|
78
|
+
const curve = parameters === undefined ? undefined : CURVES[derOid(parameters)];
|
|
79
|
+
if (curve === undefined) throw new DerError("the public key is not on P-256 or P-384");
|
|
80
|
+
const point = bitStringBytes(key, "the public key");
|
|
81
|
+
if (point.length !== 1 + 2 * FIELD_BYTES[curve] || point[0] !== 0x04) {
|
|
82
|
+
throw new DerError("the public key is not an uncompressed point");
|
|
83
|
+
}
|
|
84
|
+
return { curve, point };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function extensions(node: DerNode | undefined): Map<string, Uint8Array> {
|
|
88
|
+
const found = new Map<string, Uint8Array>();
|
|
89
|
+
if (node === undefined) return found;
|
|
90
|
+
const [list] = derChildren(node);
|
|
91
|
+
for (const extension of derChildren(expectTag(list, DER_SEQUENCE, "the extensions"))) {
|
|
92
|
+
const parts = derChildren(expectTag(extension, DER_SEQUENCE, "an extension"));
|
|
93
|
+
const oid = derOid(parts[0]);
|
|
94
|
+
const value = parts[parts.length - 1];
|
|
95
|
+
if (parts.length === 3) expectTag(parts[1], DER_BOOLEAN, "an extension's critical flag");
|
|
96
|
+
if (found.has(oid)) throw new DerError(`extension ${oid} appears twice`);
|
|
97
|
+
found.set(oid, expectTag(value, DER_OCTET_STRING, "an extension's value").content);
|
|
98
|
+
}
|
|
99
|
+
return found;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isCA(found: Map<string, Uint8Array>): boolean {
|
|
103
|
+
const value = found.get(BASIC_CONSTRAINTS);
|
|
104
|
+
if (value === undefined) return false;
|
|
105
|
+
const [flag] = derChildren(expectTag(readDer(value), DER_SEQUENCE, "basic constraints"));
|
|
106
|
+
return flag?.tag === DER_BOOLEAN && flag.content[0] === 0xff;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Read an X.509 certificate. Throws {@link DerError} on anything this verifier cannot read. */
|
|
110
|
+
export function parseCertificate(der: Uint8Array): Certificate {
|
|
111
|
+
const [tbsNode, algorithm, signature] = derChildren(expectTag(readDer(der), DER_SEQUENCE, "the certificate"));
|
|
112
|
+
const tbs = expectTag(tbsNode, DER_SEQUENCE, "the tbsCertificate");
|
|
113
|
+
const fields = derChildren(tbs);
|
|
114
|
+
// The version is an explicit [0]; without it the certificate is v1, which carries no extensions.
|
|
115
|
+
const offset = fields[0]?.tag === 0xa0 ? 1 : 0;
|
|
116
|
+
const [, innerAlgorithm, issuer, validity, subject, spki] = fields.slice(offset);
|
|
117
|
+
derInteger(fields[offset]);
|
|
118
|
+
if (innerAlgorithm === undefined || algorithm === undefined || !equalBytes(innerAlgorithm.raw, algorithm.raw)) {
|
|
119
|
+
throw new DerError("the certificate's two signature algorithms disagree");
|
|
120
|
+
}
|
|
121
|
+
const [notBefore, notAfter] = derChildren(expectTag(validity, DER_SEQUENCE, "the validity"));
|
|
122
|
+
const found = extensions(fields.slice(offset + 6).find((field) => field.tag === 0xa3));
|
|
123
|
+
return {
|
|
124
|
+
tbs: tbs.raw,
|
|
125
|
+
hash: signatureHash(algorithm),
|
|
126
|
+
signature: bitStringBytes(signature, "the signature"),
|
|
127
|
+
issuer: expectTag(issuer, DER_SEQUENCE, "the issuer").raw,
|
|
128
|
+
subject: expectTag(subject, DER_SEQUENCE, "the subject").raw,
|
|
129
|
+
notBefore: derTime(notBefore),
|
|
130
|
+
notAfter: derTime(notAfter),
|
|
131
|
+
publicKey: publicKey(spki),
|
|
132
|
+
extensions: found,
|
|
133
|
+
isCA: isCA(found),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A DER ECDSA signature as WebCrypto takes it: `r` and `s`, each left-padded to the curve's field size. */
|
|
138
|
+
export function derSignatureToRaw(signature: Uint8Array, curve: Curve): Uint8Array | undefined {
|
|
139
|
+
const size = FIELD_BYTES[curve];
|
|
140
|
+
try {
|
|
141
|
+
const [r, s, extra] = derChildren(expectTag(readDer(signature), DER_SEQUENCE, "the signature"));
|
|
142
|
+
if (r === undefined || s === undefined || extra !== undefined) return undefined;
|
|
143
|
+
const raw = new Uint8Array(size * 2);
|
|
144
|
+
for (const [index, part] of [derInteger(r), derInteger(s)].entries()) {
|
|
145
|
+
if (part.length === 0 || (part[0] as number) & 0x80) return undefined;
|
|
146
|
+
let start = 0;
|
|
147
|
+
while (start < part.length - 1 && part[start] === 0) start++;
|
|
148
|
+
const digits = part.subarray(start);
|
|
149
|
+
if (digits.length > size) return undefined;
|
|
150
|
+
raw.set(digits, index * size + size - digits.length);
|
|
151
|
+
}
|
|
152
|
+
return raw;
|
|
153
|
+
} catch (cause) {
|
|
154
|
+
if (cause instanceof DerError) return undefined;
|
|
155
|
+
throw cause;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Whether `signature`, DER-encoded, is `key`'s ECDSA signature over `data` with `hash`. */
|
|
160
|
+
export async function verifyEcdsa(
|
|
161
|
+
key: EcPublicKey,
|
|
162
|
+
hash: "SHA-256" | "SHA-384",
|
|
163
|
+
signature: Uint8Array,
|
|
164
|
+
data: Uint8Array,
|
|
165
|
+
): Promise<boolean> {
|
|
166
|
+
const raw = derSignatureToRaw(signature, key.curve);
|
|
167
|
+
if (raw === undefined) return false;
|
|
168
|
+
let imported: CryptoKey;
|
|
169
|
+
try {
|
|
170
|
+
imported = await crypto.subtle.importKey("raw", key.point, { name: "ECDSA", namedCurve: key.curve }, false, [
|
|
171
|
+
"verify",
|
|
172
|
+
]);
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
return crypto.subtle.verify({ name: "ECDSA", hash }, imported, raw, data);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Why a chain did not verify, or that it did. */
|
|
180
|
+
export type ChainVerdict = { ok: true } | { ok: false; reason: string };
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Verify that `chain` (leaf first) leads to `root`: each certificate names the next as its issuer, is signed by
|
|
184
|
+
* it, and is valid at `now`, every issuer is a CA, and the root is valid at `now` too. The root is trusted as
|
|
185
|
+
* given; it is never read from the chain.
|
|
186
|
+
*/
|
|
187
|
+
export async function verifyChain(chain: readonly Certificate[], root: Certificate, now: Date): Promise<ChainVerdict> {
|
|
188
|
+
if (chain.length === 0) return { ok: false, reason: "the chain is empty" };
|
|
189
|
+
const all = [...chain, root];
|
|
190
|
+
for (const [index, cert] of all.entries()) {
|
|
191
|
+
const name = index === 0 ? "the leaf certificate" : index === all.length - 1 ? "the root" : `certificate ${index}`;
|
|
192
|
+
if (now < cert.notBefore || now > cert.notAfter) {
|
|
193
|
+
return {
|
|
194
|
+
ok: false,
|
|
195
|
+
reason: `${name} is not valid at ${now.toISOString()} (valid ${cert.notBefore.toISOString()} to ${cert.notAfter.toISOString()})`,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
const issuer = all[index + 1];
|
|
199
|
+
if (issuer === undefined) break;
|
|
200
|
+
if (!issuer.isCA) return { ok: false, reason: `the issuer of ${name} is not a CA` };
|
|
201
|
+
if (!equalBytes(cert.issuer, issuer.subject)) {
|
|
202
|
+
return { ok: false, reason: `${name} names an issuer other than the next certificate` };
|
|
203
|
+
}
|
|
204
|
+
if (!(await verifyEcdsa(issuer.publicKey, cert.hash, cert.signature, cert.tbs))) {
|
|
205
|
+
return { ok: false, reason: `${name} is not signed by its issuer` };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return { ok: true };
|
|
209
|
+
}
|