@freedomofpress/sigstore-browser 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/.github/workflows/conformance.yml +29 -0
  2. package/.github/workflows/publish.yml +45 -0
  3. package/README.md +10 -0
  4. package/dist/asn1/error.d.ts +5 -0
  5. package/dist/asn1/error.d.ts.map +1 -0
  6. package/dist/asn1/error.js +20 -0
  7. package/dist/asn1/error.js.map +1 -0
  8. package/dist/asn1/index.d.ts +2 -0
  9. package/dist/asn1/index.d.ts.map +1 -0
  10. package/dist/asn1/index.js +17 -0
  11. package/dist/asn1/index.js.map +1 -0
  12. package/dist/asn1/length.d.ts +4 -0
  13. package/dist/asn1/length.d.ts.map +1 -0
  14. package/dist/asn1/length.js +59 -0
  15. package/dist/asn1/length.js.map +1 -0
  16. package/dist/asn1/obj.d.ts +15 -0
  17. package/dist/asn1/obj.d.ts.map +1 -0
  18. package/dist/asn1/obj.js +153 -0
  19. package/dist/asn1/obj.js.map +1 -0
  20. package/dist/asn1/parse.d.ts +7 -0
  21. package/dist/asn1/parse.d.ts.map +1 -0
  22. package/dist/asn1/parse.js +118 -0
  23. package/dist/asn1/parse.js.map +1 -0
  24. package/dist/asn1/tag.d.ts +17 -0
  25. package/dist/asn1/tag.d.ts.map +1 -0
  26. package/dist/asn1/tag.js +86 -0
  27. package/dist/asn1/tag.js.map +1 -0
  28. package/dist/bundle.d.ts +87 -0
  29. package/dist/bundle.d.ts.map +1 -0
  30. package/dist/bundle.js +2 -0
  31. package/dist/bundle.js.map +1 -0
  32. package/dist/canonicalize.d.ts +2 -0
  33. package/dist/canonicalize.d.ts.map +1 -0
  34. package/dist/canonicalize.js +64 -0
  35. package/dist/canonicalize.js.map +1 -0
  36. package/dist/cli.d.ts +3 -0
  37. package/dist/cli.d.ts.map +1 -0
  38. package/dist/cli.js +217 -0
  39. package/dist/cli.js.map +1 -0
  40. package/dist/crypto.d.ts +5 -0
  41. package/dist/crypto.d.ts.map +1 -0
  42. package/dist/crypto.js +260 -0
  43. package/dist/crypto.js.map +1 -0
  44. package/dist/dsse.d.ts +2 -0
  45. package/dist/dsse.d.ts.map +1 -0
  46. package/dist/dsse.js +42 -0
  47. package/dist/dsse.js.map +1 -0
  48. package/dist/encoding.d.ts +17 -0
  49. package/dist/encoding.d.ts.map +1 -0
  50. package/dist/encoding.js +112 -0
  51. package/dist/encoding.js.map +1 -0
  52. package/dist/errors.d.ts +39 -0
  53. package/dist/errors.d.ts.map +1 -0
  54. package/dist/errors.js +79 -0
  55. package/dist/errors.js.map +1 -0
  56. package/dist/index.d.ts +8 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +5 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/interfaces.d.ts +104 -0
  61. package/dist/interfaces.d.ts.map +1 -0
  62. package/dist/interfaces.js +26 -0
  63. package/dist/interfaces.js.map +1 -0
  64. package/dist/oid.d.ts +5 -0
  65. package/dist/oid.d.ts.map +1 -0
  66. package/dist/oid.js +25 -0
  67. package/dist/oid.js.map +1 -0
  68. package/dist/pem.d.ts +3 -0
  69. package/dist/pem.d.ts.map +1 -0
  70. package/dist/pem.js +41 -0
  71. package/dist/pem.js.map +1 -0
  72. package/dist/rfc3161/error.d.ts +3 -0
  73. package/dist/rfc3161/error.d.ts.map +1 -0
  74. package/dist/rfc3161/error.js +18 -0
  75. package/dist/rfc3161/error.js.map +1 -0
  76. package/dist/rfc3161/index.d.ts +2 -0
  77. package/dist/rfc3161/index.d.ts.map +1 -0
  78. package/dist/rfc3161/index.js +17 -0
  79. package/dist/rfc3161/index.js.map +1 -0
  80. package/dist/rfc3161/timestamp.d.ts +36 -0
  81. package/dist/rfc3161/timestamp.d.ts.map +1 -0
  82. package/dist/rfc3161/timestamp.js +203 -0
  83. package/dist/rfc3161/timestamp.js.map +1 -0
  84. package/dist/rfc3161/tstinfo.d.ts +13 -0
  85. package/dist/rfc3161/tstinfo.d.ts.map +1 -0
  86. package/dist/rfc3161/tstinfo.js +47 -0
  87. package/dist/rfc3161/tstinfo.js.map +1 -0
  88. package/dist/sigstore.d.ts +33 -0
  89. package/dist/sigstore.d.ts.map +1 -0
  90. package/dist/sigstore.js +531 -0
  91. package/dist/sigstore.js.map +1 -0
  92. package/dist/stream.d.ts +22 -0
  93. package/dist/stream.d.ts.map +1 -0
  94. package/dist/stream.js +114 -0
  95. package/dist/stream.js.map +1 -0
  96. package/dist/timestamp/tsa.d.ts +24 -0
  97. package/dist/timestamp/tsa.d.ts.map +1 -0
  98. package/dist/timestamp/tsa.js +150 -0
  99. package/dist/timestamp/tsa.js.map +1 -0
  100. package/dist/tlog/body.d.ts +8 -0
  101. package/dist/tlog/body.d.ts.map +1 -0
  102. package/dist/tlog/body.js +45 -0
  103. package/dist/tlog/body.js.map +1 -0
  104. package/dist/tlog/checkpoint.d.ts +23 -0
  105. package/dist/tlog/checkpoint.d.ts.map +1 -0
  106. package/dist/tlog/checkpoint.js +187 -0
  107. package/dist/tlog/checkpoint.js.map +1 -0
  108. package/dist/tlog/dsse.d.ts +4 -0
  109. package/dist/tlog/dsse.d.ts.map +1 -0
  110. package/dist/tlog/dsse.js +85 -0
  111. package/dist/tlog/dsse.js.map +1 -0
  112. package/dist/tlog/hashedrekord.d.ts +4 -0
  113. package/dist/tlog/hashedrekord.d.ts.map +1 -0
  114. package/dist/tlog/hashedrekord.js +63 -0
  115. package/dist/tlog/hashedrekord.js.map +1 -0
  116. package/dist/tlog/intoto.d.ts +4 -0
  117. package/dist/tlog/intoto.d.ts.map +1 -0
  118. package/dist/tlog/intoto.js +50 -0
  119. package/dist/tlog/intoto.js.map +1 -0
  120. package/dist/tlog/merkle.d.ts +3 -0
  121. package/dist/tlog/merkle.d.ts.map +1 -0
  122. package/dist/tlog/merkle.js +112 -0
  123. package/dist/tlog/merkle.js.map +1 -0
  124. package/dist/trust/tuf-root.json +1 -0
  125. package/dist/trust/tuf.d.ts +95 -0
  126. package/dist/trust/tuf.d.ts.map +1 -0
  127. package/dist/trust/tuf.js +150 -0
  128. package/dist/trust/tuf.js.map +1 -0
  129. package/dist/x509/cert.d.ts +52 -0
  130. package/dist/x509/cert.d.ts.map +1 -0
  131. package/dist/x509/cert.js +256 -0
  132. package/dist/x509/cert.js.map +1 -0
  133. package/dist/x509/chain.d.ts +20 -0
  134. package/dist/x509/chain.d.ts.map +1 -0
  135. package/dist/x509/chain.js +141 -0
  136. package/dist/x509/chain.js.map +1 -0
  137. package/dist/x509/ext.d.ts +48 -0
  138. package/dist/x509/ext.d.ts.map +1 -0
  139. package/dist/x509/ext.js +164 -0
  140. package/dist/x509/ext.js.map +1 -0
  141. package/dist/x509/index.d.ts +4 -0
  142. package/dist/x509/index.d.ts.map +1 -0
  143. package/dist/x509/index.js +19 -0
  144. package/dist/x509/index.js.map +1 -0
  145. package/dist/x509/sct.d.ts +25 -0
  146. package/dist/x509/sct.d.ts.map +1 -0
  147. package/dist/x509/sct.js +123 -0
  148. package/dist/x509/sct.js.map +1 -0
  149. package/eslint.config.mjs +31 -0
  150. package/package.json +39 -0
  151. package/src/asn1/error.ts +18 -0
  152. package/src/asn1/index.ts +16 -0
  153. package/src/asn1/length.ts +71 -0
  154. package/src/asn1/obj.ts +184 -0
  155. package/src/asn1/parse.ts +146 -0
  156. package/src/asn1/tag.ts +105 -0
  157. package/src/bundle.ts +99 -0
  158. package/src/canonicalize.ts +61 -0
  159. package/src/cli.ts +285 -0
  160. package/src/crypto.ts +310 -0
  161. package/src/dsse.ts +49 -0
  162. package/src/encoding.ts +141 -0
  163. package/src/errors.ts +82 -0
  164. package/src/index.browser.test.ts +219 -0
  165. package/src/index.ts +14 -0
  166. package/src/interfaces.ts +118 -0
  167. package/src/oid.ts +28 -0
  168. package/src/pem.ts +48 -0
  169. package/src/rfc3161/error.ts +16 -0
  170. package/src/rfc3161/index.ts +17 -0
  171. package/src/rfc3161/timestamp.ts +270 -0
  172. package/src/rfc3161/tstinfo.ts +80 -0
  173. package/src/sigstore.ts +728 -0
  174. package/src/stream.ts +141 -0
  175. package/src/timestamp/tsa.ts +205 -0
  176. package/src/tlog/body.ts +65 -0
  177. package/src/tlog/checkpoint.ts +248 -0
  178. package/src/tlog/dsse.ts +147 -0
  179. package/src/tlog/hashedrekord.ts +130 -0
  180. package/src/tlog/intoto.ts +102 -0
  181. package/src/tlog/merkle.ts +152 -0
  182. package/src/trust/README.md +38 -0
  183. package/src/trust/tuf-root.json +1 -0
  184. package/src/trust/tuf.ts +223 -0
  185. package/src/types/tuf-browser.d.ts +13 -0
  186. package/src/x509/cert.ts +319 -0
  187. package/src/x509/chain.ts +212 -0
  188. package/src/x509/ext.ts +212 -0
  189. package/src/x509/index.ts +19 -0
  190. package/src/x509/sct.ts +154 -0
  191. package/tsconfig.json +18 -0
  192. package/vite.config.playwright.ts +26 -0
  193. package/vite.config.ts +18 -0
package/src/stream.ts ADDED
@@ -0,0 +1,141 @@
1
+ /*
2
+ Copyright 2023 The Sigstore Authors.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+ class StreamError extends Error {}
17
+
18
+ export class ByteStream {
19
+ private static BLOCK_SIZE = 1024;
20
+
21
+ private buf: ArrayBuffer;
22
+ private view: Uint8Array;
23
+ private start = 0;
24
+
25
+ constructor(buffer?: ArrayBuffer) {
26
+ if (buffer) {
27
+ this.buf = buffer;
28
+ this.view = new Uint8Array(buffer);
29
+ } else {
30
+ this.buf = new ArrayBuffer(0);
31
+ this.view = new Uint8Array(this.buf);
32
+ }
33
+ }
34
+
35
+ get buffer(): Uint8Array {
36
+ return this.view.subarray(0, this.start);
37
+ }
38
+
39
+ get length(): number {
40
+ return this.view.byteLength;
41
+ }
42
+
43
+ get position(): number {
44
+ return this.start;
45
+ }
46
+
47
+ public seek(position: number) {
48
+ this.start = position;
49
+ }
50
+
51
+ // Returns a Buffer containing the specified number of bytes starting at the
52
+ // given start position.
53
+ public slice(start: number, len: number): Uint8Array {
54
+ const end = start + len;
55
+
56
+ if (end > this.length) {
57
+ throw new StreamError("request past end of buffer");
58
+ }
59
+
60
+ return this.view.subarray(start, end);
61
+ }
62
+
63
+ public appendChar(char: number) {
64
+ this.ensureCapacity(1);
65
+ this.view[this.start] = char;
66
+ this.start += 1;
67
+ }
68
+
69
+ public appendUint16(num: number) {
70
+ this.ensureCapacity(2);
71
+
72
+ const value = new Uint16Array([num]);
73
+ const view = new Uint8Array(value.buffer);
74
+
75
+ this.view[this.start] = view[1];
76
+ this.view[this.start + 1] = view[0];
77
+ this.start += 2;
78
+ }
79
+
80
+ public appendUint24(num: number) {
81
+ this.ensureCapacity(3);
82
+
83
+ const value = new Uint32Array([num]);
84
+ const view = new Uint8Array(value.buffer);
85
+
86
+ this.view[this.start] = view[2];
87
+ this.view[this.start + 1] = view[1];
88
+ this.view[this.start + 2] = view[0];
89
+ this.start += 3;
90
+ }
91
+
92
+ public appendView(view: Uint8Array) {
93
+ this.ensureCapacity(view.length);
94
+ this.view.set(view, this.start);
95
+ this.start += view.length;
96
+ }
97
+
98
+ public getBlock(size: number): Uint8Array {
99
+ if (size <= 0) {
100
+ return new Uint8Array(0);
101
+ }
102
+
103
+ if (this.start + size > this.view.length) {
104
+ throw new Error("request past end of buffer");
105
+ }
106
+
107
+ const result = this.view.subarray(this.start, this.start + size);
108
+ this.start += size;
109
+
110
+ return result;
111
+ }
112
+
113
+ public getUint8(): number {
114
+ return this.getBlock(1)[0];
115
+ }
116
+
117
+ public getUint16(): number {
118
+ const block = this.getBlock(2);
119
+
120
+ return (block[0] << 8) | block[1];
121
+ }
122
+
123
+ private ensureCapacity(size: number) {
124
+ if (this.start + size > this.view.byteLength) {
125
+ const blockSize =
126
+ ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0);
127
+ this.realloc(this.view.byteLength + blockSize);
128
+ }
129
+ }
130
+
131
+ private realloc(size: number) {
132
+ const newArray = new ArrayBuffer(size);
133
+ const newView = new Uint8Array(newArray);
134
+
135
+ // Copy the old buffer into the new one
136
+ newView.set(this.view);
137
+
138
+ this.buf = newArray;
139
+ this.view = newView;
140
+ }
141
+ }
@@ -0,0 +1,205 @@
1
+ /*
2
+ * TSA (Time-Stamping Authority) timestamp verification
3
+ *
4
+ * Based on sigstore-js:
5
+ * https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/timestamp/tsa.ts
6
+ *
7
+ * Key differences from sigstore-js:
8
+ * - Browser-compatible: uses Uint8Array instead of Buffer for binary data
9
+ * - Uses Web Crypto API for all cryptographic operations
10
+ * - Integrates with existing RFC3161 timestamp implementation
11
+ * - Uses CertificateChainVerifier for full X.509 path validation
12
+ * - Implements filterCertAuthorities inline (from sigstore-js/packages/verify/src/trust/filter.ts)
13
+ * - Adds verifyBundleTimestamp for Sigstore bundle integration (new functionality)
14
+ */
15
+
16
+ import { RFC3161Timestamp } from "../rfc3161/index.js";
17
+ import { X509Certificate, CertificateChainVerifier } from "../x509/index.js";
18
+ import { bufferEqual } from "../crypto.js";
19
+ import { base64ToUint8Array, Uint8ArrayToHex } from "../encoding.js";
20
+ import type { RawTimestampAuthority } from "../interfaces.js";
21
+
22
+ /**
23
+ * Verifies an RFC3161 timestamp against a set of timestamp authorities
24
+ *
25
+ * @param timestamp - The RFC3161 timestamp to verify
26
+ * @param data - The data that was timestamped
27
+ * @param timestampAuthorities - List of trusted timestamp authorities
28
+ * @returns The verified signing time
29
+ * @throws Error if timestamp cannot be verified
30
+ */
31
+ export async function verifyRFC3161Timestamp(
32
+ timestamp: RFC3161Timestamp,
33
+ data: Uint8Array,
34
+ timestampAuthorities: RawTimestampAuthority[]
35
+ ): Promise<Date> {
36
+ const signingTime = timestamp.signingTime;
37
+
38
+ // Filter for CAs which were valid at the time of signing
39
+ let validAuthorities = filterCertAuthorities(
40
+ timestampAuthorities,
41
+ signingTime
42
+ );
43
+
44
+ // Filter for CAs which match serial and issuer embedded in the timestamp
45
+ validAuthorities = filterCAsBySerialAndIssuer(validAuthorities, {
46
+ serialNumber: timestamp.signerSerialNumber,
47
+ issuer: timestamp.signerIssuer,
48
+ });
49
+
50
+ // Check that we can verify the timestamp with AT LEAST ONE of the remaining CAs
51
+ const verificationResults = await Promise.allSettled(
52
+ validAuthorities.map(ca => verifyTimestampForCA(timestamp, data, ca))
53
+ );
54
+
55
+ const verified = verificationResults.some(
56
+ result => result.status === "fulfilled"
57
+ );
58
+
59
+ if (!verified) {
60
+ const errors = verificationResults
61
+ .filter(r => r.status === "rejected")
62
+ .map(r => (r as PromiseRejectedResult).reason?.message || 'Unknown error');
63
+ throw new Error(`Timestamp could not be verified against any trusted authority. Errors: ${errors.join(', ')}`);
64
+ }
65
+
66
+ return signingTime;
67
+ }
68
+
69
+ /**
70
+ * Filters certificate authorities to those valid at a specific time
71
+ *
72
+ * Adapted from sigstore-js/packages/verify/src/trust/filter.ts
73
+ */
74
+ function filterCertAuthorities(
75
+ authorities: RawTimestampAuthority[],
76
+ validAt: Date
77
+ ): RawTimestampAuthority[] {
78
+ return authorities.filter(ca => {
79
+ if (ca.validFor) {
80
+ const start = ca.validFor.start ? new Date(ca.validFor.start) : null;
81
+ const end = ca.validFor.end ? new Date(ca.validFor.end) : null;
82
+
83
+ if (start && validAt < start) {
84
+ return false;
85
+ }
86
+ if (end && validAt > end) {
87
+ return false;
88
+ }
89
+ }
90
+ return true;
91
+ });
92
+ }
93
+
94
+ /**
95
+ * Filters certificate authorities by serial number and issuer
96
+ *
97
+ * Only checks the LEAF certificate (TSA signing cert), not the entire chain.
98
+ * This matches the sigstore-js reference implementation.
99
+ */
100
+ function filterCAsBySerialAndIssuer(
101
+ timestampAuthorities: RawTimestampAuthority[],
102
+ criteria: { serialNumber: Uint8Array; issuer: Uint8Array }
103
+ ): RawTimestampAuthority[] {
104
+ return timestampAuthorities.filter(ca => {
105
+ if (!ca.certChain || ca.certChain.certificates.length === 0) {
106
+ return false;
107
+ }
108
+
109
+ const leafCert = X509Certificate.parse(
110
+ base64ToUint8Array(ca.certChain.certificates[0].rawBytes)
111
+ );
112
+
113
+ return bufferEqual(leafCert.serialNumber, criteria.serialNumber) &&
114
+ bufferEqual(leafCert.issuer, criteria.issuer);
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Verifies a timestamp against a specific certificate authority
120
+ */
121
+ async function verifyTimestampForCA(
122
+ timestamp: RFC3161Timestamp,
123
+ data: Uint8Array,
124
+ ca: RawTimestampAuthority
125
+ ): Promise<void> {
126
+ if (!ca.certChain || ca.certChain.certificates.length === 0) {
127
+ throw new Error("Certificate authority missing certificate chain");
128
+ }
129
+
130
+ const leafCert = X509Certificate.parse(
131
+ base64ToUint8Array(ca.certChain.certificates[0].rawBytes)
132
+ );
133
+ const signingTime = timestamp.signingTime;
134
+
135
+ const trustedCerts = ca.certChain.certificates
136
+ .slice(1)
137
+ .map(cert => X509Certificate.parse(base64ToUint8Array(cert.rawBytes)));
138
+
139
+ try {
140
+ const verifier = new CertificateChainVerifier({
141
+ untrustedCert: leafCert,
142
+ trustedCerts: trustedCerts,
143
+ timestamp: signingTime,
144
+ });
145
+ await verifier.verify();
146
+ } catch (e) {
147
+ throw new Error(`TSA certificate chain verification failed: ${e instanceof Error ? e.message : String(e)}`);
148
+ }
149
+
150
+ const publicKey = await leafCert.publicKeyObj;
151
+
152
+ await timestamp.verify(data, publicKey);
153
+ }
154
+
155
+ /**
156
+ * Extracts the verified timestamp from a bundle's timestamp verification data
157
+ *
158
+ * New functionality for Sigstore bundle integration (not in sigstore-js reference)
159
+ *
160
+ * @param timestampData - The timestamp verification data from the bundle
161
+ * @param signature - The signature being verified
162
+ * @param timestampAuthorities - List of trusted timestamp authorities
163
+ * @returns The verified signing time, or undefined if no timestamp
164
+ */
165
+ export async function verifyBundleTimestamp(
166
+ timestampData: any,
167
+ signature: Uint8Array,
168
+ timestampAuthorities: RawTimestampAuthority[]
169
+ ): Promise<Date | undefined> {
170
+ if (!timestampData?.rfc3161Timestamps?.length) {
171
+ return undefined;
172
+ }
173
+
174
+ // Check for duplicate timestamps
175
+ const seenTimestamps = new Set<string>();
176
+ for (const tsData of timestampData.rfc3161Timestamps) {
177
+ if (seenTimestamps.has(tsData.signedTimestamp)) {
178
+ throw new Error("Duplicate TSA timestamp detected");
179
+ }
180
+ seenTimestamps.add(tsData.signedTimestamp);
181
+ }
182
+
183
+ // Process each RFC3161 timestamp
184
+ const errors: string[] = [];
185
+ for (const tsData of timestampData.rfc3161Timestamps) {
186
+ try {
187
+ // Decode the base64-encoded timestamp
188
+ const timestampBytes = base64ToUint8Array(tsData.signedTimestamp);
189
+ const timestamp = RFC3161Timestamp.parse(timestampBytes);
190
+
191
+ const signingTime = await verifyRFC3161Timestamp(
192
+ timestamp,
193
+ signature,
194
+ timestampAuthorities
195
+ );
196
+ return signingTime;
197
+ } catch (e) {
198
+ // Continue to next timestamp if this one fails
199
+ errors.push(e instanceof Error ? e.message : String(e));
200
+ continue;
201
+ }
202
+ }
203
+
204
+ throw new Error(`No valid RFC3161 timestamps found. Errors: ${errors.join(', ')}`);
205
+ }
@@ -0,0 +1,65 @@
1
+ /*
2
+ * Transparency log body verification
3
+ *
4
+ * Based on sigstore-js:
5
+ * https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/tlog/index.ts
6
+ *
7
+ * Key differences from sigstore-js:
8
+ * - Browser-compatible: uses Uint8Array instead of Buffer for binary data
9
+ * - Direct bundle comparison instead of SignatureContent abstraction
10
+ */
11
+
12
+ import { base64Decode } from "../encoding.js";
13
+ import type { SigstoreBundle, TLogEntry } from "../bundle.js";
14
+ import { verifyHashedRekordBody } from "./hashedrekord.js";
15
+ import { verifyDSSEBody } from "./dsse.js";
16
+ import { verifyIntotoBody } from "./intoto.js";
17
+
18
+ export interface RekorEntry {
19
+ apiVersion: string;
20
+ kind: string;
21
+ spec: unknown;
22
+ }
23
+
24
+ export async function verifyTLogBody(
25
+ entry: TLogEntry,
26
+ bundle: SigstoreBundle
27
+ ): Promise<void> {
28
+ const rekorEntry = parseCanonicalBody(entry);
29
+
30
+ const { kind, version } = entry.kindVersion;
31
+
32
+ if (kind !== rekorEntry.kind || version !== rekorEntry.apiVersion) {
33
+ throw new Error(
34
+ `kind/version mismatch - expected: ${kind}/${version}, received: ${rekorEntry.kind}/${rekorEntry.apiVersion}`
35
+ );
36
+ }
37
+
38
+ switch (rekorEntry.kind) {
39
+ case "hashedrekord":
40
+ return verifyHashedRekordBody(rekorEntry, bundle);
41
+ case "dsse":
42
+ return verifyDSSEBody(rekorEntry, bundle);
43
+ case "intoto":
44
+ return verifyIntotoBody(rekorEntry, bundle);
45
+ default:
46
+ throw new Error(`Unsupported TLog entry kind: ${rekorEntry.kind}`);
47
+ }
48
+ }
49
+
50
+ function parseCanonicalBody(entry: TLogEntry): RekorEntry {
51
+ try {
52
+ const decodedBody = base64Decode(entry.canonicalizedBody);
53
+ const rekorEntry = JSON.parse(decodedBody) as RekorEntry;
54
+
55
+ if (!rekorEntry.apiVersion || !rekorEntry.kind || !rekorEntry.spec) {
56
+ throw new Error("Invalid Rekor entry structure");
57
+ }
58
+
59
+ return rekorEntry;
60
+ } catch (error) {
61
+ throw new Error(
62
+ `Failed to parse canonicalized body: ${error instanceof Error ? error.message : String(error)}`
63
+ );
64
+ }
65
+ }
@@ -0,0 +1,248 @@
1
+ /*
2
+ Checkpoint verification for transparency log entries.
3
+
4
+ Adapted from sigstore-js for browser compatibility:
5
+ https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/timestamp/checkpoint.ts
6
+
7
+ Key differences:
8
+ - Uses Uint8Array instead of Buffer
9
+ - Uses Web Crypto API instead of Node.js crypto module
10
+ - Manual handling of ED25519 (raw) vs ECDSA (DER) signature formats
11
+ - Inline key import from raw bytes
12
+
13
+ Additional functionality not in reference:
14
+ - filterTLogsByDate() - inlined from sigstore-js/packages/verify/src/trust/filter.ts
15
+ - importTLogKey() - new browser-compatible key import with multiple format support
16
+ - Special handling for Rekor v2 bundles without integratedTime
17
+
18
+ Follows the signed note format specification:
19
+ https://github.com/transparency-dev/formats/blob/main/log/README.md
20
+ */
21
+
22
+ import { base64ToUint8Array, stringToUint8Array, toArrayBuffer, uint8ArrayEqual, Uint8ArrayToHex } from "../encoding.js";
23
+ import { importKey, verifySignature } from "../crypto.js";
24
+ import type { TLogEntry } from "../bundle.js";
25
+ import type { RawLogs } from "../interfaces.js";
26
+
27
+ // Signed note format per https://github.com/transparency-dev/formats
28
+ // Body is separated from signatures by a blank line
29
+ const CHECKPOINT_SEPARATOR = "\n\n";
30
+ // Signature lines format: "— <identity> <base64(key_hint+signature)>\n"
31
+ // \u2014 is the em-dash character (—)
32
+ const SIGNATURE_REGEX = /\u2014 (\S+) (\S+)\n/g;
33
+
34
+ export interface TLogSignature {
35
+ name: string;
36
+ keyHint: Uint8Array;
37
+ signature: Uint8Array;
38
+ }
39
+
40
+ // Signed checkpoint note with cryptographic signatures
41
+ export class SignedNote {
42
+ readonly note: string;
43
+ readonly signatures: TLogSignature[];
44
+
45
+ constructor(note: string, signatures: TLogSignature[]) {
46
+ this.note = note;
47
+ this.signatures = signatures;
48
+ }
49
+
50
+ static fromString(envelope: string): SignedNote {
51
+ if (!envelope.includes(CHECKPOINT_SEPARATOR)) {
52
+ throw new Error("Missing checkpoint separator");
53
+ }
54
+
55
+ // Split body from signature lines at blank line
56
+ const split = envelope.indexOf(CHECKPOINT_SEPARATOR);
57
+ const header = envelope.slice(0, split + 1);
58
+ const data = envelope.slice(split + CHECKPOINT_SEPARATOR.length);
59
+
60
+ // Parse signature lines: "— <identity> <base64(key_hint+signature)>\n"
61
+ const matches = data.matchAll(SIGNATURE_REGEX);
62
+
63
+ const signatures: TLogSignature[] = [];
64
+ for (const match of matches) {
65
+ const [, name, signature] = match;
66
+ const sigBytes = base64ToUint8Array(signature);
67
+
68
+ // First 4 bytes are key hint (SHA256 hash prefix), rest is signature
69
+ if (sigBytes.length < 5) {
70
+ throw new Error("Malformed checkpoint signature");
71
+ }
72
+
73
+ signatures.push({
74
+ name,
75
+ keyHint: sigBytes.subarray(0, 4),
76
+ signature: sigBytes.subarray(4),
77
+ });
78
+ }
79
+
80
+ if (signatures.length === 0) {
81
+ throw new Error("No signatures found in checkpoint");
82
+ }
83
+
84
+ return new SignedNote(header, signatures);
85
+ }
86
+ }
87
+
88
+ // Parsed checkpoint containing tree state (origin, size, root hash)
89
+ export class LogCheckpoint {
90
+ readonly origin: string;
91
+ readonly logSize: bigint;
92
+ readonly logHash: Uint8Array;
93
+ readonly rest: string[];
94
+
95
+ constructor(
96
+ origin: string,
97
+ logSize: bigint,
98
+ logHash: Uint8Array,
99
+ rest: string[]
100
+ ) {
101
+ this.origin = origin;
102
+ this.logSize = logSize;
103
+ this.logHash = logHash;
104
+ this.rest = rest;
105
+ }
106
+
107
+ static fromString(note: string): LogCheckpoint {
108
+ const lines = note.trimEnd().split("\n");
109
+
110
+ if (lines.length < 3) {
111
+ throw new Error("Too few lines in checkpoint header");
112
+ }
113
+
114
+ const origin = lines[0];
115
+ const logSize = BigInt(lines[1]);
116
+ const rootHash = base64ToUint8Array(lines[2]);
117
+ const rest = lines.slice(3);
118
+
119
+ return new LogCheckpoint(origin, logSize, rootHash, rest);
120
+ }
121
+ }
122
+
123
+ // Verifies checkpoint signature and ensures root hash matches inclusion proof
124
+ export async function verifyCheckpoint(
125
+ entry: TLogEntry,
126
+ tlogs: RawLogs
127
+ ): Promise<void> {
128
+ if (!entry.inclusionProof?.checkpoint) {
129
+ throw new Error("Missing checkpoint in inclusion proof");
130
+ }
131
+
132
+ // Filter by log ID first (matches entry's log ID)
133
+ const entryLogId = base64ToUint8Array(entry.logId.keyId);
134
+ const matchingTLogs = tlogs.filter((tlog) => {
135
+ const tlogId = base64ToUint8Array(tlog.logId.keyId);
136
+ return uint8ArrayEqual(tlogId, entryLogId);
137
+ });
138
+
139
+ // Then filter by date if integratedTime is available
140
+ // For Rekor v2 bundles, integratedTime may be null, so we skip date filtering
141
+ const validTLogs = entry.integratedTime
142
+ ? filterTLogsByDate(matchingTLogs, new Date(Number(entry.integratedTime) * 1000))
143
+ : matchingTLogs;
144
+
145
+ const inclusionProof = entry.inclusionProof;
146
+ const signedNote = SignedNote.fromString(inclusionProof.checkpoint.envelope);
147
+ const checkpoint = LogCheckpoint.fromString(signedNote.note);
148
+
149
+ if (!(await verifySignedNote(signedNote, validTLogs))) {
150
+ throw new Error("Invalid checkpoint signature");
151
+ }
152
+
153
+ const rootHash = base64ToUint8Array(inclusionProof.rootHash);
154
+ if (!uint8ArrayEqual(checkpoint.logHash, rootHash)) {
155
+ throw new Error("Root hash mismatch between checkpoint and inclusion proof");
156
+ }
157
+ }
158
+
159
+ // Verifies checkpoint signatures using trusted TLog keys
160
+ async function verifySignedNote(
161
+ signedNote: SignedNote,
162
+ tlogs: RawLogs
163
+ ): Promise<boolean> {
164
+ const data = stringToUint8Array(signedNote.note);
165
+
166
+ // We need at least one valid signature from a known TLog
167
+ let hasValidSignature = false;
168
+
169
+ for (const signature of signedNote.signatures) {
170
+ // Match signature to TLog using key hint (first 4 bytes of key ID)
171
+ const tlog = tlogs.find((tlog) => {
172
+ const logId = base64ToUint8Array(tlog.logId.keyId);
173
+ return uint8ArrayEqual(logId.subarray(0, 4), signature.keyHint);
174
+ });
175
+
176
+ if (!tlog) {
177
+ // Skip unknown signatures (e.g., from witnesses we don't know about)
178
+ continue;
179
+ }
180
+
181
+ const publicKey = await importTLogKey(tlog);
182
+
183
+ // Both ED25519 and ECDSA verification are now handled by verifySignature
184
+ // ED25519 signatures are raw (64 bytes), ECDSA signatures are DER-encoded
185
+ const verified = await verifySignature(
186
+ publicKey,
187
+ data,
188
+ signature.signature,
189
+ tlog.hashAlgorithm
190
+ );
191
+
192
+ if (verified) {
193
+ hasValidSignature = true;
194
+ }
195
+ }
196
+
197
+ return hasValidSignature;
198
+ }
199
+
200
+
201
+ // Inlined from sigstore-js/packages/verify/src/trust/filter.ts
202
+ function filterTLogsByDate(tlogs: RawLogs, targetDate: Date): RawLogs {
203
+ return tlogs.filter((tlog) => {
204
+ const start = new Date(tlog.publicKey.validFor.start);
205
+ const end = tlog.publicKey.validFor.end
206
+ ? new Date(tlog.publicKey.validFor.end)
207
+ : null;
208
+
209
+ return targetDate >= start && (!end || targetDate <= end);
210
+ });
211
+ }
212
+
213
+ // Browser-compatible key import supporting multiple formats (not in sigstore-js reference)
214
+ async function importTLogKey(tlog: RawLogs[0]): Promise<CryptoKey> {
215
+ // Parse keyDetails to extract key type and scheme
216
+ // Formats can be:
217
+ // - "PKIX_ECDSA_P256_SHA_256" (production format)
218
+ // - "PKIX_ED25519"
219
+ // - "ecdsa-sha2-nistp256" (SSH/test format)
220
+ const keyDetails = tlog.publicKey.keyDetails;
221
+ let keyType: string;
222
+ let scheme: string;
223
+
224
+ if (keyDetails === "ecdsa-sha2-nistp256") {
225
+ // SSH-style ECDSA P-256 format used in tests
226
+ keyType = "ecdsa";
227
+ scheme = "P256-SHA256";
228
+ } else if (keyDetails.includes("ECDSA")) {
229
+ keyType = "ecdsa";
230
+ // Extract the curve and hash, e.g., "P256_SHA_256" from "PKIX_ECDSA_P256_SHA_256"
231
+ scheme = keyDetails.replace("PKIX_ECDSA_", "").replaceAll("_", "-");
232
+ } else if (keyDetails.includes("ED25519")) {
233
+ keyType = "ed25519";
234
+ scheme = "ed25519";
235
+ } else if (keyDetails.includes("RSA")) {
236
+ keyType = "rsa";
237
+ // Extract RSA details, e.g., "PSS_SHA_256" from "PKIX_RSA_PSS_SHA_256"
238
+ scheme = keyDetails.replace("PKIX_RSA_", "").replaceAll("_", "-");
239
+ } else {
240
+ throw new Error(`Unsupported key type in keyDetails: ${keyDetails}`);
241
+ }
242
+
243
+ return importKey(
244
+ keyType,
245
+ scheme,
246
+ tlog.publicKey.rawBytes
247
+ );
248
+ }