@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
@@ -0,0 +1,728 @@
1
+ import { SigstoreBundle } from "./bundle.js";
2
+ import { canonicalize } from "./canonicalize.js";
3
+ import { importKey, verifySignature, verifySignatureOverDigest } from "./crypto.js";
4
+ import { preAuthEncoding } from "./dsse.js";
5
+ import {
6
+ base64ToUint8Array,
7
+ stringToUint8Array,
8
+ toArrayBuffer,
9
+ uint8ArrayEqual,
10
+ Uint8ArrayToHex,
11
+ Uint8ArrayToString,
12
+ } from "./encoding.js";
13
+ import {
14
+ CertAuthority,
15
+ CTLog,
16
+ HashAlgorithms,
17
+ RawCAs,
18
+ RawLogs,
19
+ RawTimestampAuthorities,
20
+ RekorKeyInfo,
21
+ Sigstore,
22
+ SigstoreRoots,
23
+ TrustedRoot,
24
+ } from "./interfaces.js";
25
+ import { ByteStream } from "./stream.js";
26
+ import {
27
+ CertificateChainVerifier,
28
+ EXTENSION_OID_SCT,
29
+ X509Certificate,
30
+ X509SCTExtension,
31
+ } from "./x509/index.js";
32
+ import { verifyMerkleInclusion } from "./tlog/merkle.js";
33
+ import { verifyCheckpoint } from "./tlog/checkpoint.js";
34
+ import { verifyTLogBody } from "./tlog/body.js";
35
+ import { verifyBundleTimestamp } from "./timestamp/tsa.js";
36
+ import { TrustedRootProvider } from "./trust/tuf.js";
37
+
38
+ export interface SigstoreVerifierOptions {
39
+ tlogThreshold?: number;
40
+ ctlogThreshold?: number;
41
+ tsaThreshold?: number;
42
+ }
43
+
44
+ export class SigstoreVerifier {
45
+ private root: Sigstore | undefined;
46
+ private rawRoot: TrustedRoot | undefined;
47
+ private options: Required<SigstoreVerifierOptions>;
48
+
49
+ constructor(options: SigstoreVerifierOptions = {}) {
50
+ this.root = undefined;
51
+ this.rawRoot = undefined;
52
+ this.options = {
53
+ tlogThreshold: options.tlogThreshold ?? 1,
54
+ ctlogThreshold: options.ctlogThreshold ?? 1,
55
+ tsaThreshold: options.tsaThreshold ?? 0,
56
+ };
57
+ }
58
+
59
+ async loadLog(frozenTimestamp: Date, logs: RawLogs): Promise<RekorKeyInfo | undefined> {
60
+ // Load the first Rekor transparency log key that's valid at the frozen timestamp
61
+ // and store its log ID for verification. This matches sigstore-go's approach of
62
+ // looking up the verifier by log ID (verify/tlog.go:80-83).
63
+
64
+ for (const log of logs) {
65
+ // if start date is not in the future, and if an end doesn't exist or is in the future
66
+ if (
67
+ frozenTimestamp > new Date(log.publicKey.validFor.start) &&
68
+ (!log.publicKey.validFor.end ||
69
+ new Date(log.publicKey.validFor.end) > frozenTimestamp)
70
+ ) {
71
+ return {
72
+ publicKey: await importKey(
73
+ log.publicKey.keyDetails,
74
+ log.publicKey.keyDetails,
75
+ log.publicKey.rawBytes,
76
+ ),
77
+ logId: base64ToUint8Array(log.logId.keyId),
78
+ };
79
+ }
80
+ }
81
+
82
+ // Return undefined instead of throwing - some bundles don't need Rekor keys
83
+ // (e.g., v0.3 bundles with inclusion proofs)
84
+ return undefined;
85
+ }
86
+
87
+ async loadCTLogs(frozenTimestamp: Date, ctlogs: RawLogs): Promise<CTLog[]> {
88
+ const result: CTLog[] = [];
89
+
90
+ for (const log of ctlogs) {
91
+ const start = new Date(log.publicKey.validFor.start);
92
+ const end = log.publicKey.validFor.end
93
+ ? new Date(log.publicKey.validFor.end)
94
+ : new Date('9999-12-31'); // No expiry means valid forever
95
+
96
+ // Include logs that are valid (started before frozen timestamp)
97
+ // We keep all logs, even expired ones, for historical verification
98
+ if (start <= frozenTimestamp) {
99
+ const publicKey = await importKey(
100
+ log.publicKey.keyDetails,
101
+ log.publicKey.keyDetails,
102
+ log.publicKey.rawBytes,
103
+ );
104
+
105
+ result.push({
106
+ logID: base64ToUint8Array(log.logId.keyId),
107
+ publicKey,
108
+ validFor: { start, end },
109
+ });
110
+ }
111
+ }
112
+
113
+ if (result.length === 0) {
114
+ throw new Error("Could not find any valid CT logs in sigstore root.");
115
+ }
116
+
117
+ return result;
118
+ }
119
+
120
+ // Adapted from https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/key/certificate.ts#L22-L53
121
+ // Verifies that the leaf certificate chains to a trusted CA and is valid at the given timestamp.
122
+ // Differences from sigstore-js:
123
+ // - This is async (uses await) because our CertificateChainVerifier.verify() is async
124
+ // - sigstore-js filters CAs using filterCertAuthorities() before calling this function,
125
+ // we do the timestamp filtering inline within this function
126
+ async verifyCertificateChain(
127
+ timestamp: Date,
128
+ leaf: X509Certificate,
129
+ certificateAuthorities: CertAuthority[]
130
+ ): Promise<X509Certificate[]> {
131
+ let lastError: any;
132
+
133
+ for (const ca of certificateAuthorities) {
134
+ // Check if this CA is valid for the given timestamp
135
+ if (timestamp < ca.validFor.start || timestamp > ca.validFor.end) {
136
+ continue;
137
+ }
138
+
139
+ try {
140
+ const verifier = new CertificateChainVerifier({
141
+ trustedCerts: ca.certChain,
142
+ untrustedCert: leaf,
143
+ timestamp,
144
+ });
145
+ return await verifier.verify();
146
+ } catch (err) {
147
+ lastError = err;
148
+ }
149
+ }
150
+
151
+ throw new Error(`Failed to verify certificate chain: ${lastError?.message || 'No valid CAs found'}`);
152
+ }
153
+
154
+ // Load timestamp authorities that are valid at the frozen timestamp.
155
+ // Unlike sigstore-js which doesn't pre-load TSAs (it passes raw TSA data to timestamp verification),
156
+ // we parse and filter them at initialization time for consistency with how we handle CAs and other roots.
157
+ loadTSA(
158
+ frozenTimestamp: Date,
159
+ tsas?: RawTimestampAuthorities,
160
+ ): CertAuthority[] {
161
+ if (!tsas || tsas.length === 0) {
162
+ return [];
163
+ }
164
+
165
+ const result: CertAuthority[] = [];
166
+
167
+ for (const tsa of tsas) {
168
+ const start = new Date(tsa.validFor.start);
169
+ const end = tsa.validFor.end ? new Date(tsa.validFor.end) : new Date(8640000000000000);
170
+
171
+ if (frozenTimestamp > start && frozenTimestamp < end) {
172
+ const certChain = tsa.certChain.certificates.map(cert =>
173
+ X509Certificate.parse(base64ToUint8Array(cert.rawBytes))
174
+ );
175
+
176
+ if (certChain.length > 0) {
177
+ result.push({
178
+ certChain,
179
+ validFor: { start, end },
180
+ });
181
+ }
182
+ }
183
+ }
184
+
185
+ return result;
186
+ }
187
+
188
+ // Load certificate authorities (Fulcio CAs) that are valid at the frozen timestamp.
189
+ // Similar to sigstore-js's filterCertAuthorities() in trust/filter.ts, but we also
190
+ // parse the certificates at load time whereas sigstore-js keeps them in the trust material
191
+ // and parses them during verification. This pre-loading approach is consistent with our
192
+ // architecture of loading all trusted roots at initialization.
193
+ loadCA(frozenTimestamp: Date, cas: RawCAs): CertAuthority[] {
194
+ const result: CertAuthority[] = [];
195
+
196
+ for (const ca of cas) {
197
+ const start = new Date(ca.validFor.start);
198
+ const end = ca.validFor.end ? new Date(ca.validFor.end) : new Date(8640000000000000);
199
+
200
+ if (frozenTimestamp > start && frozenTimestamp < end) {
201
+ const certChain = ca.certChain.certificates.map(cert =>
202
+ X509Certificate.parse(base64ToUint8Array(cert.rawBytes))
203
+ );
204
+
205
+ if (certChain.length > 0) {
206
+ result.push({
207
+ certChain,
208
+ validFor: { start, end },
209
+ });
210
+ }
211
+ }
212
+ }
213
+
214
+ return result;
215
+ }
216
+
217
+ async loadSigstoreRoot(rawRoot: TrustedRoot) {
218
+ const frozenTimestamp = new Date();
219
+
220
+ this.rawRoot = rawRoot;
221
+ this.root = {
222
+ rekor: await this.loadLog(frozenTimestamp, rawRoot[SigstoreRoots.tlogs]),
223
+ ctlogs: await this.loadCTLogs(frozenTimestamp, rawRoot[SigstoreRoots.ctlogs]),
224
+ certificateAuthorities: this.loadCA(
225
+ frozenTimestamp,
226
+ rawRoot[SigstoreRoots.certificateAuthorities],
227
+ ),
228
+ timestampAuthorities: this.loadTSA(frozenTimestamp, rawRoot.timestampAuthorities),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Load Sigstore trusted root via TUF
234
+ * Uses The Update Framework for secure, verified updates of trusted root metadata
235
+ *
236
+ * @param tufProvider Optional TrustedRootProvider instance. If not provided, uses default Sigstore TUF repository
237
+ */
238
+ async loadSigstoreRootWithTUF(tufProvider?: TrustedRootProvider): Promise<void> {
239
+ const provider = tufProvider || new TrustedRootProvider();
240
+ const trustedRoot = await provider.getTrustedRoot();
241
+ await this.loadSigstoreRoot(trustedRoot);
242
+ }
243
+
244
+ // Adapted from https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/key/sct.ts
245
+ // Key differences:
246
+ // - Adds duplicate SCT detection
247
+ // - Adds SCT timestamp validity checking
248
+ // - Inline CT log filtering by logID and validity period (reference uses filterTLogAuthorities)
249
+ // - Returns array of verified SCT logIDs for threshold checking (matches reference behavior)
250
+ async verifySCT(
251
+ cert: X509Certificate,
252
+ issuer: X509Certificate,
253
+ ctlogs: CTLog[],
254
+ ): Promise<Uint8Array[]> {
255
+ let extSCT: X509SCTExtension | undefined;
256
+
257
+ // Verifying the SCT requires that we remove the SCT extension and
258
+ // re-encode the TBS structure to DER -- this value is part of the data
259
+ // over which the signature is calculated. Since this is a destructive action
260
+ // we create a copy of the certificate so we can remove the SCT extension
261
+ // without affecting the original certificate.
262
+ const clone = cert.clone();
263
+
264
+ // Intentionally not using the findExtension method here because we want to
265
+ // remove the the SCT extension from the certificate before calculating the
266
+ // PreCert structure
267
+ for (let i = 0; i < clone.extensions.length; i++) {
268
+ const ext = clone.extensions[i];
269
+
270
+ if (ext.subs[0].toOID() === EXTENSION_OID_SCT) {
271
+ extSCT = new X509SCTExtension(ext);
272
+
273
+ // Remove the extension from the certificate
274
+ clone.extensions.splice(i, 1);
275
+ break;
276
+ }
277
+ }
278
+
279
+ // No SCT extension found - fail verification
280
+ if (!extSCT) {
281
+ throw new Error("Certificate is missing required SCT extension");
282
+ }
283
+
284
+ // Found an SCT extension but it has no SCTs - fail verification
285
+ if (extSCT.signedCertificateTimestamps.length === 0) {
286
+ throw new Error("SCT extension is present but contains no SCTs");
287
+ }
288
+
289
+ // Check for duplicate SCTs (same log ID)
290
+ const seenLogIds = new Set<string>();
291
+ for (const sct of extSCT.signedCertificateTimestamps) {
292
+ const logIdHex = Uint8ArrayToHex(sct.logID);
293
+ if (seenLogIds.has(logIdHex)) {
294
+ throw new Error(`Duplicate SCT found for log ID: ${logIdHex}`);
295
+ }
296
+ seenLogIds.add(logIdHex);
297
+ }
298
+
299
+ // Construct the PreCert structure
300
+ // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
301
+ const preCert = new ByteStream();
302
+
303
+ // Calculate hash of the issuer's public key
304
+ const issuerId = new Uint8Array(
305
+ await crypto.subtle.digest(HashAlgorithms.SHA256, toArrayBuffer(issuer.publicKey)),
306
+ );
307
+ preCert.appendView(issuerId);
308
+
309
+ // Re-encodes the certificate to DER after removing the SCT extension
310
+ const tbs = clone.tbsCertificate.toDER();
311
+ preCert.appendUint24(tbs.length);
312
+ preCert.appendView(tbs);
313
+
314
+ // Collect all verified SCTs to check against threshold
315
+ const verifiedSCTs: Uint8Array[] = [];
316
+
317
+ for (const sct of extSCT.signedCertificateTimestamps) {
318
+ // SCT should be within certificate validity period
319
+ if (sct.datetime < cert.notBefore || sct.datetime > cert.notAfter) {
320
+ continue; // Skip invalid SCT timestamp, don't fail yet
321
+ }
322
+
323
+ // Find the CT log that matches this SCT's log ID and is valid for the SCT datetime
324
+ const validCTLogs = ctlogs.filter((log) => {
325
+ // Check if log IDs match
326
+ if (log.logID.length !== sct.logID.length) return false;
327
+ for (let i = 0; i < log.logID.length; i++) {
328
+ if (log.logID[i] !== sct.logID[i]) return false;
329
+ }
330
+ // Check that the SCT datetime is within the log's validity period
331
+ return log.validFor.start <= sct.datetime && sct.datetime <= log.validFor.end;
332
+ });
333
+
334
+ // Try to verify with any valid CT log
335
+ let verified = false;
336
+ for (const log of validCTLogs) {
337
+ try {
338
+ if (await sct.verify(preCert.buffer, log.publicKey)) {
339
+ verified = true;
340
+ break; // Found a valid log for this SCT
341
+ }
342
+ } catch (e) {
343
+ // Continue trying other logs
344
+ }
345
+ }
346
+
347
+ if (verified) {
348
+ verifiedSCTs.push(sct.logID);
349
+ }
350
+ }
351
+
352
+ return verifiedSCTs;
353
+ }
354
+
355
+ async verifyInclusionPromise(
356
+ cert: X509Certificate,
357
+ bundle: SigstoreBundle,
358
+ rekor: RekorKeyInfo | undefined,
359
+ ): Promise<boolean> {
360
+ const entries = bundle.verificationMaterial.tlogEntries;
361
+
362
+ if (entries.length < 1) {
363
+ throw new Error(
364
+ "Failed to find a transparency log entry in the provided bundle.",
365
+ );
366
+ }
367
+
368
+ // Prevent DoS via excessive entries and threshold bypass via duplicates
369
+ // Matches sigstore-go limits (verify/tlog.go:46-57)
370
+ const MAX_TLOG_ENTRIES = 32;
371
+ if (entries.length > MAX_TLOG_ENTRIES) {
372
+ throw new Error(
373
+ `Too many tlog entries: ${entries.length} > ${MAX_TLOG_ENTRIES}`,
374
+ );
375
+ }
376
+
377
+ for (let i = 0; i < entries.length; i++) {
378
+ for (let j = i + 1; j < entries.length; j++) {
379
+ const iLogId = Uint8ArrayToHex(base64ToUint8Array(entries[i].logId.keyId));
380
+ const jLogId = Uint8ArrayToHex(base64ToUint8Array(entries[j].logId.keyId));
381
+ if (iLogId === jLogId && entries[i].logIndex === entries[j].logIndex) {
382
+ throw new Error(
383
+ `Duplicate tlog entry found: logID=${iLogId}, logIndex=${entries[i].logIndex}`,
384
+ );
385
+ }
386
+ }
387
+ }
388
+
389
+ const entry = entries[0];
390
+
391
+ // Extract bundle version from mediaType
392
+ // e.g., "application/vnd.dev.sigstore.bundle+json;version=0.2"
393
+ const versionMatch = bundle.mediaType.match(/version=(\d+\.\d+)/);
394
+ const bundleVersion = versionMatch ? versionMatch[1] : "0.1";
395
+ const isV02OrLater = parseFloat(bundleVersion) >= 0.2;
396
+
397
+ // Bundle v0.2+ requires an inclusion proof
398
+ if (isV02OrLater && !entry.inclusionProof) {
399
+ throw new Error(
400
+ "Bundle v0.2+ requires an inclusion proof.",
401
+ );
402
+ }
403
+
404
+ // For rekor2/v0.3 bundles with inclusion proofs, the inclusion promise is optional
405
+ if (!entry.inclusionPromise?.signedEntryTimestamp) {
406
+ // If there's no inclusion promise, there must be an inclusion proof
407
+ if (!entry.inclusionProof) {
408
+ throw new Error(
409
+ "Bundle must have either an inclusion promise or an inclusion proof.",
410
+ );
411
+ }
412
+ } else {
413
+ // Verify the inclusion promise signature if present
414
+ // For v0.3 bundles that have both inclusion promise and proof,
415
+ // we can skip the promise verification if we don't have a Rekor key
416
+ // and there's a valid inclusion proof
417
+ if (!rekor && entry.inclusionProof) {
418
+ // Skip promise verification if we have an inclusion proof
419
+ // The inclusion proof will be verified later
420
+ } else {
421
+ if (!rekor) {
422
+ throw new Error("Rekor public key not found in trusted root");
423
+ }
424
+
425
+ // Verify the log ID matches (matches sigstore-go verify/tlog.go:80-83)
426
+ const entryLogId = base64ToUint8Array(entry.logId.keyId);
427
+ if (!uint8ArrayEqual(rekor.logId, entryLogId)) {
428
+ throw new Error(
429
+ `Rekor log ID mismatch: bundle uses ${Uint8ArrayToHex(entryLogId)} but loaded key is for ${Uint8ArrayToHex(rekor.logId)}`
430
+ );
431
+ }
432
+
433
+ const signature = base64ToUint8Array(
434
+ entry.inclusionPromise.signedEntryTimestamp,
435
+ );
436
+
437
+ const keyId = Uint8ArrayToHex(entryLogId);
438
+ const integratedTime = Number(entry.integratedTime);
439
+
440
+ const signed = stringToUint8Array(
441
+ canonicalize({
442
+ body: entry.canonicalizedBody,
443
+ integratedTime: integratedTime,
444
+ logIndex: Number(entry.logIndex),
445
+ logID: keyId,
446
+ }),
447
+ );
448
+
449
+ if (!(await verifySignature(rekor.publicKey, signed, signature))) {
450
+ throw new Error(
451
+ "Failed to verify the inclusion promise in the provided bundle.",
452
+ );
453
+ }
454
+ }
455
+ }
456
+
457
+ // Validate integrated time and logged certificate
458
+ // Note: Rekor v2 bundles don't have integrated time in the tlog entry
459
+ if (entry.integratedTime) {
460
+ const integratedTime = Number(entry.integratedTime);
461
+ const integratedDate = new Date(integratedTime * 1000);
462
+
463
+ if (!cert.validForDate(integratedDate)) {
464
+ throw new Error(
465
+ "Artifact signing was logged outside of the certificate validity.",
466
+ );
467
+ }
468
+ } else {
469
+ // Rekor v2 bundles (no integratedTime) require a timestamp for verification
470
+ if (!bundle.verificationMaterial.timestampVerificationData) {
471
+ throw new Error(
472
+ "Rekor v2 bundles require a timestamp for verification.",
473
+ );
474
+ }
475
+ }
476
+
477
+ // Verify that the certificate in the log matches the signing certificate
478
+ // The format depends on the entry type (hashedrekord vs dsse) and version
479
+ const bodyJson = JSON.parse(Uint8ArrayToString(base64ToUint8Array(entry.canonicalizedBody)));
480
+
481
+ if (bodyJson.kind === "hashedrekord") {
482
+ let loggedCertContent: string | undefined;
483
+
484
+ // Check for hashedRekordV002 structure (Rekor v2)
485
+ if (bodyJson.spec.hashedRekordV002) {
486
+ const verifier = bodyJson.spec.hashedRekordV002.signature.verifier;
487
+ if (verifier?.x509Certificate) {
488
+ loggedCertContent = verifier.x509Certificate.rawBytes;
489
+ }
490
+ }
491
+ // Check for older hashedrekord structure
492
+ else if (bodyJson.spec.signature?.publicKey) {
493
+ loggedCertContent = bodyJson.spec.signature.publicKey.content;
494
+ }
495
+
496
+ if (loggedCertContent) {
497
+ // For hashedrekord v0.0.1, publicKey.content is base64-encoded PEM
498
+ // For hashedRekordV002, x509Certificate.rawBytes is base64-encoded DER
499
+ let loggedCert: X509Certificate;
500
+ if (bodyJson.spec.hashedRekordV002) {
501
+ loggedCert = X509Certificate.parse(base64ToUint8Array(loggedCertContent));
502
+ } else {
503
+ const pemString = Uint8ArrayToString(base64ToUint8Array(loggedCertContent));
504
+ loggedCert = X509Certificate.parse(pemString);
505
+ }
506
+
507
+ if (!cert.equals(loggedCert)) {
508
+ throw new Error(
509
+ "Certificate in Rekor log does not match the signing certificate.",
510
+ );
511
+ }
512
+ }
513
+ } else if (bodyJson.kind === "dsse") {
514
+ // DSSE entries store signatures differently
515
+ // The certificate is verified through the bundle's verification material
516
+ // No additional check needed here
517
+ } else if (bodyJson.kind === "intoto") {
518
+ // Intoto entries are DSSE-based and don't store certificates in the tlog entry
519
+ // The certificate is part of the bundle's verification material which has already
520
+ // been verified against the CA root. The intoto verification in tlog/intoto.ts
521
+ // verifies the signature and payload hash match between the tlog and bundle.
522
+ } else {
523
+ // Unknown entry type - this should not happen with standard Sigstore bundles
524
+ throw new Error(`Unsupported tlog entry kind: ${bodyJson.kind}`);
525
+ }
526
+
527
+ return true;
528
+ }
529
+
530
+ async verifyInclusionProof(bundle: SigstoreBundle): Promise<void> {
531
+ if (!this.rawRoot) {
532
+ throw new Error("Sigstore root is undefined");
533
+ }
534
+
535
+ if (bundle.verificationMaterial.tlogEntries.length < 1) {
536
+ throw new Error("No transparency log entries found in bundle");
537
+ }
538
+
539
+ const entry = bundle.verificationMaterial.tlogEntries[0];
540
+
541
+ // Only verify if there's an inclusion proof (v0.3/rekor2 bundles)
542
+ // v0.1 bundles use inclusion promises instead, verified in verifyInclusionPromise
543
+ if (entry.inclusionProof) {
544
+ await verifyMerkleInclusion(entry);
545
+
546
+ if (entry.inclusionProof.checkpoint) {
547
+ await verifyCheckpoint(entry, this.rawRoot.tlogs);
548
+ }
549
+ }
550
+ }
551
+
552
+ public async verifyArtifact(
553
+ identity: string,
554
+ issuer: string,
555
+ bundle: SigstoreBundle,
556
+ data: Uint8Array,
557
+ isDigestOnly: boolean = false,
558
+ ): Promise<boolean> {
559
+ // Quick checks first: does the signing certificate have the correct identity?
560
+
561
+ if (!this.root) {
562
+ throw new Error("Sigstore root is undefined");
563
+ }
564
+
565
+ const cert = bundle.verificationMaterial.certificate ||
566
+ bundle.verificationMaterial.x509CertificateChain?.certificates[0];
567
+
568
+ if (!cert) {
569
+ throw new Error("No certificate found in bundle");
570
+ }
571
+
572
+ const signingCert = X509Certificate.parse(base64ToUint8Array(cert.rawBytes));
573
+
574
+ // Handle both regular bundles (messageSignature) and DSSE bundles (dsseEnvelope)
575
+ let signature: Uint8Array;
576
+ if (bundle.messageSignature) {
577
+ signature = base64ToUint8Array(bundle.messageSignature.signature);
578
+ } else if (bundle.dsseEnvelope) {
579
+ if (!bundle.dsseEnvelope.signatures || bundle.dsseEnvelope.signatures.length === 0) {
580
+ throw new Error("DSSE envelope has no signatures");
581
+ }
582
+ signature = base64ToUint8Array(bundle.dsseEnvelope.signatures[0].sig);
583
+ } else {
584
+ throw new Error("Bundle does not contain a message signature or DSSE envelope");
585
+ }
586
+
587
+ // # 1 Basic stuff
588
+ if (signingCert.subjectAltName !== identity) {
589
+ throw new Error(
590
+ "Certificate identity (subjectAltName) do not match the verifying one.",
591
+ );
592
+ }
593
+
594
+ // Check for issuer - try V2 first, fall back to V1 (like sigstore-js does)
595
+ const certIssuer = signingCert.extFulcioIssuerV2?.issuer || signingCert.extFulcioIssuerV1?.issuer;
596
+ if (certIssuer !== issuer) {
597
+ throw new Error("Identity issuer is not the verifying one.");
598
+ }
599
+
600
+ // # 2 Certificate validity - verify chain to trusted CA
601
+ // Similar to sigstore-js key/index.ts:59-64 which calls verifyCertificateChain()
602
+ // Returns the verified certificate path [leaf, intermediate(s), root]
603
+ const certPath = await this.verifyCertificateChain(
604
+ signingCert.notBefore,
605
+ signingCert,
606
+ this.root.certificateAuthorities
607
+ );
608
+
609
+ // # 3 To verify the SCT we need to build a preCert (because the cert was logged without the SCT)
610
+ // https://github.com/sigstore/sigstore-js/packages/verify/src/key/sct.ts#L45
611
+ // Similar to sigstore-js key/index.ts:67 which uses path[0] (leaf) and path[1] (issuer)
612
+ // for SCT verification. Handle edge case where path has only one cert (self-signed root).
613
+ const issuerCert = certPath.length > 1 ? certPath[1] : certPath[0];
614
+ const verifiedSCTs = await this.verifySCT(signingCert, issuerCert, this.root.ctlogs);
615
+ if (verifiedSCTs.length < this.options.ctlogThreshold) {
616
+ throw new Error(
617
+ `Not enough valid SCTs: found ${verifiedSCTs.length}, required ${this.options.ctlogThreshold}`
618
+ );
619
+ }
620
+
621
+ // # 4 Rekor inclusion promise
622
+ if (
623
+ !(await this.verifyInclusionPromise(signingCert, bundle, this.root.rekor))
624
+ ) {
625
+ throw new Error("Inclusion promise validation failed.");
626
+ }
627
+
628
+ // # 5 Rekor inclusion proof (Merkle tree verification)
629
+ await this.verifyInclusionProof(bundle);
630
+
631
+ // # 5.1 Rekor body verification
632
+ if (bundle.verificationMaterial.tlogEntries.length > 0) {
633
+ await verifyTLogBody(
634
+ bundle.verificationMaterial.tlogEntries[0],
635
+ bundle
636
+ );
637
+ }
638
+
639
+ // # 6 TSA Timestamp Verification (if present)
640
+ let verifiedTimestamp: Date | undefined;
641
+ if (bundle.verificationMaterial.timestampVerificationData) {
642
+ // Verify TSA timestamps if present
643
+ verifiedTimestamp = await verifyBundleTimestamp(
644
+ bundle.verificationMaterial.timestampVerificationData,
645
+ signature,
646
+ this.rawRoot?.timestampAuthorities || []
647
+ );
648
+
649
+ // If we have a verified timestamp, check certificate validity at that time
650
+ if (verifiedTimestamp && !signingCert.validForDate(verifiedTimestamp)) {
651
+ throw new Error(
652
+ "Certificate was not valid at the time of timestamping"
653
+ );
654
+ }
655
+ }
656
+
657
+ // # 7 Revocation *skipping* not really a thing (unsurprisingly)
658
+
659
+ // # 8 verify the signed data
660
+ if (bundle.dsseEnvelope) {
661
+ // For DSSE bundles, verify the signature over the PAE
662
+ const payloadBytes = base64ToUint8Array(bundle.dsseEnvelope.payload);
663
+ const payload = JSON.parse(Uint8ArrayToString(payloadBytes));
664
+
665
+ // Verify the artifact digest matches a subject in the in-toto statement
666
+ if (!payload.subject || payload.subject.length === 0) {
667
+ throw new Error("DSSE payload has no subject");
668
+ }
669
+
670
+ // Compute or extract the artifact digest
671
+ let artifactDigest: string;
672
+ if (isDigestOnly) {
673
+ // data is already the digest bytes
674
+ artifactDigest = Uint8ArrayToHex(data);
675
+ } else {
676
+ // data is the file content, compute the digest
677
+ artifactDigest = Uint8ArrayToHex(
678
+ new Uint8Array(await crypto.subtle.digest(HashAlgorithms.SHA256, toArrayBuffer(data)))
679
+ );
680
+ }
681
+
682
+ // Find matching subject by scanning all subjects (not just [0])
683
+ let matchedSubject = null;
684
+ for (const subject of payload.subject) {
685
+ const subjectDigest = subject.digest?.["sha256"];
686
+ if (subjectDigest && artifactDigest === subjectDigest.toLowerCase()) {
687
+ matchedSubject = subject;
688
+ break;
689
+ }
690
+ }
691
+
692
+ if (!matchedSubject) {
693
+ throw new Error(
694
+ `Artifact digest ${artifactDigest} does not match any subject in DSSE payload`
695
+ );
696
+ }
697
+
698
+ // Create PAE (Pre-Authentication Encoding) for signature verification
699
+ const pae = preAuthEncoding(bundle.dsseEnvelope.payloadType, payloadBytes);
700
+
701
+ const publicKey = await signingCert.publicKeyObj;
702
+ const verified = await verifySignature(publicKey, pae, signature);
703
+ if (!verified) {
704
+ throw new Error("DSSE signature verification failed");
705
+ }
706
+ } else {
707
+ const publicKey = await signingCert.publicKeyObj;
708
+
709
+ if (isDigestOnly) {
710
+ // For hashedrekord bundles, verify signature over the digest directly.
711
+ // Uses the same elliptic.js workaround as sigstore-js conformance CLI.
712
+ const verified = await verifySignatureOverDigest(publicKey, data, signature);
713
+ if (!verified) {
714
+ throw new Error("Error verifying signature over digest");
715
+ }
716
+ } else {
717
+ // For regular bundles, verify the signature over the artifact data
718
+ const verified = await verifySignature(publicKey, data, signature);
719
+ if (!verified) {
720
+ const keyAlg = publicKey.algorithm.name || 'unknown';
721
+ throw new Error(`Error verifying artifact signature. Key algorithm: ${keyAlg}, Data length: ${data.length}, Signature length: ${signature.length}`);
722
+ }
723
+ }
724
+ }
725
+
726
+ return true;
727
+ }
728
+ }