@muggleai/works 5.34.0-staging.309 → 5.34.0-staging.310

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.
@@ -9,7 +9,7 @@
9
9
  "name": "muggleai",
10
10
  "source": "./plugin",
11
11
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
12
- "version": "5.34.0-staging.309"
12
+ "version": "5.34.0-staging.310"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,24 +1,25 @@
1
- import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, buildElectronAppChecksumsUrl, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-SMUHQITB.js';
1
+ import { __export, getLogger, TelemetryEnvironment, getConfig, createChildLogger, buildElectronAppReleaseAssetUrl, getActiveRuntimeTarget, getAuthService, hasApiKey, getElectronAppVersion, getElectronAppDir, getPlatformKey, reconcileProjectPreferences, getDataDir2, PREFERENCES_FILE_NAME, isFirstRun, writePreferences, DEFAULT_PREFERENCES, isElectronAppInstalled, getElectronAppChecksums, getChecksumForPlatform, getElectronAppSignedFromVersion, getReleaseSignerIdentityUri, verifyFileChecksum, resolveElectronAppExecutablePath, calculateFileChecksum, initTelemetry, Surface, ServiceName, track, EventName, getQaTools, getLocalQaTools, performLogout, assertDeviceCodeClientProvisioned, performLogin, getActiveElectronAppReleaseStream, buildToolInputJsonSchema, toolRequiresAuth, getCallerCredentials, parseElectronAppDirName, getElectronAppReleaseTagPrefix, hasShownDisclosure, markDisclosureShown, getBundledElectronAppVersion, getElectronAppVersionSource, getCredentialsFilePath, ElectronAppReleaseStream, __require, getDisclosureCopy, buildOnboardingPlan, applyOnboardingAnswers, needsOnboarding, buildLlmSourcePlan, describeLlmSourceStatus, resolveLlmSourceStatus, readRunView, RunViewError, renderRunViewText, writeRunViewHtml, openBrowserUrl, evaluateCheckoutFreshness, runGitCommand, BLOCKING_FRESHNESS_VERDICTS, claimServiceStack, BUSY_EXIT_CODE, checkServiceStack, releaseServiceStack, readServiceStackStatus, resolvePreferences, buildElectronAppChecksumsUrl, OnboardingBlanketChoice, PreferenceKey, LlmSource, applyLlmSourceSelection, describeStackMismatch, getDataDir, DEFAULT_LOCAL_LLM_BASE_URL, isValidLocalBaseUrl, local_exports } from './chunk-SMUHQITB.js';
2
2
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { v4 } from 'uuid';
5
5
  import { z, ZodError } from 'zod';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
7
  import * as fs from 'fs';
8
- import { readFileSync, existsSync, rmSync, mkdirSync, readdirSync, createWriteStream, writeFileSync, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, renameSync, appendFileSync, readSync, fstatSync } from 'fs';
8
+ import { readFileSync, existsSync, rmSync, readdirSync, mkdirSync, writeFileSync, renameSync, createWriteStream, statSync, readlinkSync, realpathSync, openSync, closeSync, writeSync, unlinkSync, copyFileSync, appendFileSync, readSync, fstatSync } from 'fs';
9
9
  import * as path from 'path';
10
10
  import { join, dirname, resolve, win32, basename } from 'path';
11
11
  import { fileURLToPath, pathToFileURL } from 'url';
12
12
  import { Command } from 'commander';
13
13
  import axios from 'axios';
14
- import { createHash } from 'crypto';
14
+ import { createHash, X509Certificate, verify } from 'crypto';
15
15
  import { platform, homedir, arch, tmpdir, hostname } from 'os';
16
16
  import { execFile, execFileSync, spawnSync, spawn } from 'child_process';
17
17
  import { createInterface } from 'readline/promises';
18
18
  import { Writable } from 'stream';
19
19
  import { pipeline } from 'stream/promises';
20
20
  import { readFile } from 'fs/promises';
21
- import { verify } from 'sigstore';
21
+ import { createVerifier, TUFError } from 'sigstore';
22
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
22
23
 
23
24
  var registeredTools = [];
24
25
  function registerTools(tools) {
@@ -254,8 +255,8 @@ function createUnifiedMcpServer(options) {
254
255
  errors: error.issues
255
256
  });
256
257
  const issueMessages = error.issues.slice(0, 3).map((issue) => {
257
- const path6 = issue.path.join(".");
258
- return path6 ? `'${path6}': ${issue.message}` : issue.message;
258
+ const path7 = issue.path.join(".");
259
+ return path7 ? `'${path7}': ${issue.message}` : issue.message;
259
260
  });
260
261
  return {
261
262
  content: [
@@ -1492,12 +1493,12 @@ var WORKFLOW_WRITING_OUTCOMES = /* @__PURE__ */ new Set([
1492
1493
  "replaced" /* Replaced */
1493
1494
  ]);
1494
1495
  var CI_INSTALL_MESSAGES = {
1495
- ["installed" /* Installed */]: (path6) => `Wrote ${path6}
1496
+ ["installed" /* Installed */]: (path7) => `Wrote ${path7}
1496
1497
  Commit it, and every pull request here will owe a settled Muggle AI walkthrough comment.`,
1497
- ["updated" /* Updated */]: (path6) => `Updated ${path6} from an earlier Muggle release to the current workflow. Commit it.`,
1498
- ["already-current" /* AlreadyCurrent */]: (path6) => `${path6} is already the current workflow \u2014 nothing to do.`,
1499
- ["kept-customized" /* KeptCustomized */]: (path6) => `${path6} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1500
- ["replaced" /* Replaced */]: (path6) => `Replaced ${path6} with the current workflow. Commit it.`,
1498
+ ["updated" /* Updated */]: (path7) => `Updated ${path7} from an earlier Muggle release to the current workflow. Commit it.`,
1499
+ ["already-current" /* AlreadyCurrent */]: (path7) => `${path7} is already the current workflow \u2014 nothing to do.`,
1500
+ ["kept-customized" /* KeptCustomized */]: (path7) => `${path7} has been edited since Muggle wrote it \u2014 left untouched. Re-run with --force to replace it.`,
1501
+ ["replaced" /* Replaced */]: (path7) => `Replaced ${path7} with the current workflow. Commit it.`,
1501
1502
  ["not-a-repository" /* NotARepository */]: () => "Not a git repository \u2014 run this from the repo that should carry the check."
1502
1503
  };
1503
1504
 
@@ -2753,8 +2754,8 @@ ${title}`, COLORS.bold + COLORS.cyan);
2753
2754
  function cmd(cmd2) {
2754
2755
  return colorize(cmd2, COLORS.green);
2755
2756
  }
2756
- function path3(path6) {
2757
- return colorize(path6, COLORS.yellow);
2757
+ function path3(path7) {
2758
+ return colorize(path7, COLORS.yellow);
2758
2759
  }
2759
2760
  function getHelpGuidance() {
2760
2761
  const lines = [
@@ -4153,6 +4154,32 @@ async function serveCommand(options) {
4153
4154
  var SIGNATURE_BUNDLE_SUFFIX = ".sigstore.json";
4154
4155
  var SIGNER_CERTIFICATE_ISSUER = "https://token.actions.githubusercontent.com";
4155
4156
  var SIGNATURE_FETCH_TIMEOUT_MS = 3e4;
4157
+ var SIGNATURE_TRUST_ROOT_HOST = "tuf-repo-cdn.sigstore.dev";
4158
+ var SIGNATURE_VERIFIED_MESSAGE = "Signature verified successfully.";
4159
+ var SIGNATURE_REFUSAL_PREFIX = "Signature verification failed, refusing to install: ";
4160
+ var BUNDLE_DIGEST_ALGORITHM = "SHA2_256";
4161
+ var BUNDLE_HASH_ALGORITHM = "sha256";
4162
+ var CERTIFICATE_URI_SAN_PREFIX = "URI:";
4163
+ var CERTIFICATE_SAN_SEPARATOR = ", ";
4164
+ var TRUST_ROOT_FETCH_ERROR_CODES = /* @__PURE__ */ new Set([
4165
+ "TUF_REFRESH_METADATA_ERROR",
4166
+ "TUF_DOWNLOAD_TARGET_ERROR"
4167
+ ]);
4168
+ var HOST_UNREACHABLE_ERROR_CODES = /* @__PURE__ */ new Set([
4169
+ "ENOTFOUND",
4170
+ "EAI_AGAIN",
4171
+ "ECONNREFUSED",
4172
+ "ECONNRESET",
4173
+ "ETIMEDOUT",
4174
+ "ENETUNREACH",
4175
+ "EHOSTUNREACH",
4176
+ "ENETDOWN",
4177
+ "UND_ERR_CONNECT_TIMEOUT",
4178
+ "UND_ERR_SOCKET"
4179
+ ]);
4180
+ var FETCH_TIMEOUT_ERROR_NAME = "TimeoutError";
4181
+ var FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN = /^Unable to load (?:snapshot metadata|targets) error TimeoutError: The operation was aborted due to timeout$/;
4182
+ var MAX_ERROR_CAUSE_DEPTH = 5;
4156
4183
 
4157
4184
  // scripts/release-integrity/compareVersions.mjs
4158
4185
  function compareVersions2(a, b) {
@@ -4172,10 +4199,12 @@ function compareVersions2(a, b) {
4172
4199
  }
4173
4200
 
4174
4201
  // scripts/release-integrity/resolveIntegrityPolicy.mjs
4202
+ function hasExpectedChecksum(expectedChecksum) {
4203
+ return Boolean(expectedChecksum && expectedChecksum.trim());
4204
+ }
4175
4205
  function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }) {
4176
4206
  const requiresSignature = Boolean(signedFromVersion) && compareVersions2(version, signedFromVersion) >= 0;
4177
- const hasChecksum = Boolean(expectedChecksum && expectedChecksum.trim());
4178
- if (!requiresSignature && !hasChecksum) {
4207
+ if (!requiresSignature && !hasExpectedChecksum(expectedChecksum)) {
4179
4208
  return {
4180
4209
  requiresSignature: false,
4181
4210
  requiresChecksum: false,
@@ -4188,9 +4217,66 @@ function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }
4188
4217
  unverifiableReason: ""
4189
4218
  };
4190
4219
  }
4220
+ function listErrorChain(error) {
4221
+ const chain = [];
4222
+ let current = error;
4223
+ while (current && chain.length < MAX_ERROR_CAUSE_DEPTH) {
4224
+ chain.push(current);
4225
+ current = current.cause;
4226
+ }
4227
+ return chain;
4228
+ }
4229
+ function isTrustRootUnreachable(trustRootError) {
4230
+ if (!(trustRootError instanceof TUFError) || !TRUST_ROOT_FETCH_ERROR_CODES.has(trustRootError.code)) {
4231
+ return false;
4232
+ }
4233
+ return listErrorChain(trustRootError.cause).some(
4234
+ (chainedError) => chainedError.name === FETCH_TIMEOUT_ERROR_NAME || HOST_UNREACHABLE_ERROR_CODES.has(chainedError.code) || FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN.test(chainedError.message ?? "")
4235
+ );
4236
+ }
4237
+ function describeErrorChain(error) {
4238
+ return listErrorChain(error).map((chainedError) => chainedError.message).filter(Boolean).join(": ");
4239
+ }
4240
+ function findBundleMismatch({ bundle, artifactBytes, signerIdentityUri }) {
4241
+ const messageSignature = bundle?.messageSignature;
4242
+ const messageDigest = messageSignature?.messageDigest;
4243
+ const certificateRawBytes = bundle?.verificationMaterial?.certificate?.rawBytes;
4244
+ if (!messageDigest?.digest || !messageSignature?.signature || !certificateRawBytes) {
4245
+ return "the signature bundle is missing its digest, signature or signing certificate";
4246
+ }
4247
+ if (messageDigest.algorithm !== BUNDLE_DIGEST_ALGORITHM) {
4248
+ return `the signature bundle uses an unexpected digest algorithm: ${messageDigest.algorithm}`;
4249
+ }
4250
+ const artifactDigest = createHash(BUNDLE_HASH_ALGORITHM).update(artifactBytes).digest();
4251
+ if (!artifactDigest.equals(Buffer.from(messageDigest.digest, "base64"))) {
4252
+ return "the download does not match the digest recorded in its signature bundle";
4253
+ }
4254
+ try {
4255
+ const signingCertificate = new X509Certificate(Buffer.from(certificateRawBytes, "base64"));
4256
+ const certificateNames = (signingCertificate.subjectAltName ?? "").split(CERTIFICATE_SAN_SEPARATOR);
4257
+ if (!certificateNames.includes(`${CERTIFICATE_URI_SAN_PREFIX}${signerIdentityUri}`)) {
4258
+ return `the signing certificate was not issued to ${signerIdentityUri}`;
4259
+ }
4260
+ const isSignatureMatching = verify(
4261
+ BUNDLE_HASH_ALGORITHM,
4262
+ artifactBytes,
4263
+ signingCertificate.publicKey,
4264
+ Buffer.from(messageSignature.signature, "base64")
4265
+ );
4266
+ return isSignatureMatching ? "" : "the signature in the bundle does not match the download";
4267
+ } catch (error) {
4268
+ return `the signature bundle could not be read: ${error.message}`;
4269
+ }
4270
+ }
4271
+
4272
+ // scripts/release-integrity/verifyReleaseSignature.mjs
4191
4273
  async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityUri }) {
4192
4274
  if (!signerIdentityUri) {
4193
- return { valid: false, reason: "no signer identity is configured to verify against" };
4275
+ return {
4276
+ valid: false,
4277
+ reason: "no signer identity is configured to verify against",
4278
+ isTrustRootUnreachable: false
4279
+ };
4194
4280
  }
4195
4281
  const controller = new AbortController();
4196
4282
  const timer = setTimeout(() => controller.abort(), SIGNATURE_FETCH_TIMEOUT_MS);
@@ -4200,23 +4286,161 @@ async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityU
4200
4286
  if (!response.ok) {
4201
4287
  return {
4202
4288
  valid: false,
4203
- reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`
4289
+ reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`,
4290
+ isTrustRootUnreachable: false
4204
4291
  };
4205
4292
  }
4206
4293
  bundle = await response.json();
4207
4294
  } catch (error) {
4208
- return { valid: false, reason: `could not fetch signature bundle: ${error.message}` };
4295
+ return {
4296
+ valid: false,
4297
+ reason: `could not fetch signature bundle: ${error.message}`,
4298
+ isTrustRootUnreachable: false
4299
+ };
4209
4300
  } finally {
4210
4301
  clearTimeout(timer);
4211
4302
  }
4303
+ let artifactBytes;
4304
+ try {
4305
+ artifactBytes = await readFile(artifactPath);
4306
+ } catch (error) {
4307
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4308
+ }
4309
+ let bundleVerifier;
4212
4310
  try {
4213
- await verify(bundle, await readFile(artifactPath), {
4311
+ bundleVerifier = await createVerifier({
4214
4312
  certificateIssuer: SIGNER_CERTIFICATE_ISSUER,
4215
4313
  certificateIdentityURI: signerIdentityUri
4216
4314
  });
4217
- return { valid: true, reason: "" };
4218
4315
  } catch (error) {
4219
- return { valid: false, reason: error.message };
4316
+ const failureDescription = describeErrorChain(error);
4317
+ if (!isTrustRootUnreachable(error)) {
4318
+ return {
4319
+ valid: false,
4320
+ reason: `could not load the trust root from ${SIGNATURE_TRUST_ROOT_HOST}: ${failureDescription}`,
4321
+ isTrustRootUnreachable: false
4322
+ };
4323
+ }
4324
+ const bundleMismatch = findBundleMismatch({
4325
+ bundle,
4326
+ artifactBytes,
4327
+ signerIdentityUri
4328
+ });
4329
+ return {
4330
+ valid: false,
4331
+ reason: bundleMismatch || failureDescription,
4332
+ isTrustRootUnreachable: !bundleMismatch
4333
+ };
4334
+ }
4335
+ try {
4336
+ bundleVerifier.verify(bundle, artifactBytes);
4337
+ return { valid: true, reason: "", isTrustRootUnreachable: false };
4338
+ } catch (error) {
4339
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
4340
+ }
4341
+ }
4342
+
4343
+ // scripts/release-integrity/enforceReleaseSignature.mjs
4344
+ async function enforceReleaseSignature({
4345
+ artifactPath,
4346
+ bundleUrl,
4347
+ signerIdentityUri,
4348
+ expectedChecksum,
4349
+ logInfo,
4350
+ logWarning
4351
+ }) {
4352
+ const signatureOutcome = await verifyReleaseSignature({
4353
+ artifactPath,
4354
+ bundleUrl,
4355
+ signerIdentityUri
4356
+ });
4357
+ if (signatureOutcome.valid) {
4358
+ logInfo(SIGNATURE_VERIFIED_MESSAGE);
4359
+ return { isSignatureVerified: true };
4360
+ }
4361
+ if (!signatureOutcome.isTrustRootUnreachable) {
4362
+ throw new Error(SIGNATURE_REFUSAL_PREFIX + signatureOutcome.reason);
4363
+ }
4364
+ const networkFailure = `a network failure kept ${SIGNATURE_TRUST_ROOT_HOST} out of reach (${signatureOutcome.reason})`;
4365
+ if (!hasExpectedChecksum(expectedChecksum)) {
4366
+ throw new Error(`${SIGNATURE_REFUSAL_PREFIX}${networkFailure}, and no checksum is available to check instead.`);
4367
+ }
4368
+ logWarning(
4369
+ `WARNING: The signature was NOT verified: ${networkFailure}. Falling back to the checksum check only.`
4370
+ );
4371
+ return { isSignatureVerified: false };
4372
+ }
4373
+
4374
+ // src/cli/studio-install-staging-constants.ts
4375
+ var STUDIO_STAGING_DIR_NAME = "studio-stage";
4376
+ var RETIRED_INSTALL_SUFFIX = ".retired";
4377
+ var INSTALL_MOVE_MAX_ATTEMPTS = 10;
4378
+ var INSTALL_MOVE_RETRY_DELAY_MS = 500;
4379
+ var INSTALL_MOVE_RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
4380
+
4381
+ // src/cli/studio-install-staging.ts
4382
+ function getStudioStagingDir(versionDir) {
4383
+ return path.join(getDataDir2(), STUDIO_STAGING_DIR_NAME, path.basename(versionDir));
4384
+ }
4385
+ function getRetiredInstallDir(stagingDir) {
4386
+ return `${stagingDir}${RETIRED_INSTALL_SUFFIX}`;
4387
+ }
4388
+ function prepareStudioStagingDir(params) {
4389
+ const { stagingDir, versionDir } = params;
4390
+ const retiredDir = getRetiredInstallDir(stagingDir);
4391
+ if (existsSync(retiredDir) && !existsSync(versionDir)) {
4392
+ renameSync(retiredDir, versionDir);
4393
+ }
4394
+ rmSync(stagingDir, { recursive: true, force: true });
4395
+ rmSync(retiredDir, { recursive: true, force: true });
4396
+ mkdirSync(stagingDir, { recursive: true });
4397
+ }
4398
+ function discardStudioStagingDir(stagingDir) {
4399
+ try {
4400
+ rmSync(stagingDir, { recursive: true, force: true });
4401
+ } catch {
4402
+ }
4403
+ }
4404
+ async function moveDirectory(fromDir, toDir) {
4405
+ for (let attempt = 1; ; attempt++) {
4406
+ try {
4407
+ renameSync(fromDir, toDir);
4408
+ return;
4409
+ } catch (error) {
4410
+ const errorCode = error.code ?? "";
4411
+ if (attempt >= INSTALL_MOVE_MAX_ATTEMPTS || !INSTALL_MOVE_RETRYABLE_ERROR_CODES.has(errorCode)) {
4412
+ throw error;
4413
+ }
4414
+ await setTimeout$1(INSTALL_MOVE_RETRY_DELAY_MS);
4415
+ }
4416
+ }
4417
+ }
4418
+ async function replaceStudioInstall(params) {
4419
+ const { stagingDir, versionDir } = params;
4420
+ mkdirSync(path.dirname(versionDir), { recursive: true });
4421
+ if (!existsSync(versionDir)) {
4422
+ await moveDirectory(stagingDir, versionDir);
4423
+ return;
4424
+ }
4425
+ const retiredDir = getRetiredInstallDir(stagingDir);
4426
+ try {
4427
+ await moveDirectory(versionDir, retiredDir);
4428
+ } catch (error) {
4429
+ const errorMessage = error instanceof Error ? error.message : String(error);
4430
+ throw new Error(
4431
+ `Could not replace the install at ${versionDir}, which may be in use. It was left as it was: ${errorMessage}`,
4432
+ { cause: error }
4433
+ );
4434
+ }
4435
+ try {
4436
+ await moveDirectory(stagingDir, versionDir);
4437
+ } catch (error) {
4438
+ await moveDirectory(retiredDir, versionDir);
4439
+ throw error;
4440
+ }
4441
+ try {
4442
+ rmSync(retiredDir, { recursive: true, force: true });
4443
+ } catch {
4220
4444
  }
4221
4445
  }
4222
4446
 
@@ -4324,14 +4548,6 @@ function writeInstallMetadata(params) {
4324
4548
  writeFileSync(params.metadataPath, `${JSON.stringify(metadata, null, 2)}
4325
4549
  `, "utf-8");
4326
4550
  }
4327
- function cleanupFailedInstall(versionDir) {
4328
- if (existsSync(versionDir)) {
4329
- try {
4330
- rmSync(versionDir, { recursive: true, force: true });
4331
- } catch {
4332
- }
4333
- }
4334
- }
4335
4551
  function upsertCursorMcpConfig() {
4336
4552
  const cursorMcpConfigPath = path.join(homedir(), ".cursor", "mcp.json");
4337
4553
  const cursorDir = path.join(homedir(), ".cursor");
@@ -4392,12 +4608,10 @@ async function setupCommand(options) {
4392
4608
  });
4393
4609
  console.log(`Downloading Muggle Test Electron app v${version}...`);
4394
4610
  console.log(`URL: ${downloadUrl}`);
4611
+ const stagingDir = getStudioStagingDir(versionDir);
4395
4612
  try {
4396
- if (existsSync(versionDir)) {
4397
- rmSync(versionDir, { recursive: true, force: true });
4398
- }
4399
- mkdirSync(versionDir, { recursive: true });
4400
- const tempFile = path.join(versionDir, binaryName);
4613
+ prepareStudioStagingDir({ stagingDir, versionDir });
4614
+ const tempFile = path.join(stagingDir, binaryName);
4401
4615
  await downloadWithRetry(downloadUrl, tempFile);
4402
4616
  console.log("Download complete, verifying integrity...");
4403
4617
  const checksums = getElectronAppChecksums();
@@ -4408,24 +4622,23 @@ async function setupCommand(options) {
4408
4622
  expectedChecksum: expectedChecksum ?? ""
4409
4623
  });
4410
4624
  if (integrityPolicy.unverifiableReason) {
4411
- cleanupFailedInstall(versionDir);
4412
4625
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4413
4626
  }
4627
+ let isSignatureVerified = false;
4414
4628
  if (integrityPolicy.requiresSignature) {
4415
- const signatureResult = await verifyReleaseSignature({
4629
+ const signatureEnforcement = await enforceReleaseSignature({
4416
4630
  artifactPath: tempFile,
4417
4631
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4418
- signerIdentityUri: getReleaseSignerIdentityUri()
4632
+ signerIdentityUri: getReleaseSignerIdentityUri(),
4633
+ expectedChecksum: expectedChecksum ?? "",
4634
+ logInfo: console.log,
4635
+ logWarning: console.warn
4419
4636
  });
4420
- if (!signatureResult.valid) {
4421
- cleanupFailedInstall(versionDir);
4422
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4423
- }
4424
- console.log("Signature verified successfully.");
4637
+ isSignatureVerified = signatureEnforcement.isSignatureVerified;
4425
4638
  }
4426
4639
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum);
4427
4640
  if (!checksumResult.valid && expectedChecksum) {
4428
- if (!integrityPolicy.requiresChecksum) {
4641
+ if (isSignatureVerified) {
4429
4642
  console.warn(
4430
4643
  `Pinned checksum does not match this download, but its signature verified.
4431
4644
  Expected: ${checksumResult.expected}
@@ -4433,7 +4646,6 @@ Actual: ${checksumResult.actual}
4433
4646
  The pin in package.json muggleConfig.checksumsByStream is stale for this release; continuing on the signature.`
4434
4647
  );
4435
4648
  } else {
4436
- cleanupFailedInstall(versionDir);
4437
4649
  throw new Error(
4438
4650
  `Checksum verification failed!
4439
4651
  Expected: ${checksumResult.expected}
@@ -4447,13 +4659,12 @@ The downloaded file may be corrupted or tampered with.`
4447
4659
  }
4448
4660
  console.log("Extracting...");
4449
4661
  if (binaryName.endsWith(".zip")) {
4450
- await extractZip(tempFile, versionDir);
4662
+ await extractZip(tempFile, stagingDir);
4451
4663
  } else if (binaryName.endsWith(".tar.gz")) {
4452
- await extractTarGz(tempFile, versionDir);
4664
+ await extractTarGz(tempFile, stagingDir);
4453
4665
  }
4454
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
4666
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4455
4667
  if (!existsSync(executablePath)) {
4456
- cleanupFailedInstall(versionDir);
4457
4668
  throw new Error(
4458
4669
  `Extraction failed: executable not found at expected path.
4459
4670
  Expected: ${executablePath}
@@ -4461,7 +4672,7 @@ The archive may be corrupted or in an unexpected format.`
4461
4672
  );
4462
4673
  }
4463
4674
  const executableChecksum = await calculateFileChecksum(executablePath);
4464
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME);
4675
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME);
4465
4676
  writeInstallMetadata({
4466
4677
  metadataPath,
4467
4678
  version,
@@ -4471,9 +4682,11 @@ The archive may be corrupted or in an unexpected format.`
4471
4682
  expectedArchiveChecksum: expectedChecksum
4472
4683
  });
4473
4684
  rmSync(tempFile, { force: true });
4685
+ await replaceStudioInstall({ stagingDir, versionDir });
4474
4686
  console.log(`Electron app installed to ${versionDir}`);
4475
4687
  logger6.info("Setup complete", { version, path: versionDir });
4476
4688
  } catch (error) {
4689
+ discardStudioStagingDir(stagingDir);
4477
4690
  const errorMessage = error instanceof Error ? error.message : String(error);
4478
4691
  console.error(`Failed to download Electron app: ${errorMessage}`);
4479
4692
  logger6.error("Setup failed", { error: errorMessage });
@@ -4773,21 +4986,15 @@ async function fetchChecksumFromRelease(version) {
4773
4986
  return "";
4774
4987
  }
4775
4988
  }
4776
- async function downloadAndInstall(version, downloadUrl, checksum) {
4777
- const versionDir = getElectronAppDir(version);
4989
+ async function stageVerifiedDownload(params) {
4990
+ const { version, downloadUrl, checksum, stagingDir } = params;
4778
4991
  const binaryName = getBinaryName2();
4779
4992
  const platformKey = getPlatformKey();
4780
- console.log(`Downloading Muggle Test Electron app v${version}...`);
4781
- console.log(`URL: ${downloadUrl}`);
4782
- if (existsSync(versionDir)) {
4783
- rmSync(versionDir, { recursive: true, force: true });
4784
- }
4785
- mkdirSync(versionDir, { recursive: true });
4786
4993
  const response = await fetch(downloadUrl);
4787
4994
  if (!response.ok) {
4788
4995
  throw new Error(`Download failed: ${response.status} ${response.statusText}`);
4789
4996
  }
4790
- const tempFile = path.join(versionDir, binaryName);
4997
+ const tempFile = path.join(stagingDir, binaryName);
4791
4998
  const fileStream = createWriteStream(tempFile);
4792
4999
  if (!response.body) {
4793
5000
  throw new Error("No response body");
@@ -4804,24 +5011,20 @@ async function downloadAndInstall(version, downloadUrl, checksum) {
4804
5011
  expectedChecksum: expectedChecksum ?? ""
4805
5012
  });
4806
5013
  if (integrityPolicy.unverifiableReason) {
4807
- rmSync(versionDir, { recursive: true, force: true });
4808
5014
  throw new Error("Refusing to install an unverifiable download: " + integrityPolicy.unverifiableReason);
4809
5015
  }
4810
5016
  if (integrityPolicy.requiresSignature) {
4811
- const signatureResult = await verifyReleaseSignature({
5017
+ await enforceReleaseSignature({
4812
5018
  artifactPath: tempFile,
4813
5019
  bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
4814
- signerIdentityUri: getReleaseSignerIdentityUri()
5020
+ signerIdentityUri: getReleaseSignerIdentityUri(),
5021
+ expectedChecksum: expectedChecksum ?? "",
5022
+ logInfo: console.log,
5023
+ logWarning: console.warn
4815
5024
  });
4816
- if (!signatureResult.valid) {
4817
- rmSync(versionDir, { recursive: true, force: true });
4818
- throw new Error("Signature verification failed, refusing to install: " + signatureResult.reason);
4819
- }
4820
- console.log("Signature verified successfully.");
4821
5025
  }
4822
5026
  const checksumResult = await verifyFileChecksum(tempFile, expectedChecksum || "");
4823
5027
  if (!checksumResult.valid && expectedChecksum) {
4824
- rmSync(versionDir, { recursive: true, force: true });
4825
5028
  throw new Error(
4826
5029
  `Checksum verification failed!
4827
5030
  Expected: ${checksumResult.expected}
@@ -4834,13 +5037,12 @@ The downloaded file may be corrupted or tampered with.`
4834
5037
  }
4835
5038
  console.log("Extracting...");
4836
5039
  if (binaryName.endsWith(".zip")) {
4837
- await extractZip2(tempFile, versionDir);
5040
+ await extractZip2(tempFile, stagingDir);
4838
5041
  } else if (binaryName.endsWith(".tar.gz")) {
4839
- await extractTarGz2(tempFile, versionDir);
5042
+ await extractTarGz2(tempFile, stagingDir);
4840
5043
  }
4841
- const executablePath = resolveElectronAppExecutablePath({ installDir: versionDir, platformName: platform() });
5044
+ const executablePath = resolveElectronAppExecutablePath({ installDir: stagingDir, platformName: platform() });
4842
5045
  if (!existsSync(executablePath)) {
4843
- rmSync(versionDir, { recursive: true, force: true });
4844
5046
  throw new Error(
4845
5047
  `Extraction failed: executable not found at expected path.
4846
5048
  Expected: ${executablePath}
@@ -4848,7 +5050,7 @@ The archive may be corrupted or in an unexpected format.`
4848
5050
  );
4849
5051
  }
4850
5052
  const executableChecksum = await calculateFileChecksum(executablePath);
4851
- const metadataPath = path.join(versionDir, INSTALL_METADATA_FILE_NAME2);
5053
+ const metadataPath = path.join(stagingDir, INSTALL_METADATA_FILE_NAME2);
4852
5054
  writeInstallMetadata2({
4853
5055
  metadataPath,
4854
5056
  version,
@@ -4858,6 +5060,25 @@ The archive may be corrupted or in an unexpected format.`
4858
5060
  expectedArchiveChecksum: expectedChecksum || ""
4859
5061
  });
4860
5062
  rmSync(tempFile, { force: true });
5063
+ }
5064
+ async function downloadAndInstall(version, downloadUrl, checksum) {
5065
+ const versionDir = getElectronAppDir(version);
5066
+ const stagingDir = getStudioStagingDir(versionDir);
5067
+ console.log(`Downloading Muggle Test Electron app v${version}...`);
5068
+ console.log(`URL: ${downloadUrl}`);
5069
+ try {
5070
+ prepareStudioStagingDir({ stagingDir, versionDir });
5071
+ await stageVerifiedDownload({
5072
+ version,
5073
+ downloadUrl,
5074
+ checksum,
5075
+ stagingDir
5076
+ });
5077
+ await replaceStudioInstall({ stagingDir, versionDir });
5078
+ } catch (error) {
5079
+ discardStudioStagingDir(stagingDir);
5080
+ throw error;
5081
+ }
4861
5082
  saveVersionOverride(version);
4862
5083
  console.log(`Electron app v${version} installed to ${versionDir}`);
4863
5084
  logger7.info("Upgrade complete", { version, path: versionDir });
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { runCli } from './chunk-AKEZHBGS.js';
2
+ import { runCli } from './chunk-TVA5J73U.js';
3
3
  import './chunk-SMUHQITB.js';
4
4
 
5
5
  // src/cli/main.ts
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-AKEZHBGS.js';
1
+ export { src_exports as commands, createUnifiedMcpServer, server_exports as server } from './chunk-TVA5J73U.js';
2
2
  export { createChildLogger, e2e_exports as e2e, getConfig, getLocalQaTools, getLogger, getQaTools, local_exports as localQa, mcp_exports as mcp, e2e_exports as qa, src_exports as shared } from './chunk-SMUHQITB.js';
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.34.0-staging.309",
4
+ "version": "5.34.0-staging.310",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.34.0-staging.309",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.34.0-staging.309",
3
+ "version": "5.34.0-staging.310",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.34.0-staging.309",
5
+ "version": "5.34.0-staging.310",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.34.0-staging.309",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release": "5.34.0-staging.309",
3
- "buildId": "run-309-1",
4
- "commitSha": "e8afe5dda5751c7634796688ab54e5614ee527fa",
5
- "buildTime": "2026-11-05T19:11:37Z",
2
+ "release": "5.34.0-staging.310",
3
+ "buildId": "run-310-1",
4
+ "commitSha": "8357ccb201eb2959719b07ba87cedd1967b3bee4",
5
+ "buildTime": "2026-11-05T22:51:37Z",
6
6
  "serviceName": "muggle-ai-works-mcp"
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@muggleai/works",
3
3
  "mcpName": "io.github.multiplex-ai/muggle",
4
- "version": "5.34.0-staging.309",
4
+ "version": "5.34.0-staging.310",
5
5
  "description": "13 years of Microsoft hyperscale engineering, packaged as a harness for your AI coding agent.",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.34.0-staging.309",
4
+ "version": "5.34.0-staging.310",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.34.0-staging.309",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.34.0-staging.309",
3
+ "version": "5.34.0-staging.310",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.34.0-staging.309",
5
+ "version": "5.34.0-staging.310",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
package/plugin/.mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.34.0-staging.309",
7
+ "@muggleai/works@5.34.0-staging.310",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -36,8 +36,8 @@ import { clearUpgradeNoticeCache } from "./upgrade-notice-cache.mjs";
36
36
  import { listRunningInstallDirectoryNames, normalizeInstallDirectoryName } from "./running-studio-installs.mjs";
37
37
  import {
38
38
  SIGNATURE_BUNDLE_SUFFIX,
39
+ enforceReleaseSignature,
39
40
  resolveIntegrityPolicy,
40
- verifyReleaseSignature,
41
41
  } from "./release-integrity/index.mjs";
42
42
  import { buildPostInstallGuide, showPostInstallGuide } from "./post-install-guide/index.mjs";
43
43
 
@@ -814,20 +814,19 @@ async function downloadElectronApp() {
814
814
  }
815
815
 
816
816
  if (integrityPolicy.requiresSignature) {
817
- const signatureResult = await verifyReleaseSignature({
818
- artifactPath: tempFile,
819
- bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
820
- signerIdentityUri: config.signerIdentityUri || "",
821
- });
822
-
823
- if (!signatureResult.valid) {
817
+ try {
818
+ await enforceReleaseSignature({
819
+ artifactPath: tempFile,
820
+ bundleUrl: downloadUrl + SIGNATURE_BUNDLE_SUFFIX,
821
+ signerIdentityUri: config.signerIdentityUri || "",
822
+ expectedChecksum: expectedChecksum,
823
+ logInfo: log,
824
+ logWarning: log,
825
+ });
826
+ } catch (error) {
824
827
  rmSync(versionDir, { recursive: true, force: true });
825
- throw new Error(
826
- "Signature verification failed, refusing to install: " + signatureResult.reason,
827
- );
828
+ throw error;
828
829
  }
829
-
830
- log("Signature verified successfully.");
831
830
  }
832
831
 
833
832
  // Verify checksum
@@ -0,0 +1,67 @@
1
+ import { TUFError } from "sigstore";
2
+ import {
3
+ FETCH_TIMEOUT_ERROR_NAME,
4
+ FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN,
5
+ HOST_UNREACHABLE_ERROR_CODES,
6
+ MAX_ERROR_CAUSE_DEPTH,
7
+ TRUST_ROOT_FETCH_ERROR_CODES,
8
+ } from "./constants.mjs";
9
+
10
+ /**
11
+ * List an error and its causes, outermost first.
12
+ *
13
+ * @param {unknown} error - The outermost error.
14
+ * @returns {Array<{name?: string, code?: unknown, message?: string, cause?: unknown}>} The chain, cut off at the depth limit.
15
+ */
16
+ function listErrorChain(error) {
17
+ const chain = [];
18
+ let current = error;
19
+
20
+ while (current && chain.length < MAX_ERROR_CAUSE_DEPTH) {
21
+ chain.push(current);
22
+ current = current.cause;
23
+ }
24
+
25
+ return chain;
26
+ }
27
+
28
+ /**
29
+ * Decide whether a failed trust-root load means the host could not be reached.
30
+ *
31
+ * Only pass an error from loading the trust root: that step never reads the bundle,
32
+ * so nothing a bundle contains can reach this decision. Anything not positively
33
+ * recognised as a network failure is false, which refuses the install. TLS failures,
34
+ * HTTP statuses, invalid TUF metadata and file system errors are all false, because
35
+ * in each the host answered or the failure is local.
36
+ *
37
+ * @param {unknown} trustRootError - What loading the trust root rejected with.
38
+ * @returns {boolean} True only for a recognised network failure reaching the host.
39
+ */
40
+ export function isTrustRootUnreachable(trustRootError) {
41
+ if (!(trustRootError instanceof TUFError) || !TRUST_ROOT_FETCH_ERROR_CODES.has(trustRootError.code)) {
42
+ return false;
43
+ }
44
+
45
+ return listErrorChain(trustRootError.cause).some(
46
+ (chainedError) =>
47
+ chainedError.name === FETCH_TIMEOUT_ERROR_NAME ||
48
+ HOST_UNREACHABLE_ERROR_CODES.has(chainedError.code) ||
49
+ FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN.test(chainedError.message ?? ""),
50
+ );
51
+ }
52
+
53
+ /**
54
+ * Render an error and its causes as one line, since the outermost TUF message alone
55
+ * never says what went wrong.
56
+ *
57
+ * @param {unknown} error - The outermost error.
58
+ * @returns {string} Every message in the chain, outermost first.
59
+ *
60
+ * Output shape: `"error refreshing TUF metadata: fetch failed: getaddrinfo ENOTFOUND tuf-repo-cdn.sigstore.dev"`
61
+ */
62
+ export function describeErrorChain(error) {
63
+ return listErrorChain(error)
64
+ .map((chainedError) => chainedError.message)
65
+ .filter(Boolean)
66
+ .join(": ");
67
+ }
@@ -6,3 +6,58 @@ export const SIGNER_CERTIFICATE_ISSUER = "https://token.actions.githubuserconten
6
6
 
7
7
  /** Abort budget for fetching a signature bundle. */
8
8
  export const SIGNATURE_FETCH_TIMEOUT_MS = 30_000;
9
+
10
+ /** Host every signature check reads the Sigstore trust root from. */
11
+ export const SIGNATURE_TRUST_ROOT_HOST = "tuf-repo-cdn.sigstore.dev";
12
+
13
+ /** Printed once a download's signature has been proven. */
14
+ export const SIGNATURE_VERIFIED_MESSAGE = "Signature verified successfully.";
15
+
16
+ /** Opens every signature refusal, ahead of the cause. */
17
+ export const SIGNATURE_REFUSAL_PREFIX = "Signature verification failed, refusing to install: ";
18
+
19
+ /** Digest algorithm release bundles record, as the bundle spells it. */
20
+ export const BUNDLE_DIGEST_ALGORITHM = "SHA2_256";
21
+
22
+ /** The same digest algorithm, as node:crypto spells it. */
23
+ export const BUNDLE_HASH_ALGORITHM = "sha256";
24
+
25
+ /** Prefix an X.509 subject alternative name carries when it holds a URI. */
26
+ export const CERTIFICATE_URI_SAN_PREFIX = "URI:";
27
+
28
+ /** Separator between the entries of a certificate's subject alternative name. */
29
+ export const CERTIFICATE_SAN_SEPARATOR = ", ";
30
+
31
+ /** TUF client failures that mean a fetch went wrong, not that a file on disk did. */
32
+ export const TRUST_ROOT_FETCH_ERROR_CODES = new Set([
33
+ "TUF_REFRESH_METADATA_ERROR",
34
+ "TUF_DOWNLOAD_TARGET_ERROR",
35
+ ]);
36
+
37
+ /** Socket and resolver failures that show no HTTP exchange with the host ever happened. */
38
+ export const HOST_UNREACHABLE_ERROR_CODES = new Set([
39
+ "ENOTFOUND",
40
+ "EAI_AGAIN",
41
+ "ECONNREFUSED",
42
+ "ECONNRESET",
43
+ "ETIMEDOUT",
44
+ "ENETUNREACH",
45
+ "EHOSTUNREACH",
46
+ "ENETDOWN",
47
+ "UND_ERR_CONNECT_TIMEOUT",
48
+ "UND_ERR_SOCKET",
49
+ ]);
50
+
51
+ /** Name of the error an elapsed abort signal rejects a fetch with. */
52
+ export const FETCH_TIMEOUT_ERROR_NAME = "TimeoutError";
53
+
54
+ /**
55
+ * Whole message of a timeout the TUF client caught mid-refresh and flattened to text,
56
+ * leaving no type to read. `fetch failed` flattens the same way, but is left out on
57
+ * purpose: as text it cannot be told from a TLS failure.
58
+ */
59
+ export const FLATTENED_TRUST_ROOT_TIMEOUT_PATTERN =
60
+ /^Unable to load (?:snapshot metadata|targets) error TimeoutError: The operation was aborted due to timeout$/;
61
+
62
+ /** Links followed through an error's causes; a cycle must not hang an install. */
63
+ export const MAX_ERROR_CAUSE_DEPTH = 5;
@@ -0,0 +1,62 @@
1
+ import {
2
+ SIGNATURE_REFUSAL_PREFIX,
3
+ SIGNATURE_TRUST_ROOT_HOST,
4
+ SIGNATURE_VERIFIED_MESSAGE,
5
+ } from "./constants.mjs";
6
+ import { hasExpectedChecksum } from "./resolveIntegrityPolicy.mjs";
7
+ import { verifyReleaseSignature } from "./verifyReleaseSignature.mjs";
8
+
9
+ /**
10
+ * Hold a download to its signature, the same way on every install path.
11
+ *
12
+ * A signature that fails refuses. The one exception is a trust root the network kept
13
+ * out of reach: then nothing was proven either way, so the caller warns and the
14
+ * checksum decides. That needs a checksum to exist, so with none the download refuses.
15
+ * Callers must treat a checksum mismatch as fatal whenever `isSignatureVerified` is false.
16
+ *
17
+ * @param {object} params - Enforcement inputs.
18
+ * @param {string} params.artifactPath - Path to the downloaded asset.
19
+ * @param {string} params.bundleUrl - URL of the asset's Sigstore bundle.
20
+ * @param {string} params.signerIdentityUri - Certificate subject the signer must carry.
21
+ * @param {string} params.expectedChecksum - SHA256 the fallback would check, empty when none.
22
+ * @param {(message: string) => void} params.logInfo - Writes a progress line.
23
+ * @param {(message: string) => void} params.logWarning - Writes a warning.
24
+ * @returns {Promise<{isSignatureVerified: boolean}>} Whether the signature was proven.
25
+ * @throws {Error} When the download must not be installed.
26
+ */
27
+ export async function enforceReleaseSignature({
28
+ artifactPath,
29
+ bundleUrl,
30
+ signerIdentityUri,
31
+ expectedChecksum,
32
+ logInfo,
33
+ logWarning,
34
+ }) {
35
+ const signatureOutcome = await verifyReleaseSignature({
36
+ artifactPath: artifactPath,
37
+ bundleUrl: bundleUrl,
38
+ signerIdentityUri: signerIdentityUri,
39
+ });
40
+
41
+ if (signatureOutcome.valid) {
42
+ logInfo(SIGNATURE_VERIFIED_MESSAGE);
43
+ return { isSignatureVerified: true };
44
+ }
45
+
46
+ if (!signatureOutcome.isTrustRootUnreachable) {
47
+ throw new Error(SIGNATURE_REFUSAL_PREFIX + signatureOutcome.reason);
48
+ }
49
+
50
+ const networkFailure =
51
+ `a network failure kept ${SIGNATURE_TRUST_ROOT_HOST} out of reach (${signatureOutcome.reason})`;
52
+
53
+ if (!hasExpectedChecksum(expectedChecksum)) {
54
+ throw new Error(`${SIGNATURE_REFUSAL_PREFIX}${networkFailure}, and no checksum is available to check instead.`);
55
+ }
56
+
57
+ logWarning(
58
+ `WARNING: The signature was NOT verified: ${networkFailure}. ` +
59
+ `Falling back to the checksum check only.`,
60
+ );
61
+ return { isSignatureVerified: false };
62
+ }
@@ -0,0 +1,58 @@
1
+ import { X509Certificate, createHash, verify as verifyMessageSignature } from "node:crypto";
2
+ import {
3
+ BUNDLE_DIGEST_ALGORITHM,
4
+ BUNDLE_HASH_ALGORITHM,
5
+ CERTIFICATE_SAN_SEPARATOR,
6
+ CERTIFICATE_URI_SAN_PREFIX,
7
+ } from "./constants.mjs";
8
+
9
+ /**
10
+ * Check a bundle against a download without the trust root.
11
+ *
12
+ * This proves nothing about who signed: with no trust root the certificate chain
13
+ * cannot be checked. It only catches a bundle that shows on its own that it is not
14
+ * what was signed, so a blocked host cannot wave those through to the checksum.
15
+ *
16
+ * @param {object} params - Check inputs.
17
+ * @param {object} params.bundle - Parsed Sigstore bundle.
18
+ * @param {Buffer} params.artifactBytes - The downloaded asset.
19
+ * @param {string} params.signerIdentityUri - Certificate subject the signer must carry.
20
+ * @returns {string} Why the bundle cannot be for this download, empty when nothing shows that.
21
+ */
22
+ export function findBundleMismatch({ bundle, artifactBytes, signerIdentityUri }) {
23
+ const messageSignature = bundle?.messageSignature;
24
+ const messageDigest = messageSignature?.messageDigest;
25
+ const certificateRawBytes = bundle?.verificationMaterial?.certificate?.rawBytes;
26
+
27
+ if (!messageDigest?.digest || !messageSignature?.signature || !certificateRawBytes) {
28
+ return "the signature bundle is missing its digest, signature or signing certificate";
29
+ }
30
+
31
+ if (messageDigest.algorithm !== BUNDLE_DIGEST_ALGORITHM) {
32
+ return `the signature bundle uses an unexpected digest algorithm: ${messageDigest.algorithm}`;
33
+ }
34
+
35
+ const artifactDigest = createHash(BUNDLE_HASH_ALGORITHM).update(artifactBytes).digest();
36
+ if (!artifactDigest.equals(Buffer.from(messageDigest.digest, "base64"))) {
37
+ return "the download does not match the digest recorded in its signature bundle";
38
+ }
39
+
40
+ try {
41
+ const signingCertificate = new X509Certificate(Buffer.from(certificateRawBytes, "base64"));
42
+ const certificateNames = (signingCertificate.subjectAltName ?? "").split(CERTIFICATE_SAN_SEPARATOR);
43
+
44
+ if (!certificateNames.includes(`${CERTIFICATE_URI_SAN_PREFIX}${signerIdentityUri}`)) {
45
+ return `the signing certificate was not issued to ${signerIdentityUri}`;
46
+ }
47
+
48
+ const isSignatureMatching = verifyMessageSignature(
49
+ BUNDLE_HASH_ALGORITHM,
50
+ artifactBytes,
51
+ signingCertificate.publicKey,
52
+ Buffer.from(messageSignature.signature, "base64"),
53
+ );
54
+ return isSignatureMatching ? "" : "the signature in the bundle does not match the download";
55
+ } catch (error) {
56
+ return `the signature bundle could not be read: ${error.message}`;
57
+ }
58
+ }
@@ -4,6 +4,15 @@ export declare const SIGNER_CERTIFICATE_ISSUER: string;
4
4
 
5
5
  export declare function compareVersions(a: string, b: string): number;
6
6
 
7
+ export declare function enforceReleaseSignature(params: {
8
+ artifactPath: string;
9
+ bundleUrl: string;
10
+ signerIdentityUri: string;
11
+ expectedChecksum: string;
12
+ logInfo: (message: string) => void;
13
+ logWarning: (message: string) => void;
14
+ }): Promise<{ isSignatureVerified: boolean }>;
15
+
7
16
  export declare function resolveIntegrityPolicy(params: {
8
17
  version: string;
9
18
  signedFromVersion: string;
@@ -18,4 +27,4 @@ export declare function verifyReleaseSignature(params: {
18
27
  artifactPath: string;
19
28
  bundleUrl: string;
20
29
  signerIdentityUri: string;
21
- }): Promise<{ valid: boolean; reason: string }>;
30
+ }): Promise<{ valid: boolean; reason: string; isTrustRootUnreachable: boolean }>;
@@ -1,4 +1,5 @@
1
1
  export { SIGNATURE_BUNDLE_SUFFIX, SIGNATURE_FETCH_TIMEOUT_MS, SIGNER_CERTIFICATE_ISSUER } from "./constants.mjs";
2
2
  export { compareVersions } from "./compareVersions.mjs";
3
+ export { enforceReleaseSignature } from "./enforceReleaseSignature.mjs";
3
4
  export { resolveIntegrityPolicy } from "./resolveIntegrityPolicy.mjs";
4
5
  export { verifyReleaseSignature } from "./verifyReleaseSignature.mjs";
@@ -1,5 +1,15 @@
1
1
  import { compareVersions } from "./compareVersions.mjs";
2
2
 
3
+ /**
4
+ * Tell whether a checksum was actually configured.
5
+ *
6
+ * @param {string} expectedChecksum - Configured SHA256, empty when none.
7
+ * @returns {boolean} False for an empty or whitespace-only value.
8
+ */
9
+ export function hasExpectedChecksum(expectedChecksum) {
10
+ return Boolean(expectedChecksum && expectedChecksum.trim());
11
+ }
12
+
3
13
  /**
4
14
  * Decide which integrity evidence a download must produce before it is trusted.
5
15
  *
@@ -16,9 +26,8 @@ import { compareVersions } from "./compareVersions.mjs";
16
26
  */
17
27
  export function resolveIntegrityPolicy({ version, signedFromVersion, expectedChecksum }) {
18
28
  const requiresSignature = Boolean(signedFromVersion) && compareVersions(version, signedFromVersion) >= 0;
19
- const hasChecksum = Boolean(expectedChecksum && expectedChecksum.trim());
20
29
 
21
- if (!requiresSignature && !hasChecksum) {
30
+ if (!requiresSignature && !hasExpectedChecksum(expectedChecksum)) {
22
31
  return {
23
32
  requiresSignature: false,
24
33
  requiresChecksum: false,
@@ -1,7 +1,13 @@
1
1
  /* global AbortController */
2
2
  import { readFile } from "node:fs/promises";
3
- import { verify } from "sigstore";
4
- import { SIGNATURE_FETCH_TIMEOUT_MS, SIGNER_CERTIFICATE_ISSUER } from "./constants.mjs";
3
+ import { createVerifier } from "sigstore";
4
+ import { describeErrorChain, isTrustRootUnreachable } from "./classifyTrustRootFailure.mjs";
5
+ import {
6
+ SIGNATURE_FETCH_TIMEOUT_MS,
7
+ SIGNATURE_TRUST_ROOT_HOST,
8
+ SIGNER_CERTIFICATE_ISSUER,
9
+ } from "./constants.mjs";
10
+ import { findBundleMismatch } from "./findBundleMismatch.mjs";
5
11
 
6
12
  /**
7
13
  * Verify a downloaded release asset against the Sigstore bundle published beside it.
@@ -10,15 +16,23 @@ import { SIGNATURE_FETCH_TIMEOUT_MS, SIGNER_CERTIFICATE_ISSUER } from "./constan
10
16
  * source repository, so the signer identity is pinned exactly: a bundle that is
11
17
  * otherwise valid but was issued to any other workflow is rejected.
12
18
  *
19
+ * Loading the trust root and checking the bundle run as separate steps. Only the
20
+ * first can report the host unreachable, and it never sees the bundle, so a tampered
21
+ * bundle cannot be mistaken for a network failure.
22
+ *
13
23
  * @param {object} params - Verification parameters.
14
24
  * @param {string} params.artifactPath - Path to the downloaded asset.
15
25
  * @param {string} params.bundleUrl - URL of the asset's Sigstore bundle.
16
26
  * @param {string} params.signerIdentityUri - Certificate subject the signer must carry.
17
- * @returns {Promise<{valid: boolean, reason: string}>} Verification outcome, with the rejection cause when invalid.
27
+ * @returns {Promise<{valid: boolean, reason: string, isTrustRootUnreachable: boolean}>} Verification outcome. `valid` is false whenever the signature was not proven; `isTrustRootUnreachable` marks the one case where it could not be checked at all.
18
28
  */
19
29
  export async function verifyReleaseSignature({ artifactPath, bundleUrl, signerIdentityUri }) {
20
30
  if (!signerIdentityUri) {
21
- return { valid: false, reason: "no signer identity is configured to verify against" };
31
+ return {
32
+ valid: false,
33
+ reason: "no signer identity is configured to verify against",
34
+ isTrustRootUnreachable: false,
35
+ };
22
36
  }
23
37
 
24
38
  const controller = new AbortController();
@@ -30,22 +44,60 @@ export async function verifyReleaseSignature({ artifactPath, bundleUrl, signerId
30
44
  return {
31
45
  valid: false,
32
46
  reason: `signature bundle unavailable (HTTP ${response.status}) at ${bundleUrl}`,
47
+ isTrustRootUnreachable: false,
33
48
  };
34
49
  }
35
50
  bundle = await response.json();
36
51
  } catch (error) {
37
- return { valid: false, reason: `could not fetch signature bundle: ${error.message}` };
52
+ return {
53
+ valid: false,
54
+ reason: `could not fetch signature bundle: ${error.message}`,
55
+ isTrustRootUnreachable: false,
56
+ };
38
57
  } finally {
39
58
  clearTimeout(timer);
40
59
  }
41
60
 
61
+ let artifactBytes;
62
+ try {
63
+ artifactBytes = await readFile(artifactPath);
64
+ } catch (error) {
65
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
66
+ }
67
+
68
+ let bundleVerifier;
42
69
  try {
43
- await verify(bundle, await readFile(artifactPath), {
70
+ bundleVerifier = await createVerifier({
44
71
  certificateIssuer: SIGNER_CERTIFICATE_ISSUER,
45
72
  certificateIdentityURI: signerIdentityUri,
46
73
  });
47
- return { valid: true, reason: "" };
48
74
  } catch (error) {
49
- return { valid: false, reason: error.message };
75
+ const failureDescription = describeErrorChain(error);
76
+
77
+ if (!isTrustRootUnreachable(error)) {
78
+ return {
79
+ valid: false,
80
+ reason: `could not load the trust root from ${SIGNATURE_TRUST_ROOT_HOST}: ${failureDescription}`,
81
+ isTrustRootUnreachable: false,
82
+ };
83
+ }
84
+
85
+ const bundleMismatch = findBundleMismatch({
86
+ bundle: bundle,
87
+ artifactBytes: artifactBytes,
88
+ signerIdentityUri: signerIdentityUri,
89
+ });
90
+ return {
91
+ valid: false,
92
+ reason: bundleMismatch || failureDescription,
93
+ isTrustRootUnreachable: !bundleMismatch,
94
+ };
95
+ }
96
+
97
+ try {
98
+ bundleVerifier.verify(bundle, artifactBytes);
99
+ return { valid: true, reason: "", isTrustRootUnreachable: false };
100
+ } catch (error) {
101
+ return { valid: false, reason: error.message, isTrustRootUnreachable: false };
50
102
  }
51
103
  }