@freedomofpress/sigstore-browser 0.1.15 → 0.1.16

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 (132) hide show
  1. package/dist/bundle.d.ts +2 -3
  2. package/dist/bundle.js.map +1 -1
  3. package/dist/cli.d.ts +0 -1
  4. package/dist/cli.js.map +1 -1
  5. package/dist/dsse.d.ts +0 -1
  6. package/dist/dsse.js.map +1 -1
  7. package/dist/errors.d.ts +0 -1
  8. package/dist/errors.js.map +1 -1
  9. package/dist/index.d.ts +9 -10
  10. package/dist/index.js +5 -5
  11. package/dist/index.js.map +1 -1
  12. package/dist/interfaces.d.ts +1 -2
  13. package/dist/interfaces.js +1 -1
  14. package/dist/interfaces.js.map +1 -1
  15. package/dist/oid.d.ts +0 -1
  16. package/dist/oid.js.map +1 -1
  17. package/dist/policy.d.ts +0 -1
  18. package/dist/policy.js +1 -1
  19. package/dist/policy.js.map +1 -1
  20. package/dist/rfc3161/error.d.ts +0 -1
  21. package/dist/rfc3161/error.js.map +1 -1
  22. package/dist/rfc3161/index.d.ts +0 -1
  23. package/dist/rfc3161/index.js.map +1 -1
  24. package/dist/rfc3161/timestamp.d.ts +0 -1
  25. package/dist/rfc3161/timestamp.js.map +1 -1
  26. package/dist/rfc3161/tstinfo.d.ts +0 -1
  27. package/dist/rfc3161/tstinfo.js.map +1 -1
  28. package/dist/sigstore.d.ts +2 -3
  29. package/dist/sigstore.js +9 -9
  30. package/dist/sigstore.js.map +1 -1
  31. package/dist/timestamp/tsa.d.ts +1 -2
  32. package/dist/timestamp/tsa.js +1 -1
  33. package/dist/timestamp/tsa.js.map +1 -1
  34. package/dist/tlog/body.d.ts +0 -1
  35. package/dist/tlog/body.js +1 -1
  36. package/dist/tlog/body.js.map +1 -1
  37. package/dist/tlog/checkpoint.d.ts +0 -1
  38. package/dist/tlog/checkpoint.js.map +1 -1
  39. package/dist/tlog/dsse.d.ts +0 -1
  40. package/dist/tlog/dsse.js +3 -0
  41. package/dist/tlog/dsse.js.map +1 -1
  42. package/dist/tlog/hashedrekord.d.ts +0 -1
  43. package/dist/tlog/hashedrekord.js.map +1 -1
  44. package/dist/tlog/intoto.d.ts +0 -1
  45. package/dist/tlog/intoto.js.map +1 -1
  46. package/dist/tlog/merkle.d.ts +0 -1
  47. package/dist/tlog/merkle.js.map +1 -1
  48. package/dist/trust/tuf-root.d.ts +0 -1
  49. package/dist/trust/tuf-root.js.map +1 -1
  50. package/dist/trust/tuf.d.ts +0 -1
  51. package/dist/trust/tuf.js.map +1 -1
  52. package/dist/x509/cert.d.ts +0 -1
  53. package/dist/x509/cert.js +1 -1
  54. package/dist/x509/cert.js.map +1 -1
  55. package/dist/x509/chain.d.ts +0 -1
  56. package/dist/x509/chain.js +2 -2
  57. package/dist/x509/chain.js.map +1 -1
  58. package/dist/x509/ext.d.ts +0 -1
  59. package/dist/x509/ext.js.map +1 -1
  60. package/dist/x509/index.d.ts +1 -2
  61. package/dist/x509/index.js +1 -1
  62. package/dist/x509/index.js.map +1 -1
  63. package/dist/x509/sct.d.ts +0 -1
  64. package/dist/x509/sct.js.map +1 -1
  65. package/package.json +15 -8
  66. package/.github/workflows/conformance.yml +0 -29
  67. package/.github/workflows/publish.yml +0 -47
  68. package/dist/bundle.d.ts.map +0 -1
  69. package/dist/cli.d.ts.map +0 -1
  70. package/dist/dsse.d.ts.map +0 -1
  71. package/dist/errors.d.ts.map +0 -1
  72. package/dist/index.d.ts.map +0 -1
  73. package/dist/interfaces.d.ts.map +0 -1
  74. package/dist/oid.d.ts.map +0 -1
  75. package/dist/policy.d.ts.map +0 -1
  76. package/dist/rfc3161/error.d.ts.map +0 -1
  77. package/dist/rfc3161/index.d.ts.map +0 -1
  78. package/dist/rfc3161/timestamp.d.ts.map +0 -1
  79. package/dist/rfc3161/tstinfo.d.ts.map +0 -1
  80. package/dist/sigstore.d.ts.map +0 -1
  81. package/dist/timestamp/tsa.d.ts.map +0 -1
  82. package/dist/tlog/body.d.ts.map +0 -1
  83. package/dist/tlog/checkpoint.d.ts.map +0 -1
  84. package/dist/tlog/dsse.d.ts.map +0 -1
  85. package/dist/tlog/hashedrekord.d.ts.map +0 -1
  86. package/dist/tlog/intoto.d.ts.map +0 -1
  87. package/dist/tlog/merkle.d.ts.map +0 -1
  88. package/dist/trust/tuf-root.d.ts.map +0 -1
  89. package/dist/trust/tuf.d.ts.map +0 -1
  90. package/dist/x509/cert.d.ts.map +0 -1
  91. package/dist/x509/chain.d.ts.map +0 -1
  92. package/dist/x509/ext.d.ts.map +0 -1
  93. package/dist/x509/index.d.ts.map +0 -1
  94. package/dist/x509/sct.d.ts.map +0 -1
  95. package/eslint.config.mjs +0 -31
  96. package/src/bundle.ts +0 -186
  97. package/src/cli.ts +0 -290
  98. package/src/dsse.ts +0 -49
  99. package/src/ed25519.browser.test.ts +0 -76
  100. package/src/errors.ts +0 -82
  101. package/src/index.browser.test.ts +0 -301
  102. package/src/index.ts +0 -93
  103. package/src/interfaces.ts +0 -150
  104. package/src/oid.ts +0 -34
  105. package/src/policy.ts +0 -476
  106. package/src/rfc3161/error.ts +0 -16
  107. package/src/rfc3161/index.ts +0 -17
  108. package/src/rfc3161/timestamp.ts +0 -268
  109. package/src/rfc3161/tstinfo.ts +0 -78
  110. package/src/security.browser.test.ts +0 -249
  111. package/src/sigstore.ts +0 -605
  112. package/src/timestamp/tsa.ts +0 -212
  113. package/src/tlog/body.ts +0 -84
  114. package/src/tlog/checkpoint.ts +0 -154
  115. package/src/tlog/dsse.ts +0 -153
  116. package/src/tlog/hashedrekord.ts +0 -136
  117. package/src/tlog/intoto.ts +0 -109
  118. package/src/tlog/merkle.ts +0 -152
  119. package/src/trust/README.md +0 -38
  120. package/src/trust/tuf-root.ts +0 -3
  121. package/src/trust/tuf.ts +0 -233
  122. package/src/verify.browser.test.ts +0 -281
  123. package/src/x509/cert.ts +0 -569
  124. package/src/x509/chain.ts +0 -212
  125. package/src/x509/ext.ts +0 -356
  126. package/src/x509/index.ts +0 -19
  127. package/src/x509/sct.ts +0 -156
  128. package/test/fixtures/rekor2.ts +0 -14
  129. package/test/fixtures/sigstore.ts +0 -13
  130. package/tsconfig.json +0 -18
  131. package/vite.config.playwright.ts +0 -14
  132. package/vite.config.ts +0 -18
package/src/sigstore.ts DELETED
@@ -1,605 +0,0 @@
1
- import {
2
- base64ToUint8Array,
3
- ByteStream,
4
- canonicalize,
5
- importKey,
6
- stringToUint8Array,
7
- uint8ArrayEqual,
8
- Uint8ArrayToHex,
9
- Uint8ArrayToString,
10
- verifySignature,
11
- verifySignatureOverDigest,
12
- } from "@freedomofpress/crypto-browser";
13
- import { HashAlgorithms } from "./interfaces.js";
14
- import {
15
- CertificateChainVerifier,
16
- EXTENSION_OID_SCT,
17
- X509Certificate,
18
- X509SCTExtension,
19
- } from "./x509/index.js";
20
- import { assertBundle, SigstoreBundle, TLogEntry } from "./bundle.js";
21
- import { preAuthEncoding } from "./dsse.js";
22
- import {
23
- CertAuthority,
24
- CTLog,
25
- parseValidityPeriod,
26
- RawCAs,
27
- RawLogs,
28
- RekorKeyInfo,
29
- Sigstore,
30
- SigstoreRoots,
31
- TrustedRoot,
32
- } from "./interfaces.js";
33
- import { verifyMerkleInclusion } from "./tlog/merkle.js";
34
- import { verifyCheckpoint } from "./tlog/checkpoint.js";
35
- import { verifyTLogBody } from "./tlog/body.js";
36
- import { verifyBundleTimestamp } from "./timestamp/tsa.js";
37
- import { TrustedRootProvider } from "./trust/tuf.js";
38
- import type { VerificationPolicy } from "./policy.js";
39
- import { AnyOf, AllOf, OIDCIssuer, OIDCIssuerV2, Identity } from "./policy.js";
40
-
41
- const MEDIA_TYPE_BASE = "application/vnd.dev.sigstore.bundle";
42
- // Upper bounds on in-toto subjects and digests, matching sigstore-go.
43
- const MAX_SUBJECTS = 1024;
44
- const MAX_SUBJECT_DIGESTS = 32;
45
-
46
- // Unknown operators can satisfy threshold one, but add no independence to named operators.
47
- function countOperators(operators: Set<string>): number {
48
- if (operators.size === 0) return 0;
49
- return Math.max(1, operators.size - (operators.has("") ? 1 : 0));
50
- }
51
-
52
- /**
53
- * Extract bundle version from mediaType string
54
- * Reference: https://github.com/sigstore/sigstore-go/blob/main/pkg/bundle/bundle.go#L159-L177
55
- */
56
- function getBundleVersion(mediaType: string): string {
57
- switch (mediaType) {
58
- case `${MEDIA_TYPE_BASE}+json;version=0.1`:
59
- return "0.1";
60
- case `${MEDIA_TYPE_BASE}+json;version=0.2`:
61
- return "0.2";
62
- case `${MEDIA_TYPE_BASE}+json;version=0.3`:
63
- return "0.3";
64
- }
65
-
66
- // New format: "application/vnd.dev.sigstore.bundle.v0.3+json"
67
- if (mediaType.startsWith(`${MEDIA_TYPE_BASE}.v`) && mediaType.endsWith("+json")) {
68
- const version = mediaType
69
- .replace(`${MEDIA_TYPE_BASE}.v`, "")
70
- .replace("+json", "");
71
- // Only the versions this verifier implements are accepted.
72
- if (/^0\.[123]$/.test(version)) {
73
- return version;
74
- }
75
- }
76
-
77
- throw new Error(`Unsupported bundle media type: ${mediaType}`);
78
- }
79
-
80
- export interface SigstoreVerifierOptions {
81
- tlogThreshold?: number;
82
- ctlogThreshold?: number;
83
- tsaThreshold?: number;
84
- }
85
-
86
- export class SigstoreVerifier {
87
- private root: Sigstore | undefined;
88
- private rawRoot: TrustedRoot | undefined;
89
- private options: Required<SigstoreVerifierOptions>;
90
-
91
- constructor(options: SigstoreVerifierOptions = {}) {
92
- this.root = undefined;
93
- this.rawRoot = undefined;
94
- this.options = {
95
- tlogThreshold: options.tlogThreshold ?? 1,
96
- ctlogThreshold: options.ctlogThreshold ?? 1,
97
- tsaThreshold: options.tsaThreshold ?? 0,
98
- };
99
- for (const [name, threshold] of Object.entries(this.options)) {
100
- if (!Number.isSafeInteger(threshold) || threshold < 0) {
101
- throw new Error(`${name} must be a non-negative safe integer`);
102
- }
103
- }
104
- }
105
-
106
- // Loads every Rekor key; entries select theirs by log ID and SETs are checked against its validity window.
107
- async loadLog(logs: RawLogs): Promise<RekorKeyInfo[]> {
108
- return Promise.all(
109
- logs.map(async (log) => ({
110
- publicKey: await importKey(
111
- log.publicKey.keyDetails,
112
- log.publicKey.keyDetails,
113
- log.publicKey.rawBytes,
114
- ),
115
- logId: base64ToUint8Array(log.logId.keyId),
116
- hashAlgorithm: log.hashAlgorithm,
117
- // Empty means unknown; countOperators never adds it to the named operator count.
118
- operator: log.operator || "",
119
- validFor: parseValidityPeriod(log.publicKey.validFor),
120
- })),
121
- );
122
- }
123
-
124
- // Loads every CT log; SCTs select their log by ID and are checked against its validity window.
125
- async loadCTLogs(ctlogs: RawLogs): Promise<CTLog[]> {
126
- if (ctlogs.length === 0) {
127
- throw new Error("Could not find any CT logs in sigstore root.");
128
- }
129
- return Promise.all(
130
- ctlogs.map(async (log) => ({
131
- logID: base64ToUint8Array(log.logId.keyId),
132
- publicKey: await importKey(
133
- log.publicKey.keyDetails,
134
- log.publicKey.keyDetails,
135
- log.publicKey.rawBytes,
136
- ),
137
- operator: log.operator || "",
138
- validFor: parseValidityPeriod(log.publicKey.validFor),
139
- })),
140
- );
141
- }
142
-
143
- // Adapted from https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/key/certificate.ts#L22-L53
144
- // Verifies that the leaf certificate chains to a trusted CA and is valid at the given timestamp.
145
- // Differences from sigstore-js:
146
- // - This is async (uses await) because our CertificateChainVerifier.verify() is async
147
- // - sigstore-js filters CAs using filterCertAuthorities() before calling this function,
148
- // we do the timestamp filtering inline within this function
149
- async verifyCertificateChain(
150
- timestamp: Date,
151
- leaf: X509Certificate,
152
- certificateAuthorities: CertAuthority[]
153
- ): Promise<X509Certificate[]> {
154
- let lastError: any;
155
-
156
- for (const ca of certificateAuthorities) {
157
- // Check if this CA is valid for the given timestamp
158
- if (timestamp < ca.validFor.start || timestamp > ca.validFor.end) {
159
- continue;
160
- }
161
-
162
- try {
163
- const verifier = new CertificateChainVerifier({
164
- trustedCerts: ca.certChain,
165
- untrustedCert: leaf,
166
- timestamp,
167
- });
168
- return await verifier.verify();
169
- } catch (err) {
170
- lastError = err;
171
- }
172
- }
173
-
174
- throw new Error(`Failed to verify certificate chain: ${lastError?.message || 'No valid CAs found'}`);
175
- }
176
-
177
- // Loads every Fulcio CA; verifyCertificateChain() selects CAs by the observer timestamp.
178
- loadCA(cas: RawCAs): CertAuthority[] {
179
- return cas
180
- .filter((ca) => ca.certChain.certificates.length > 0)
181
- .map((ca) => ({
182
- certChain: ca.certChain.certificates.map((cert) =>
183
- X509Certificate.parse(base64ToUint8Array(cert.rawBytes)),
184
- ),
185
- validFor: parseValidityPeriod(ca.validFor),
186
- }));
187
- }
188
-
189
- async loadSigstoreRoot(rawRoot: TrustedRoot) {
190
- rawRoot.timestampAuthorities?.forEach((authority) =>
191
- parseValidityPeriod(authority.validFor),
192
- );
193
- const root = {
194
- rekor: await this.loadLog(rawRoot[SigstoreRoots.tlogs]),
195
- ctlogs: await this.loadCTLogs(rawRoot[SigstoreRoots.ctlogs]),
196
- certificateAuthorities: this.loadCA(rawRoot[SigstoreRoots.certificateAuthorities]),
197
- };
198
- this.rawRoot = rawRoot;
199
- this.root = root;
200
- }
201
-
202
- /**
203
- * Load Sigstore trusted root via TUF
204
- * Uses The Update Framework for secure, verified updates of trusted root metadata
205
- *
206
- * @param tufProvider Optional TrustedRootProvider instance. If not provided, uses default Sigstore TUF repository
207
- */
208
- async loadSigstoreRootWithTUF(tufProvider?: TrustedRootProvider): Promise<void> {
209
- const provider = tufProvider || new TrustedRootProvider();
210
- const trustedRoot = await provider.getTrustedRoot();
211
- await this.loadSigstoreRoot(trustedRoot);
212
- }
213
-
214
- // Adapted from https://github.com/sigstore/sigstore-js/blob/main/packages/verify/src/key/sct.ts
215
- // Key differences:
216
- // - Adds duplicate SCT detection (not in reference)
217
- // - Inline CT log filtering by logID and validity period (reference uses filterTLogAuthorities)
218
- // - Returns the distinct operators of the logs whose SCTs verified, for threshold checking
219
- async verifySCT(
220
- cert: X509Certificate,
221
- issuer: X509Certificate,
222
- ctlogs: CTLog[],
223
- ): Promise<Set<string>> {
224
- let extSCT: X509SCTExtension | undefined;
225
-
226
- // Verifying the SCT requires that we remove the SCT extension and
227
- // re-encode the TBS structure to DER -- this value is part of the data
228
- // over which the signature is calculated. Since this is a destructive action
229
- // we create a copy of the certificate so we can remove the SCT extension
230
- // without affecting the original certificate.
231
- const clone = cert.clone();
232
-
233
- // Intentionally not using the findExtension method here because we want to
234
- // remove the the SCT extension from the certificate before calculating the
235
- // PreCert structure
236
- for (let i = 0; i < clone.extensions.length; i++) {
237
- const ext = clone.extensions[i];
238
-
239
- if (ext.subs[0].toOID() === EXTENSION_OID_SCT) {
240
- extSCT = new X509SCTExtension(ext);
241
-
242
- // Remove the extension from the certificate
243
- clone.extensions.splice(i, 1);
244
- break;
245
- }
246
- }
247
-
248
- // No SCT extension found - fail verification
249
- if (!extSCT) {
250
- throw new Error("Certificate is missing required SCT extension");
251
- }
252
-
253
- // Found an SCT extension but it has no SCTs - fail verification
254
- if (extSCT.signedCertificateTimestamps.length === 0) {
255
- throw new Error("SCT extension is present but contains no SCTs");
256
- }
257
-
258
- // Check for duplicate SCTs (same log ID)
259
- const seenLogIds = new Set<string>();
260
- for (const sct of extSCT.signedCertificateTimestamps) {
261
- const logIdHex = Uint8ArrayToHex(sct.logID);
262
- if (seenLogIds.has(logIdHex)) {
263
- throw new Error(`Duplicate SCT found for log ID: ${logIdHex}`);
264
- }
265
- seenLogIds.add(logIdHex);
266
- }
267
-
268
- // Construct the PreCert structure
269
- // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
270
- const preCert = new ByteStream();
271
-
272
- // Calculate hash of the issuer's public key
273
- const issuerId = new Uint8Array(
274
- await crypto.subtle.digest(HashAlgorithms.SHA256, issuer.publicKey as BufferSource),
275
- );
276
- preCert.appendView(issuerId);
277
-
278
- // Re-encodes the certificate to DER after removing the SCT extension
279
- const tbs = clone.tbsCertificate.toDER();
280
- preCert.appendUint24(tbs.length);
281
- preCert.appendView(tbs);
282
-
283
- // Calculate and return the verification results for each SCT
284
- // Unlike sigstore-go which counts verified SCTs and checks threshold at the end,
285
- // sigstore-js throws immediately if any SCT fails verification
286
- const operators = new Set<string>();
287
-
288
- for (const sct of extSCT.signedCertificateTimestamps) {
289
- // Find the CT log that matches this SCT's log ID and is valid for the SCT datetime
290
- const validCTLogs = ctlogs.filter((log) => {
291
- // Check if log IDs match
292
- if (!uint8ArrayEqual(log.logID, sct.logID)) return false;
293
- // Check that the SCT datetime is within the log's validity period
294
- return log.validFor.start <= sct.datetime && sct.datetime <= log.validFor.end;
295
- });
296
-
297
- // See if the SCT is valid for any of the CT logs
298
- const verified = await (async () => {
299
- for (const log of validCTLogs) {
300
- try {
301
- if (await sct.verify(preCert.buffer, log.publicKey)) {
302
- return log;
303
- }
304
- } catch {
305
- // Continue trying other logs
306
- }
307
- }
308
- return undefined;
309
- })();
310
-
311
- if (!verified) {
312
- throw new Error("SCT verification failed");
313
- }
314
-
315
- operators.add(verified.operator);
316
- }
317
-
318
- return operators;
319
- }
320
-
321
- // Verifies the signed entry timestamp and returns the integrated time it binds.
322
- private async verifySET(entry: TLogEntry, promise: string, log: RekorKeyInfo): Promise<Date> {
323
- const integratedTime = Number(entry.integratedTime);
324
- const integratedDate = new Date(integratedTime * 1000);
325
- if (integratedDate < log.validFor.start || integratedDate > log.validFor.end) {
326
- throw new Error("Rekor key was not valid at the integrated time.");
327
- }
328
- const signed = stringToUint8Array(
329
- canonicalize({
330
- body: entry.canonicalizedBody,
331
- integratedTime,
332
- logIndex: Number(entry.logIndex),
333
- logID: Uint8ArrayToHex(log.logId),
334
- }),
335
- );
336
- if (!(await verifySignature(log.publicKey, signed, base64ToUint8Array(promise), log.hashAlgorithm))) {
337
- throw new Error("Failed to verify the inclusion promise in the provided bundle.");
338
- }
339
- return integratedDate;
340
- }
341
-
342
- // Fully verifies every entry from a trusted log and returns the SET-bound integrated times.
343
- // Entries from unknown logs are ignored; the threshold counts distinct log operators that verified.
344
- private async verifyTlogEntries(
345
- cert: X509Certificate,
346
- bundle: SigstoreBundle,
347
- rekor: RekorKeyInfo[],
348
- ): Promise<Date[]> {
349
- const entries = bundle.verificationMaterial.tlogEntries;
350
- // Only v0.1 bundles may rely on an inclusion promise alone.
351
- const requireProof = getBundleVersion(bundle.mediaType) !== "0.1";
352
- const operators = new Set<string>();
353
- const integratedTimes: Date[] = [];
354
-
355
- for (const entry of entries) {
356
- const logId = base64ToUint8Array(entry.logId.keyId);
357
- const log = rekor.find((l) => uint8ArrayEqual(l.logId, logId));
358
- if (!log) continue;
359
-
360
- const promise = entry.inclusionPromise?.signedEntryTimestamp;
361
- if (!entry.inclusionProof && (requireProof || !promise)) {
362
- throw new Error("Transparency log entry requires an inclusion proof.");
363
- }
364
- if (promise) {
365
- integratedTimes.push(await this.verifySET(entry, promise, log));
366
- }
367
- if (entry.inclusionProof) {
368
- await verifyMerkleInclusion(entry);
369
- await verifyCheckpoint(entry, log);
370
- }
371
- if (entry.integratedTime && !cert.validForDate(new Date(Number(entry.integratedTime) * 1000))) {
372
- throw new Error("Artifact signing was logged outside of the certificate validity.");
373
- }
374
- await verifyTLogBody(entry, bundle, cert);
375
- operators.add(log.operator);
376
- }
377
-
378
- const verifiedOperators = countOperators(operators);
379
- if (verifiedOperators < this.options.tlogThreshold) {
380
- throw new Error(`Not enough verified transparency logs: ${verifiedOperators} < ${this.options.tlogThreshold}`);
381
- }
382
- return integratedTimes;
383
- }
384
-
385
- // Shared checks: policy, transparency log, timestamps, chain at every observer time, SCTs.
386
- // Returns the signing certificate and the bundle's signature.
387
- private async verifyBundle(
388
- bundle: SigstoreBundle,
389
- policy: VerificationPolicy,
390
- ): Promise<{ signingCert: X509Certificate; signature: Uint8Array }> {
391
- assertBundle(bundle);
392
- if (!this.root || !this.rawRoot) {
393
- throw new Error("Sigstore root is undefined");
394
- }
395
-
396
- const cert = bundle.verificationMaterial.certificate ||
397
- bundle.verificationMaterial.x509CertificateChain?.certificates[0];
398
- if (!cert) {
399
- throw new Error("No certificate found in bundle");
400
- }
401
- const signingCert = X509Certificate.parse(base64ToUint8Array(cert.rawBytes));
402
- const signature = base64ToUint8Array(
403
- bundle.messageSignature ? bundle.messageSignature.signature : bundle.dsseEnvelope.signatures[0].sig,
404
- );
405
-
406
- await policy.verify(signingCert);
407
-
408
- // Observer timestamps come from SET-bound integrated times and verified RFC 3161 timestamps.
409
- // Rekor v2 entries carry no integrated time, so they need a TSA timestamp to be anchored at all.
410
- const integratedTimes = await this.verifyTlogEntries(signingCert, bundle, this.root.rekor);
411
- const timestamps = await verifyBundleTimestamp(
412
- bundle.verificationMaterial.timestampVerificationData,
413
- signature,
414
- this.rawRoot.timestampAuthorities || [],
415
- );
416
- const tsaOperators = countOperators(new Set(timestamps.map((t) => t.operator)));
417
- if (tsaOperators < this.options.tsaThreshold) {
418
- throw new Error(`Not enough verified TSA operators: ${tsaOperators} < ${this.options.tsaThreshold}`);
419
- }
420
- const observerTimes = [...integratedTimes, ...timestamps.map((t) => t.signingTime)];
421
- if (observerTimes.length === 0) {
422
- throw new Error("No verified observer timestamp anchors the signature in time.");
423
- }
424
-
425
- // The CA window and the whole chain are checked at every observer time, never at the leaf's own notBefore.
426
- let certPath: X509Certificate[] = [];
427
- for (const ts of observerTimes) {
428
- certPath = await this.verifyCertificateChain(ts, signingCert, this.root.certificateAuthorities);
429
- }
430
- const issuerCert = certPath.length > 1 ? certPath[1] : certPath[0];
431
- const ctOperators = countOperators(await this.verifySCT(signingCert, issuerCert, this.root.ctlogs));
432
- if (ctOperators < this.options.ctlogThreshold) {
433
- throw new Error(`Not enough verified CT log operators: ${ctOperators} < ${this.options.ctlogThreshold}`);
434
- }
435
-
436
- return { signingCert, signature };
437
- }
438
-
439
- public async verifyArtifactPolicy(
440
- policy: VerificationPolicy,
441
- bundle: SigstoreBundle,
442
- data: Uint8Array,
443
- isDigestOnly: boolean = false,
444
- ): Promise<boolean> {
445
- if (isDigestOnly && data.byteLength !== 32) {
446
- throw new Error("SHA-256 digest must be exactly 32 bytes");
447
- }
448
- const { signingCert, signature } = await this.verifyBundle(bundle, policy);
449
-
450
- // # 7 Revocation *skipping* not really a thing (unsurprisingly)
451
-
452
- // # 8 verify the signed data
453
- if (bundle.dsseEnvelope) {
454
- // Only in-toto statements are understood; other payload types must not be read as one.
455
- if (bundle.dsseEnvelope.payloadType !== "application/vnd.in-toto+json") {
456
- throw new Error(`Unsupported DSSE payload type: ${bundle.dsseEnvelope.payloadType}`);
457
- }
458
- const payloadBytes = base64ToUint8Array(bundle.dsseEnvelope.payload);
459
- const payload = JSON.parse(Uint8ArrayToString(payloadBytes));
460
-
461
- // Verify the artifact digest matches a subject in the in-toto statement
462
- if (!Array.isArray(payload?.subject) || payload.subject.length === 0 || payload.subject.length > MAX_SUBJECTS) {
463
- throw new Error(`DSSE payload must have between 1 and ${MAX_SUBJECTS} subjects`);
464
- }
465
- // Compute or extract the artifact digest
466
- let artifactDigest: string;
467
- if (isDigestOnly) {
468
- // data is already the digest bytes
469
- artifactDigest = Uint8ArrayToHex(data);
470
- } else {
471
- // data is the file content, compute the digest
472
- artifactDigest = Uint8ArrayToHex(
473
- new Uint8Array(await crypto.subtle.digest(HashAlgorithms.SHA256, data as BufferSource))
474
- );
475
- }
476
-
477
- // Every subject must carry a bounded digest map; any one of them may match the artifact.
478
- let matchedSubject = false;
479
- for (const subject of payload.subject) {
480
- const digests = subject?.digest;
481
- if (!digests || typeof digests !== "object" || Array.isArray(digests) || Object.keys(digests).length > MAX_SUBJECT_DIGESTS) {
482
- throw new Error(`Invalid DSSE subject digest map (maximum ${MAX_SUBJECT_DIGESTS} digests)`);
483
- }
484
- matchedSubject ||= typeof digests.sha256 === "string" && artifactDigest === digests.sha256.toLowerCase();
485
- }
486
-
487
- if (!matchedSubject) {
488
- throw new Error(
489
- `Artifact digest ${artifactDigest} does not match any subject in DSSE payload`
490
- );
491
- }
492
-
493
- // Create PAE (Pre-Authentication Encoding) for signature verification
494
- const pae = preAuthEncoding(bundle.dsseEnvelope.payloadType, payloadBytes);
495
-
496
- const publicKey = await signingCert.publicKeyObj;
497
- const verified = await verifySignature(publicKey, pae, signature);
498
- if (!verified) {
499
- throw new Error("DSSE signature verification failed");
500
- }
501
- } else {
502
- // The bundle's message digest must be the digest of the artifact being verified.
503
- const { messageDigest } = bundle.messageSignature;
504
- const digest = isDigestOnly
505
- ? data
506
- : new Uint8Array(await crypto.subtle.digest(HashAlgorithms.SHA256, data as BufferSource));
507
- if (messageDigest.algorithm !== "SHA2_256" || !uint8ArrayEqual(digest, base64ToUint8Array(messageDigest.digest))) {
508
- throw new Error("Artifact digest does not match the bundle message digest");
509
- }
510
- const publicKey = await signingCert.publicKeyObj;
511
-
512
- if (isDigestOnly) {
513
- // For hashedrekord bundles, verify signature over the digest directly.
514
- // Uses the same elliptic.js workaround as sigstore-js conformance CLI.
515
- const verified = await verifySignatureOverDigest(publicKey, data, signature);
516
- if (!verified) {
517
- throw new Error("Error verifying signature over digest");
518
- }
519
- } else {
520
- // For regular bundles, verify the signature over the artifact data
521
- const verified = await verifySignature(publicKey, data, signature);
522
- if (!verified) {
523
- const keyAlg = publicKey.algorithm.name || 'unknown';
524
- throw new Error(`Error verifying artifact signature. Key algorithm: ${keyAlg}, Data length: ${data.length}, Signature length: ${signature.length}`);
525
- }
526
- }
527
- }
528
-
529
- return true;
530
- }
531
-
532
- public async verifyArtifact(
533
- identity: string,
534
- issuer: string,
535
- bundle: SigstoreBundle,
536
- data: Uint8Array,
537
- isDigestOnly: boolean = false,
538
- ): Promise<boolean> {
539
-
540
- const policy = new AllOf([
541
- new Identity({ identity }),
542
- new AnyOf([
543
- new OIDCIssuerV2(issuer),
544
- new OIDCIssuer(issuer),
545
- ]),
546
- ]);
547
-
548
- return this.verifyArtifactPolicy(
549
- policy,
550
- bundle,
551
- data,
552
- isDigestOnly,
553
- );
554
- }
555
-
556
-
557
-
558
- /**
559
- * Verify a DSSE bundle using a verification policy.
560
- * This matches sigstore-python's verify_dsse API.
561
- *
562
- * Reference: https://github.com/sigstore/sigstore-python/blob/main/sigstore/verify/verifier.py#L388
563
- *
564
- * Unlike verify_artifact which verifies an artifact against a bundle,
565
- * this method verifies the DSSE envelope itself and returns the payload.
566
- * The caller is responsible for checking that the payload matches their
567
- * expected artifact (e.g., by checking subjects in an in-toto statement).
568
- *
569
- * @param bundle - The Sigstore bundle containing the DSSE envelope
570
- * @param policy - A verification policy to apply to the signing certificate
571
- * @returns The payload type and payload bytes from the verified envelope
572
- */
573
- public async verifyDsse(
574
- bundle: SigstoreBundle,
575
- policy: VerificationPolicy,
576
- ): Promise<{ payloadType: string; payload: Uint8Array }> {
577
- const { signingCert, signature } = await this.verifyBundle(bundle, policy);
578
- if (!bundle.dsseEnvelope) {
579
- throw new Error("Bundle does not contain a DSSE envelope");
580
- }
581
-
582
- // (7) Verify the DSSE envelope signature
583
- const payloadBytes = base64ToUint8Array(bundle.dsseEnvelope.payload);
584
- const pae = preAuthEncoding(bundle.dsseEnvelope.payloadType, payloadBytes);
585
-
586
- const publicKey = await signingCert.publicKeyObj;
587
- const verified = await verifySignature(publicKey, pae, signature);
588
- if (!verified) {
589
- throw new Error("DSSE signature verification failed");
590
- }
591
-
592
- // (8) Every entry MUST be of type "dsse" for DSSE verification
593
- for (const entry of bundle.verificationMaterial.tlogEntries) {
594
- if (entry.kindVersion.kind !== "dsse") {
595
- throw new Error(`Expected entry type dsse, got ${entry.kindVersion.kind}`);
596
- }
597
- }
598
-
599
- // Return the verified payload
600
- return {
601
- payloadType: bundle.dsseEnvelope.payloadType,
602
- payload: payloadBytes,
603
- };
604
- }
605
- }