@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,106 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
//#region src/attestation/appAttest/der.ts
|
|
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
|
+
/** The input is not DER this reader accepts. */
|
|
9
|
+
var DerError = class extends Error {
|
|
10
|
+
name = "DerError";
|
|
11
|
+
};
|
|
12
|
+
const DER_INTEGER = 2;
|
|
13
|
+
const DER_BIT_STRING = 3;
|
|
14
|
+
const DER_OCTET_STRING = 4;
|
|
15
|
+
const DER_OID = 6;
|
|
16
|
+
const DER_BOOLEAN = 1;
|
|
17
|
+
const DER_SEQUENCE = 48;
|
|
18
|
+
const UTC_TIME = 23;
|
|
19
|
+
const GENERALIZED_TIME = 24;
|
|
20
|
+
/** Read the element at `offset`, and answer it with the offset just past it. */
|
|
21
|
+
function readAt(bytes, offset) {
|
|
22
|
+
if (offset + 2 > bytes.length) throw new DerError("DER element runs past the end of its input");
|
|
23
|
+
const tag = bytes[offset];
|
|
24
|
+
if ((tag & 31) === 31) throw new DerError("DER high tag numbers are not supported");
|
|
25
|
+
let length = bytes[offset + 1];
|
|
26
|
+
let header = 2;
|
|
27
|
+
if (length & 128) {
|
|
28
|
+
const width = length & 127;
|
|
29
|
+
if (width === 0) throw new DerError("DER indefinite lengths are not allowed");
|
|
30
|
+
if (width > 4) throw new DerError("DER length is wider than four bytes");
|
|
31
|
+
if (offset + 2 + width > bytes.length) throw new DerError("DER length runs past the end of its input");
|
|
32
|
+
length = 0;
|
|
33
|
+
for (let i = 0; i < width; i++) length = length * 256 + bytes[offset + 2 + i];
|
|
34
|
+
if (length < 128 || bytes[offset + 2] === 0) throw new DerError("DER length is not minimal");
|
|
35
|
+
header += width;
|
|
36
|
+
}
|
|
37
|
+
const end = offset + header + length;
|
|
38
|
+
if (end > bytes.length) throw new DerError("DER content runs past the end of its input");
|
|
39
|
+
return {
|
|
40
|
+
node: {
|
|
41
|
+
tag,
|
|
42
|
+
content: bytes.subarray(offset + header, end),
|
|
43
|
+
raw: bytes.subarray(offset, end)
|
|
44
|
+
},
|
|
45
|
+
end
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Read exactly one element that fills `bytes`. */
|
|
49
|
+
function readDer(bytes) {
|
|
50
|
+
const { node, end } = readAt(bytes, 0);
|
|
51
|
+
if (end !== bytes.length) throw new DerError("DER has bytes after its one element");
|
|
52
|
+
return node;
|
|
53
|
+
}
|
|
54
|
+
/** The elements inside a constructed element, in order. */
|
|
55
|
+
function derChildren(node) {
|
|
56
|
+
if ((node.tag & 32) === 0) throw new DerError("DER element is primitive and has no children");
|
|
57
|
+
const children = [];
|
|
58
|
+
let offset = 0;
|
|
59
|
+
while (offset < node.content.length) {
|
|
60
|
+
const { node: child, end } = readAt(node.content, offset);
|
|
61
|
+
children.push(child);
|
|
62
|
+
offset = end;
|
|
63
|
+
}
|
|
64
|
+
return children;
|
|
65
|
+
}
|
|
66
|
+
/** Assert `node` carries `tag`, naming `what` when it does not. */
|
|
67
|
+
function expectTag(node, tag, what) {
|
|
68
|
+
if (node === void 0 || node.tag !== tag) throw new DerError(`${what} is missing or has the wrong DER type`);
|
|
69
|
+
return node;
|
|
70
|
+
}
|
|
71
|
+
/** An INTEGER's content octets, two's complement big-endian. */
|
|
72
|
+
function derInteger(node) {
|
|
73
|
+
return expectTag(node, 2, "the integer").content;
|
|
74
|
+
}
|
|
75
|
+
/** An OBJECT IDENTIFIER in dotted form. */
|
|
76
|
+
function derOid(node) {
|
|
77
|
+
const content = expectTag(node, 6, "the object identifier").content;
|
|
78
|
+
if (content.length === 0) throw new DerError("DER object identifier is empty");
|
|
79
|
+
const arcs = [];
|
|
80
|
+
let value = 0;
|
|
81
|
+
for (const byte of content) {
|
|
82
|
+
value = value * 128 + (byte & 127);
|
|
83
|
+
if (!Number.isSafeInteger(value)) throw new DerError("DER object identifier arc is too large");
|
|
84
|
+
if ((byte & 128) === 0) {
|
|
85
|
+
arcs.push(value);
|
|
86
|
+
value = 0;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (content[content.length - 1] & 128) throw new DerError("DER object identifier is truncated");
|
|
90
|
+
const first = arcs.shift();
|
|
91
|
+
return [...first < 40 ? [0, first] : first < 80 ? [1, first - 40] : [2, first - 80], ...arcs].join(".");
|
|
92
|
+
}
|
|
93
|
+
/** A UTCTime or GeneralizedTime, which RFC 5280 requires in UTC to the second. */
|
|
94
|
+
function derTime(node) {
|
|
95
|
+
if (node === void 0) throw new DerError("DER time is missing");
|
|
96
|
+
const text = new TextDecoder().decode(node.content);
|
|
97
|
+
const match = node.tag === UTC_TIME ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(text) : node.tag === GENERALIZED_TIME ? /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(text) : null;
|
|
98
|
+
if (match === null) throw new DerError("DER time is not a UTC UTCTime or GeneralizedTime to the second");
|
|
99
|
+
const [, y, mo, d, h, mi, s] = match.map(Number);
|
|
100
|
+
const year = node.tag === UTC_TIME ? y + (y >= 50 ? 1900 : 2e3) : y;
|
|
101
|
+
const time = Date.UTC(year, mo - 1, d, h, mi, s);
|
|
102
|
+
if (Number.isNaN(time)) throw new DerError("DER time is not a real date");
|
|
103
|
+
return new Date(time);
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { DER_BIT_STRING, DER_BOOLEAN, DER_INTEGER, DER_OCTET_STRING, DER_OID, DER_SEQUENCE, DerError, derChildren, derInteger, derOid, derTime, expectTag, readDer };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { AppAttestKey } from "../../data/appAttestKey";
|
|
4
|
+
import type { AuthDatabase } from "../../data/tables";
|
|
5
|
+
import type { AttestedAppAttestKey } from "./attestation";
|
|
6
|
+
/** Store a key an attestation proved, at counter zero. Answers false when the key id is already registered. */
|
|
7
|
+
export declare function storeAppAttestKey(db: AuthDatabase, key: AttestedAppAttestKey, now: Date): Promise<boolean>;
|
|
8
|
+
/** The registered key with this id, or `undefined`. */
|
|
9
|
+
export declare function findAppAttestKey(db: AuthDatabase, keyId: Uint8Array): Promise<AppAttestKey | undefined>;
|
|
10
|
+
/**
|
|
11
|
+
* Store an assertion's counter, only if it is still above the stored one. One conditional `UPDATE`, so two
|
|
12
|
+
* requests racing on one counter cannot both move it: answers false for the one that lost.
|
|
13
|
+
*/
|
|
14
|
+
export declare function advanceAppAttestCounter(db: AuthDatabase, keyId: Uint8Array, counter: number, now: Date): Promise<boolean>;
|
|
15
|
+
//# sourceMappingURL=keys.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../../src/attestation/appAttest/keys.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAE1D,+GAA+G;AAC/G,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,YAAY,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAiBhH;AAED,uDAAuD;AACvD,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAO7G;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,EAAE,EAAE,YAAY,EAChB,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,IAAI,GACR,OAAO,CAAC,OAAO,CAAC,CAQlB"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { AppAttestKey } from "../../data/appAttestKey.js";
|
|
4
|
+
import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
|
|
5
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
6
|
+
//#region src/attestation/appAttest/keys.ts
|
|
7
|
+
/** Store a key an attestation proved, at counter zero. Answers false when the key id is already registered. */
|
|
8
|
+
async function storeAppAttestKey(db, key, now) {
|
|
9
|
+
const result = await db.insertInto("pithyAuthAppAttestKeys").values(AppAttestKey.encode({
|
|
10
|
+
id: base64UrlEncode(key.keyId),
|
|
11
|
+
publicKey: base64UrlEncode(key.publicKey),
|
|
12
|
+
appId: key.appId,
|
|
13
|
+
environment: key.environment,
|
|
14
|
+
counter: 0,
|
|
15
|
+
createdAt: now,
|
|
16
|
+
lastUsedAt: null
|
|
17
|
+
})).onConflict((conflict) => conflict.column("id").doNothing()).executeTakeFirst();
|
|
18
|
+
return Number(result.numInsertedOrUpdatedRows ?? 0n) === 1;
|
|
19
|
+
}
|
|
20
|
+
/** The registered key with this id, or `undefined`. */
|
|
21
|
+
async function findAppAttestKey(db, keyId) {
|
|
22
|
+
const row = await db.selectFrom("pithyAuthAppAttestKeys").selectAll().where("id", "=", base64UrlEncode(keyId)).executeTakeFirst();
|
|
23
|
+
return row === void 0 ? void 0 : AppAttestKey.parse(row);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Store an assertion's counter, only if it is still above the stored one. One conditional `UPDATE`, so two
|
|
27
|
+
* requests racing on one counter cannot both move it: answers false for the one that lost.
|
|
28
|
+
*/
|
|
29
|
+
async function advanceAppAttestCounter(db, keyId, counter, now) {
|
|
30
|
+
const result = await db.updateTable("pithyAuthAppAttestKeys").set({
|
|
31
|
+
counter,
|
|
32
|
+
lastUsedAt: SQLiteDate.encode(now)
|
|
33
|
+
}).where("id", "=", base64UrlEncode(keyId)).where("counter", "<", counter).executeTakeFirst();
|
|
34
|
+
return Number(result.numUpdatedRows) === 1;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { advanceAppAttestCounter, findAppAttestKey, storeAppAttestKey };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/**
|
|
4
|
+
* Apple App Attestation Root CA, DER, as Apple publishes it at
|
|
5
|
+
* https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. Valid to 2045-03-15. Its SHA-256
|
|
6
|
+
* fingerprint is `1CB9823BA28BA6AD2D33A006941DE2AE4F513EF1D4E831B9F7E0FA7B6242C932`, which `root.workers.test.ts` pins.
|
|
7
|
+
*/
|
|
8
|
+
export declare const APPLE_APP_ATTESTATION_ROOT: Uint8Array;
|
|
9
|
+
//# sourceMappingURL=root.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root.d.ts","sourceRoot":"","sources":["../../../src/attestation/appAttest/root.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,EAAE,UAE1B,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { decodeBase64 } from "./base64.js";
|
|
4
|
+
//#region src/attestation/appAttest/root.ts
|
|
5
|
+
/**
|
|
6
|
+
* Apple App Attestation Root CA, DER, as Apple publishes it at
|
|
7
|
+
* https://www.apple.com/certificateauthority/Apple_App_Attestation_Root_CA.pem. Valid to 2045-03-15. Its SHA-256
|
|
8
|
+
* fingerprint is `1CB9823BA28BA6AD2D33A006941DE2AE4F513EF1D4E831B9F7E0FA7B6242C932`, which `root.workers.test.ts` pins.
|
|
9
|
+
*/
|
|
10
|
+
const APPLE_APP_ATTESTATION_ROOT = decodeBase64("MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYwJAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNaFw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlvbiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdhNbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9auYen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijVoyFraWVIyd/dganmrduC1bmTBGwD");
|
|
11
|
+
//#endregion
|
|
12
|
+
export { APPLE_APP_ATTESTATION_ROOT };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { AuthDatabase } from "../../data/tables";
|
|
4
|
+
import { type AppleAppIdentity } from "../config";
|
|
5
|
+
import type { AttestationVerdict, AttestationVerifier } from "../verifier";
|
|
6
|
+
/** The App ID App Attest hashes into `rpIdHash`: `<TeamID>.<bundleId>`. */
|
|
7
|
+
export declare function appIdOf(app: AppleAppIdentity): string;
|
|
8
|
+
/**
|
|
9
|
+
* Whether a development key is accepted where the Worker is stamped `environment`: in dev, staging and a feature
|
|
10
|
+
* deployment, as the test assertion is, and nowhere else. A production key is accepted everywhere.
|
|
11
|
+
*/
|
|
12
|
+
export declare function developmentKeysAllowedIn(environment: string | null): boolean;
|
|
13
|
+
/** What registering a key takes. */
|
|
14
|
+
export interface AppAttestRegistration {
|
|
15
|
+
db: AuthDatabase;
|
|
16
|
+
/** The challenge the app attested over. Spent first, pass or fail. */
|
|
17
|
+
challenge: string;
|
|
18
|
+
/** The key id, base64, as `generateKey` hands it over. */
|
|
19
|
+
keyId: string;
|
|
20
|
+
/** The attestation object, base64, as `attestKey` hands it over. */
|
|
21
|
+
attestation: string;
|
|
22
|
+
/** The iOS apps this environment allows. */
|
|
23
|
+
apps: readonly AppleAppIdentity[];
|
|
24
|
+
environment: string | null;
|
|
25
|
+
/** The root CA the chain must lead to, DER. */
|
|
26
|
+
root: Uint8Array;
|
|
27
|
+
now: Date;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Register an App Attest key. The challenge is spent before anything is judged; the app attested over
|
|
31
|
+
* {@link requestBinding} of the challenge and an empty body, which is SHA-256 of the challenge's characters.
|
|
32
|
+
*/
|
|
33
|
+
export declare function registerAppAttestKey(input: AppAttestRegistration): Promise<AttestationVerdict>;
|
|
34
|
+
/**
|
|
35
|
+
* Apple App Attest. Verifies an assertion from a registered key over the request binding: the key is known, its
|
|
36
|
+
* app is still allowed, the signature verifies, and the counter rises. Then stores the counter.
|
|
37
|
+
*/
|
|
38
|
+
export declare const appAttestVerifier: AttestationVerifier;
|
|
39
|
+
//# sourceMappingURL=verifier.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verifier.d.ts","sourceRoot":"","sources":["../../../src/attestation/appAttest/verifier.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,KAAK,gBAAgB,EAA0B,MAAM,WAAW,CAAC;AAC1E,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAO3E,2EAA2E;AAC3E,wBAAgB,OAAO,CAAC,GAAG,EAAE,gBAAgB,GAAG,MAAM,CAErD;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAE5E;AAQD,oCAAoC;AACpC,MAAM,WAAW,qBAAqB;IACpC,EAAE,EAAE,YAAY,CAAC;IACjB,sEAAsE;IACtE,SAAS,EAAE,MAAM,CAAC;IAClB,0DAA0D;IAC1D,KAAK,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,WAAW,EAAE,MAAM,CAAC;IACpB,4CAA4C;IAC5C,IAAI,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,+CAA+C;IAC/C,IAAI,EAAE,UAAU,CAAC;IACjB,GAAG,EAAE,IAAI,CAAC;CACX;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAuBpG;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,EAAE,mBA8B/B,CAAC"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { testAssertionAllowedIn } from "../config.js";
|
|
4
|
+
import { consumeChallenge } from "../challenge.js";
|
|
5
|
+
import { requestBinding } from "../wire.js";
|
|
6
|
+
import { verifyAppAttestAssertion } from "./assertion.js";
|
|
7
|
+
import { verifyAppAttestation } from "./attestation.js";
|
|
8
|
+
import { decodeBase64 } from "./base64.js";
|
|
9
|
+
import { advanceAppAttestCounter, findAppAttestKey, storeAppAttestKey } from "./keys.js";
|
|
10
|
+
//#region src/attestation/appAttest/verifier.ts
|
|
11
|
+
/** The App ID App Attest hashes into `rpIdHash`: `<TeamID>.<bundleId>`. */
|
|
12
|
+
function appIdOf(app) {
|
|
13
|
+
return `${app.teamId}.${app.bundleId}`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Whether a development key is accepted where the Worker is stamped `environment`: in dev, staging and a feature
|
|
17
|
+
* deployment, as the test assertion is, and nowhere else. A production key is accepted everywhere.
|
|
18
|
+
*/
|
|
19
|
+
function developmentKeysAllowedIn(environment) {
|
|
20
|
+
return testAssertionAllowedIn(environment);
|
|
21
|
+
}
|
|
22
|
+
/** A key id as `generateKey` hands it over, decoded, or `undefined` when it is not 32 bytes of base64. */
|
|
23
|
+
function decodeKeyId(keyId) {
|
|
24
|
+
const bytes = decodeBase64(keyId);
|
|
25
|
+
return bytes?.length === 32 ? bytes : void 0;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Register an App Attest key. The challenge is spent before anything is judged; the app attested over
|
|
29
|
+
* {@link requestBinding} of the challenge and an empty body, which is SHA-256 of the challenge's characters.
|
|
30
|
+
*/
|
|
31
|
+
async function registerAppAttestKey(input) {
|
|
32
|
+
const use = await consumeChallenge(input.db, input.challenge, input.now);
|
|
33
|
+
if (!use.ok) return {
|
|
34
|
+
ok: false,
|
|
35
|
+
reason: `challenge: ${use.reason}`
|
|
36
|
+
};
|
|
37
|
+
if (input.apps.length === 0) return {
|
|
38
|
+
ok: false,
|
|
39
|
+
reason: "rpIdHash: no iOS app is allowed to attest here"
|
|
40
|
+
};
|
|
41
|
+
const keyId = decodeKeyId(input.keyId);
|
|
42
|
+
if (keyId === void 0) return {
|
|
43
|
+
ok: false,
|
|
44
|
+
reason: "keyId: the key id is not 32 bytes of base64"
|
|
45
|
+
};
|
|
46
|
+
const attestation = decodeBase64(input.attestation);
|
|
47
|
+
if (attestation === void 0) return {
|
|
48
|
+
ok: false,
|
|
49
|
+
reason: "format: the attestation object is not base64"
|
|
50
|
+
};
|
|
51
|
+
const result = await verifyAppAttestation({
|
|
52
|
+
attestation,
|
|
53
|
+
keyId,
|
|
54
|
+
clientDataHash: await requestBinding(input.challenge, /* @__PURE__ */ new Uint8Array(0)),
|
|
55
|
+
apps: input.apps,
|
|
56
|
+
allowDevelopment: developmentKeysAllowedIn(input.environment),
|
|
57
|
+
root: input.root,
|
|
58
|
+
now: input.now
|
|
59
|
+
});
|
|
60
|
+
if (!result.ok) return {
|
|
61
|
+
ok: false,
|
|
62
|
+
reason: `${result.check}: ${result.reason}`
|
|
63
|
+
};
|
|
64
|
+
if (!await storeAppAttestKey(input.db, result.key, input.now)) return {
|
|
65
|
+
ok: false,
|
|
66
|
+
reason: "keyId: this key is already registered"
|
|
67
|
+
};
|
|
68
|
+
return { ok: true };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Apple App Attest. Verifies an assertion from a registered key over the request binding: the key is known, its
|
|
72
|
+
* app is still allowed, the signature verifies, and the counter rises. Then stores the counter.
|
|
73
|
+
*/
|
|
74
|
+
const appAttestVerifier = { async verify({ presented, binding, environment, settings, db, now }) {
|
|
75
|
+
if (presented.keyId === void 0) return {
|
|
76
|
+
ok: false,
|
|
77
|
+
reason: "keyId: no App Attest key id was presented"
|
|
78
|
+
};
|
|
79
|
+
const keyId = decodeKeyId(presented.keyId);
|
|
80
|
+
if (keyId === void 0) return {
|
|
81
|
+
ok: false,
|
|
82
|
+
reason: "keyId: the key id is not 32 bytes of base64"
|
|
83
|
+
};
|
|
84
|
+
const key = await findAppAttestKey(db, keyId);
|
|
85
|
+
if (key === void 0) return {
|
|
86
|
+
ok: false,
|
|
87
|
+
reason: "key: no App Attest key with this id is registered"
|
|
88
|
+
};
|
|
89
|
+
if (!settings.ios.some((app) => appIdOf(app) === key.appId)) return {
|
|
90
|
+
ok: false,
|
|
91
|
+
reason: `rpIdHash: the key's app ${key.appId} is not allowed to attest here`
|
|
92
|
+
};
|
|
93
|
+
if (key.environment === "development" && !developmentKeysAllowedIn(environment)) return {
|
|
94
|
+
ok: false,
|
|
95
|
+
reason: "aaguid: a development key is refused here: only production keys are accepted"
|
|
96
|
+
};
|
|
97
|
+
const assertion = decodeBase64(presented.assertion);
|
|
98
|
+
if (assertion === void 0) return {
|
|
99
|
+
ok: false,
|
|
100
|
+
reason: "format: the assertion is not base64"
|
|
101
|
+
};
|
|
102
|
+
const publicKey = decodeBase64(key.publicKey);
|
|
103
|
+
const result = await verifyAppAttestAssertion({
|
|
104
|
+
assertion,
|
|
105
|
+
publicKey,
|
|
106
|
+
appId: key.appId,
|
|
107
|
+
clientDataHash: binding,
|
|
108
|
+
counter: key.counter
|
|
109
|
+
});
|
|
110
|
+
if (!result.ok) return {
|
|
111
|
+
ok: false,
|
|
112
|
+
reason: `${result.check}: ${result.reason}`
|
|
113
|
+
};
|
|
114
|
+
if (!await advanceAppAttestCounter(db, keyId, result.counter, now)) return {
|
|
115
|
+
ok: false,
|
|
116
|
+
reason: `counter: ${result.counter} was overtaken by another assertion from this key`
|
|
117
|
+
};
|
|
118
|
+
return { ok: true };
|
|
119
|
+
} };
|
|
120
|
+
//#endregion
|
|
121
|
+
export { appAttestVerifier, appIdOf, developmentKeysAllowedIn, registerAppAttestKey };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
/** The elliptic curves an App Attest chain uses: P-384 for the root and intermediate, P-256 for the key. */
|
|
4
|
+
export type Curve = "P-256" | "P-384";
|
|
5
|
+
/** An EC public key as a certificate carries it. */
|
|
6
|
+
export interface EcPublicKey {
|
|
7
|
+
curve: Curve;
|
|
8
|
+
/** The X9.62 uncompressed point: `0x04`, then X and Y. */
|
|
9
|
+
point: Uint8Array;
|
|
10
|
+
}
|
|
11
|
+
/** The parts of an X.509 certificate this verifier reads. */
|
|
12
|
+
export interface Certificate {
|
|
13
|
+
/** The DER `tbsCertificate`: what the issuer signed. */
|
|
14
|
+
tbs: Uint8Array;
|
|
15
|
+
/** The signature algorithm's hash. */
|
|
16
|
+
hash: "SHA-256" | "SHA-384";
|
|
17
|
+
/** The DER ECDSA signature. */
|
|
18
|
+
signature: Uint8Array;
|
|
19
|
+
/** The DER issuer name, compared byte for byte against the issuer's subject. */
|
|
20
|
+
issuer: Uint8Array;
|
|
21
|
+
/** The DER subject name. */
|
|
22
|
+
subject: Uint8Array;
|
|
23
|
+
notBefore: Date;
|
|
24
|
+
notAfter: Date;
|
|
25
|
+
publicKey: EcPublicKey;
|
|
26
|
+
/** Each extension's `extnValue` contents, by OID. */
|
|
27
|
+
extensions: Map<string, Uint8Array>;
|
|
28
|
+
/** Whether basic constraints mark it a CA. */
|
|
29
|
+
isCA: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** Read an X.509 certificate. Throws {@link DerError} on anything this verifier cannot read. */
|
|
32
|
+
export declare function parseCertificate(der: Uint8Array): Certificate;
|
|
33
|
+
/** A DER ECDSA signature as WebCrypto takes it: `r` and `s`, each left-padded to the curve's field size. */
|
|
34
|
+
export declare function derSignatureToRaw(signature: Uint8Array, curve: Curve): Uint8Array | undefined;
|
|
35
|
+
/** Whether `signature`, DER-encoded, is `key`'s ECDSA signature over `data` with `hash`. */
|
|
36
|
+
export declare function verifyEcdsa(key: EcPublicKey, hash: "SHA-256" | "SHA-384", signature: Uint8Array, data: Uint8Array): Promise<boolean>;
|
|
37
|
+
/** Why a chain did not verify, or that it did. */
|
|
38
|
+
export type ChainVerdict = {
|
|
39
|
+
ok: true;
|
|
40
|
+
} | {
|
|
41
|
+
ok: false;
|
|
42
|
+
reason: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Verify that `chain` (leaf first) leads to `root`: each certificate names the next as its issuer, is signed by
|
|
46
|
+
* it, and is valid at `now`, every issuer is a CA, and the root is valid at `now` too. The root is trusted as
|
|
47
|
+
* given; it is never read from the chain.
|
|
48
|
+
*/
|
|
49
|
+
export declare function verifyChain(chain: readonly Certificate[], root: Certificate, now: Date): Promise<ChainVerdict>;
|
|
50
|
+
//# sourceMappingURL=x509.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"x509.d.ts","sourceRoot":"","sources":["../../../src/attestation/appAttest/x509.ts"],"names":[],"mappings":"AAmBA,4GAA4G;AAC5G,MAAM,MAAM,KAAK,GAAG,OAAO,GAAG,OAAO,CAAC;AAEtC,oDAAoD;AACpD,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,KAAK,CAAC;IACb,0DAA0D;IAC1D,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,6DAA6D;AAC7D,MAAM,WAAW,WAAW;IAC1B,wDAAwD;IACxD,GAAG,EAAE,UAAU,CAAC;IAChB,sCAAsC;IACtC,IAAI,EAAE,SAAS,GAAG,SAAS,CAAC;IAC5B,+BAA+B;IAC/B,SAAS,EAAE,UAAU,CAAC;IACtB,gFAAgF;IAChF,MAAM,EAAE,UAAU,CAAC;IACnB,4BAA4B;IAC5B,OAAO,EAAE,UAAU,CAAC;IACpB,SAAS,EAAE,IAAI,CAAC;IAChB,QAAQ,EAAE,IAAI,CAAC;IACf,SAAS,EAAE,WAAW,CAAC;IACvB,qDAAqD;IACrD,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACpC,8CAA8C;IAC9C,IAAI,EAAE,OAAO,CAAC;CACf;AA4DD,gGAAgG;AAChG,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,GAAG,WAAW,CAyB7D;AAED,4GAA4G;AAC5G,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,GAAG,UAAU,GAAG,SAAS,CAmB7F;AAED,4FAA4F;AAC5F,wBAAsB,WAAW,CAC/B,GAAG,EAAE,WAAW,EAChB,IAAI,EAAE,SAAS,GAAG,SAAS,EAC3B,SAAS,EAAE,UAAU,EACrB,IAAI,EAAE,UAAU,GACf,OAAO,CAAC,OAAO,CAAC,CAYlB;AAED,kDAAkD;AAClD,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC,CAsBpH"}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { equalBytes } from "./bytes.js";
|
|
4
|
+
import { DerError, derChildren, derInteger, derOid, derTime, expectTag, readDer } from "./der.js";
|
|
5
|
+
//#region src/attestation/appAttest/x509.ts
|
|
6
|
+
const EC_PUBLIC_KEY = "1.2.840.10045.2.1";
|
|
7
|
+
const CURVES = {
|
|
8
|
+
"1.2.840.10045.3.1.7": "P-256",
|
|
9
|
+
"1.3.132.0.34": "P-384"
|
|
10
|
+
};
|
|
11
|
+
const SIGNATURE_HASHES = {
|
|
12
|
+
"1.2.840.10045.4.3.2": "SHA-256",
|
|
13
|
+
"1.2.840.10045.4.3.3": "SHA-384"
|
|
14
|
+
};
|
|
15
|
+
const BASIC_CONSTRAINTS = "2.5.29.19";
|
|
16
|
+
const FIELD_BYTES = {
|
|
17
|
+
"P-256": 32,
|
|
18
|
+
"P-384": 48
|
|
19
|
+
};
|
|
20
|
+
function bitStringBytes(node, what) {
|
|
21
|
+
const content = expectTag(node, 3, what).content;
|
|
22
|
+
if (content[0] !== 0) throw new DerError(`${what} has unused bits`);
|
|
23
|
+
return content.subarray(1);
|
|
24
|
+
}
|
|
25
|
+
function signatureHash(node) {
|
|
26
|
+
const [identifier] = derChildren(expectTag(node, 48, "the signature algorithm"));
|
|
27
|
+
const oid = derOid(identifier);
|
|
28
|
+
const hash = SIGNATURE_HASHES[oid];
|
|
29
|
+
if (hash === void 0) throw new DerError(`signature algorithm ${oid} is not ECDSA with SHA-256 or SHA-384`);
|
|
30
|
+
return hash;
|
|
31
|
+
}
|
|
32
|
+
function publicKey(node) {
|
|
33
|
+
const [algorithm, key] = derChildren(expectTag(node, 48, "the subject public key info"));
|
|
34
|
+
const [type, parameters] = derChildren(expectTag(algorithm, 48, "the public key algorithm"));
|
|
35
|
+
if (derOid(type) !== EC_PUBLIC_KEY) throw new DerError("the public key is not an EC key");
|
|
36
|
+
const curve = parameters === void 0 ? void 0 : CURVES[derOid(parameters)];
|
|
37
|
+
if (curve === void 0) throw new DerError("the public key is not on P-256 or P-384");
|
|
38
|
+
const point = bitStringBytes(key, "the public key");
|
|
39
|
+
if (point.length !== 1 + 2 * FIELD_BYTES[curve] || point[0] !== 4) throw new DerError("the public key is not an uncompressed point");
|
|
40
|
+
return {
|
|
41
|
+
curve,
|
|
42
|
+
point
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function extensions(node) {
|
|
46
|
+
const found = /* @__PURE__ */ new Map();
|
|
47
|
+
if (node === void 0) return found;
|
|
48
|
+
const [list] = derChildren(node);
|
|
49
|
+
for (const extension of derChildren(expectTag(list, 48, "the extensions"))) {
|
|
50
|
+
const parts = derChildren(expectTag(extension, 48, "an extension"));
|
|
51
|
+
const oid = derOid(parts[0]);
|
|
52
|
+
const value = parts[parts.length - 1];
|
|
53
|
+
if (parts.length === 3) expectTag(parts[1], 1, "an extension's critical flag");
|
|
54
|
+
if (found.has(oid)) throw new DerError(`extension ${oid} appears twice`);
|
|
55
|
+
found.set(oid, expectTag(value, 4, "an extension's value").content);
|
|
56
|
+
}
|
|
57
|
+
return found;
|
|
58
|
+
}
|
|
59
|
+
function isCA(found) {
|
|
60
|
+
const value = found.get(BASIC_CONSTRAINTS);
|
|
61
|
+
if (value === void 0) return false;
|
|
62
|
+
const [flag] = derChildren(expectTag(readDer(value), 48, "basic constraints"));
|
|
63
|
+
return flag?.tag === 1 && flag.content[0] === 255;
|
|
64
|
+
}
|
|
65
|
+
/** Read an X.509 certificate. Throws {@link DerError} on anything this verifier cannot read. */
|
|
66
|
+
function parseCertificate(der) {
|
|
67
|
+
const [tbsNode, algorithm, signature] = derChildren(expectTag(readDer(der), 48, "the certificate"));
|
|
68
|
+
const tbs = expectTag(tbsNode, 48, "the tbsCertificate");
|
|
69
|
+
const fields = derChildren(tbs);
|
|
70
|
+
const offset = fields[0]?.tag === 160 ? 1 : 0;
|
|
71
|
+
const [, innerAlgorithm, issuer, validity, subject, spki] = fields.slice(offset);
|
|
72
|
+
derInteger(fields[offset]);
|
|
73
|
+
if (innerAlgorithm === void 0 || algorithm === void 0 || !equalBytes(innerAlgorithm.raw, algorithm.raw)) throw new DerError("the certificate's two signature algorithms disagree");
|
|
74
|
+
const [notBefore, notAfter] = derChildren(expectTag(validity, 48, "the validity"));
|
|
75
|
+
const found = extensions(fields.slice(offset + 6).find((field) => field.tag === 163));
|
|
76
|
+
return {
|
|
77
|
+
tbs: tbs.raw,
|
|
78
|
+
hash: signatureHash(algorithm),
|
|
79
|
+
signature: bitStringBytes(signature, "the signature"),
|
|
80
|
+
issuer: expectTag(issuer, 48, "the issuer").raw,
|
|
81
|
+
subject: expectTag(subject, 48, "the subject").raw,
|
|
82
|
+
notBefore: derTime(notBefore),
|
|
83
|
+
notAfter: derTime(notAfter),
|
|
84
|
+
publicKey: publicKey(spki),
|
|
85
|
+
extensions: found,
|
|
86
|
+
isCA: isCA(found)
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** A DER ECDSA signature as WebCrypto takes it: `r` and `s`, each left-padded to the curve's field size. */
|
|
90
|
+
function derSignatureToRaw(signature, curve) {
|
|
91
|
+
const size = FIELD_BYTES[curve];
|
|
92
|
+
try {
|
|
93
|
+
const [r, s, extra] = derChildren(expectTag(readDer(signature), 48, "the signature"));
|
|
94
|
+
if (r === void 0 || s === void 0 || extra !== void 0) return void 0;
|
|
95
|
+
const raw = new Uint8Array(size * 2);
|
|
96
|
+
for (const [index, part] of [derInteger(r), derInteger(s)].entries()) {
|
|
97
|
+
if (part.length === 0 || part[0] & 128) return void 0;
|
|
98
|
+
let start = 0;
|
|
99
|
+
while (start < part.length - 1 && part[start] === 0) start++;
|
|
100
|
+
const digits = part.subarray(start);
|
|
101
|
+
if (digits.length > size) return void 0;
|
|
102
|
+
raw.set(digits, index * size + size - digits.length);
|
|
103
|
+
}
|
|
104
|
+
return raw;
|
|
105
|
+
} catch (cause) {
|
|
106
|
+
if (cause instanceof DerError) return void 0;
|
|
107
|
+
throw cause;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Whether `signature`, DER-encoded, is `key`'s ECDSA signature over `data` with `hash`. */
|
|
111
|
+
async function verifyEcdsa(key, hash, signature, data) {
|
|
112
|
+
const raw = derSignatureToRaw(signature, key.curve);
|
|
113
|
+
if (raw === void 0) return false;
|
|
114
|
+
let imported;
|
|
115
|
+
try {
|
|
116
|
+
imported = await crypto.subtle.importKey("raw", key.point, {
|
|
117
|
+
name: "ECDSA",
|
|
118
|
+
namedCurve: key.curve
|
|
119
|
+
}, false, ["verify"]);
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
return crypto.subtle.verify({
|
|
124
|
+
name: "ECDSA",
|
|
125
|
+
hash
|
|
126
|
+
}, imported, raw, data);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Verify that `chain` (leaf first) leads to `root`: each certificate names the next as its issuer, is signed by
|
|
130
|
+
* it, and is valid at `now`, every issuer is a CA, and the root is valid at `now` too. The root is trusted as
|
|
131
|
+
* given; it is never read from the chain.
|
|
132
|
+
*/
|
|
133
|
+
async function verifyChain(chain, root, now) {
|
|
134
|
+
if (chain.length === 0) return {
|
|
135
|
+
ok: false,
|
|
136
|
+
reason: "the chain is empty"
|
|
137
|
+
};
|
|
138
|
+
const all = [...chain, root];
|
|
139
|
+
for (const [index, cert] of all.entries()) {
|
|
140
|
+
const name = index === 0 ? "the leaf certificate" : index === all.length - 1 ? "the root" : `certificate ${index}`;
|
|
141
|
+
if (now < cert.notBefore || now > cert.notAfter) return {
|
|
142
|
+
ok: false,
|
|
143
|
+
reason: `${name} is not valid at ${now.toISOString()} (valid ${cert.notBefore.toISOString()} to ${cert.notAfter.toISOString()})`
|
|
144
|
+
};
|
|
145
|
+
const issuer = all[index + 1];
|
|
146
|
+
if (issuer === void 0) break;
|
|
147
|
+
if (!issuer.isCA) return {
|
|
148
|
+
ok: false,
|
|
149
|
+
reason: `the issuer of ${name} is not a CA`
|
|
150
|
+
};
|
|
151
|
+
if (!equalBytes(cert.issuer, issuer.subject)) return {
|
|
152
|
+
ok: false,
|
|
153
|
+
reason: `${name} names an issuer other than the next certificate`
|
|
154
|
+
};
|
|
155
|
+
if (!await verifyEcdsa(issuer.publicKey, cert.hash, cert.signature, cert.tbs)) return {
|
|
156
|
+
ok: false,
|
|
157
|
+
reason: `${name} is not signed by its issuer`
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
return { ok: true };
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
export { derSignatureToRaw, parseCertificate, verifyChain, verifyEcdsa };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import type { AuthDatabase } from "../data/tables";
|
|
4
|
+
/** A challenge as the challenge route hands it out. */
|
|
5
|
+
export interface IssuedChallenge {
|
|
6
|
+
challenge: string;
|
|
7
|
+
expiresAt: Date;
|
|
8
|
+
}
|
|
9
|
+
/** What presenting a challenge established. */
|
|
10
|
+
export type ChallengeUse = {
|
|
11
|
+
ok: true;
|
|
12
|
+
} | {
|
|
13
|
+
ok: false;
|
|
14
|
+
reason: string;
|
|
15
|
+
};
|
|
16
|
+
/** Issue a challenge good for `expiresIn` seconds from `now`, pruning every one that has already run out. */
|
|
17
|
+
export declare function issueChallenge(db: AuthDatabase, options: {
|
|
18
|
+
now: Date;
|
|
19
|
+
expiresIn: number;
|
|
20
|
+
}): Promise<IssuedChallenge>;
|
|
21
|
+
/**
|
|
22
|
+
* Spend a challenge. One `DELETE … RETURNING`, so two requests racing on one challenge cannot both find it live:
|
|
23
|
+
* the first takes the row and the second finds none. An expired challenge is spent and refused.
|
|
24
|
+
*/
|
|
25
|
+
export declare function consumeChallenge(db: AuthDatabase, challenge: string, now: Date): Promise<ChallengeUse>;
|
|
26
|
+
//# sourceMappingURL=challenge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challenge.d.ts","sourceRoot":"","sources":["../../src/attestation/challenge.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,uDAAuD;AACvD,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,+CAA+C;AAC/C,MAAM,MAAM,YAAY,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAMxE,6GAA6G;AAC7G,wBAAsB,cAAc,CAClC,EAAE,EAAE,YAAY,EAChB,OAAO,EAAE;IAAE,GAAG,EAAE,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACxC,OAAO,CAAC,eAAe,CAAC,CAY1B;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC,CAY5G"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
import { AttestationChallenge } from "../data/attestationChallenge.js";
|
|
4
|
+
import { base64UrlEncode } from "@pithy-sh/core/src/controlPlane/token/base64url";
|
|
5
|
+
import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
6
|
+
//#region src/attestation/challenge.ts
|
|
7
|
+
async function digest(challenge) {
|
|
8
|
+
return base64UrlEncode(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(challenge))));
|
|
9
|
+
}
|
|
10
|
+
/** Issue a challenge good for `expiresIn` seconds from `now`, pruning every one that has already run out. */
|
|
11
|
+
async function issueChallenge(db, options) {
|
|
12
|
+
const challenge = base64UrlEncode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
13
|
+
const expiresAt = new Date(options.now.getTime() + options.expiresIn * 1e3);
|
|
14
|
+
await db.deleteFrom("pithyAuthAttestationChallenges").where("expiresAt", "<=", SQLiteDate.encode(options.now)).execute();
|
|
15
|
+
await db.insertInto("pithyAuthAttestationChallenges").values(AttestationChallenge.encode({
|
|
16
|
+
id: await digest(challenge),
|
|
17
|
+
issuedAt: options.now,
|
|
18
|
+
expiresAt
|
|
19
|
+
})).execute();
|
|
20
|
+
return {
|
|
21
|
+
challenge,
|
|
22
|
+
expiresAt
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Spend a challenge. One `DELETE … RETURNING`, so two requests racing on one challenge cannot both find it live:
|
|
27
|
+
* the first takes the row and the second finds none. An expired challenge is spent and refused.
|
|
28
|
+
*/
|
|
29
|
+
async function consumeChallenge(db, challenge, now) {
|
|
30
|
+
const row = await db.deleteFrom("pithyAuthAttestationChallenges").where("id", "=", await digest(challenge)).returning([
|
|
31
|
+
"id",
|
|
32
|
+
"issuedAt",
|
|
33
|
+
"expiresAt"
|
|
34
|
+
]).executeTakeFirst();
|
|
35
|
+
if (row === void 0) return {
|
|
36
|
+
ok: false,
|
|
37
|
+
reason: "the challenge was already used or never issued"
|
|
38
|
+
};
|
|
39
|
+
const { expiresAt } = AttestationChallenge.parse(row);
|
|
40
|
+
if (expiresAt.getTime() <= now.getTime()) return {
|
|
41
|
+
ok: false,
|
|
42
|
+
reason: `the challenge expired at ${expiresAt.toISOString()}`
|
|
43
|
+
};
|
|
44
|
+
return { ok: true };
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
export { consumeChallenge, issueChallenge };
|