@deeeed/metamask-harness 0.72.0 → 0.74.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.
@@ -12,7 +12,8 @@ import {
12
12
  importRecipeHarnessRuntimeCdp,
13
13
  recipeHarnessPath,
14
14
  recipeRuntimeDir,
15
- runnerDir
15
+ runnerDir,
16
+ walletFixturePath
16
17
  } from "../../paths.js";
17
18
  import { extensionIdFromKey } from "../../adapters/extension/extension-id.js";
18
19
  import {
@@ -29,9 +30,16 @@ import {
29
30
  import { checkExtensionRuntimeHealth } from "../../adapters/extension/runtime.js";
30
31
  import { ensureHarnessFresh } from "../../adapters/harness-freshness.js";
31
32
  import { isExtensionWatcherLive, stopExtensionWatcher } from "../../adapters/slot-ports.js";
32
- import { EXIT, spawnScriptStreaming } from "../shared.js";
33
+ import { EXIT, spawnScript, spawnScriptStreaming } from "../shared.js";
33
34
  import { readExtensionPinnedFlags } from "../../adapters/extension/feature-flags.js";
34
- import { sameFeatureFlags } from "../../feature-flags.js";
35
+ import { ensureExtensionConsoleCapture } from "../../adapters/extension/console-capture.js";
36
+ import {
37
+ fixtureFeatureFlags,
38
+ sameFeatureFlags,
39
+ toRemoteFlagSpec
40
+ } from "../../feature-flags.js";
41
+ import { RECOVERY_CODE } from "../../heal-bounds.js";
42
+ import { shellQuote } from "./device.js";
35
43
  const { CdpSession } = await importRecipeHarnessRuntimeCdp();
36
44
  const { RUNTIME_IDENTITY_FILENAME, RUNTIME_NONCE_PREFIX } = createRequire(import.meta.url)(
37
45
  path.join(runnerDir, "adapters/extension/lib/chrome-args.cjs")
@@ -479,9 +487,301 @@ async function extensionRebuild(target, remoteFlags) {
479
487
  }
480
488
  return result;
481
489
  }
490
+ const DEFAULT_EXTENSION_DAPP_URL = "https://metamask.github.io/test-dapp/";
491
+ function verifyExtensionPin(target, requested) {
492
+ const pinned = readExtensionPinnedFlags(target);
493
+ if (pinned.error) {
494
+ return {
495
+ ok: false,
496
+ flags: {},
497
+ code: "RUNTIME_MANIFEST_UNREADABLE",
498
+ message: `the launched dist snapshot manifest could not be read (${pinned.sourcePath ?? "unknown path"}): ${pinned.error}`
499
+ };
500
+ }
501
+ if (pinned.overrides !== null && pinned.pinned === null) {
502
+ return {
503
+ ok: false,
504
+ flags: {},
505
+ code: "REMOTE_FLAG_NOT_APPLIED",
506
+ message: `the launched dist snapshot manifest (${pinned.sourcePath ?? "unknown path"}) carries no harness pin record; it was not written by this launch.`
507
+ };
508
+ }
509
+ const actual = pinned.pinned ?? {};
510
+ if (!sameFeatureFlags(actual, requested)) {
511
+ const mismatched = [.../* @__PURE__ */ new Set([...Object.keys(requested), ...Object.keys(actual)])].filter(
512
+ (key) => JSON.stringify(actual[key]) !== JSON.stringify(requested[key])
513
+ );
514
+ return {
515
+ ok: false,
516
+ flags: {},
517
+ code: "REMOTE_FLAG_NOT_APPLIED",
518
+ message: `the remote feature-flag pin ${toRemoteFlagSpec(requested) || "(none)"} does not match the launched snapshot manifest: ` + mismatched.map((key) => `${key} expected ${JSON.stringify(requested[key])}, got ${JSON.stringify(actual[key])}`).join("; ")
519
+ };
520
+ }
521
+ return { ok: true, flags: actual, message: "" };
522
+ }
523
+ function extensionQuickReattachFailed(output) {
524
+ return /\[reattach\]|extension quick reattach|mm-harness launch --build/u.test(output);
525
+ }
526
+ function extensionRuntimeBlocked(output) {
527
+ return /ERR_BLOCKED_BY_CLIENT|has been blocked by Chromium/u.test(output);
528
+ }
529
+ function extensionBrowserMissing(output) {
530
+ return /Playwright Chromium is not installed|No compatible Chromium binary selected/u.test(output);
531
+ }
532
+ function extensionProductConfigMissing(output) {
533
+ return /EXTENSION_PRODUCT_CONFIG_REQUIRED:/u.test(output);
534
+ }
535
+ function extensionEvmRpcUnreachable(output) {
536
+ return /EVM_RPC_UNREACHABLE|EVM RPC readiness probe failed|Infura configured ≠ RPC reachable/u.test(output);
537
+ }
538
+ const extensionLaunchProfile = {
539
+ refuseFlags({ target }, { watch, runway, clearMetro, remoteFlagSpec }) {
540
+ if (runway) return { message: "runway is mobile-only.", userAction: "drop --runway for the extension" };
541
+ if (clearMetro) return { message: "--clear-metro is mobile-only.", userAction: "drop --clear-metro for the extension" };
542
+ if (remoteFlagSpec !== void 0 && watch) {
543
+ return {
544
+ message: "--remote-flag cannot be applied with --watch: the watcher never re-creates the dist snapshot that carries the pin.",
545
+ userAction: `mm-harness launch --adapter extension --remote-flag ${remoteFlagSpec} --target ${shellQuote(target)}`
546
+ };
547
+ }
548
+ return void 0;
549
+ },
550
+ // --url: initial main-tab page for extension launches (dapp beside the
551
+ // sidepanel); travels to live.sh/launch-browser via env. Sidepanel mode has a
552
+ // useful default so `mm-harness launch --sidepanel` opens a working dapp, not
553
+ // just a wallet panel with no page to connect from.
554
+ start({ options, displayMode, machine, wantWatch, tier }) {
555
+ const requestedUrl = typeof options["url"] === "string" && options["url"] ? options["url"] : "";
556
+ if (requestedUrl || displayMode === "sidepanel") {
557
+ process.env.EXTENSION_START_URL = requestedUrl || DEFAULT_EXTENSION_DAPP_URL;
558
+ }
559
+ if (machine) return;
560
+ const modeNote = displayMode === "sidepanel" ? `sidepanel \xB7 dapp ${process.env.EXTENSION_START_URL ?? DEFAULT_EXTENSION_DAPP_URL}` : "fullscreen";
561
+ const workNote = wantWatch ? "watch only" : tier === "build" ? "clean build" : "quick reuse probe";
562
+ console.error(colorHumanMessage(
563
+ `\u2192 extension launch \u2014 ${modeNote} \xB7 CDP :${process.env.CDP_PORT ?? "default"} \xB7 ${workNote}`
564
+ ));
565
+ },
566
+ nativeInputs: ["package.json", "yarn.lock", "webpack.config.js"],
567
+ rebuildCommand: () => "mm-harness launch --build",
568
+ // Source-development launch paths require checkout tooling. A verified local
569
+ // release artifact can reuse its healthy browser without building or watching.
570
+ async healthcheck(launch, state) {
571
+ const { target, tier, wantWatch, heal, stream } = launch;
572
+ const artifact = releaseArtifactState(target);
573
+ const reusable = !wantWatch && tier !== "build" && await extensionRuntimeReusable(target, artifact);
574
+ const verifiedReleaseReuse = artifact.status === "valid" && reusable;
575
+ const verifiedReleaseLaunch = !wantWatch && tier !== "build" && artifact.status === "valid" && runtimeDistCheck(target, artifact).status === "fresh";
576
+ const willBuild = !reusable;
577
+ if (willBuild) {
578
+ const productConfigBlock = extensionProductConfigBlock(target);
579
+ if (productConfigBlock) {
580
+ return launch.fail(state, {
581
+ code: "EXTENSION_PRODUCT_CONFIG_REQUIRED",
582
+ message: productConfigBlock.message,
583
+ recoverable: false,
584
+ userAction: productConfigBlock.userAction,
585
+ exitCode: EXIT.infra
586
+ });
587
+ }
588
+ }
589
+ const depsBlock = verifiedReleaseReuse || verifiedReleaseLaunch ? null : extensionDepsBlock(target);
590
+ if (depsBlock) {
591
+ if (heal === "off") return launch.usage(depsBlock.message, depsBlock.userAction);
592
+ const recoveryCode = "deps.installed";
593
+ state.attemptedRecoveries.push(recoveryCode);
594
+ stream.phase("recover");
595
+ const repaired = await installExtensionDeps(target);
596
+ if (repaired.status !== 0 || extensionDepsBlock(target)) {
597
+ return launch.fail(state, {
598
+ code: "DEPENDENCY_INSTALL_FAILED",
599
+ message: depsBlock.message,
600
+ recoverable: false,
601
+ userAction: "install the checkout-pinned Node version, then re-run mm-harness launch",
602
+ originalError: repaired.output,
603
+ exitCode: EXIT.infra
604
+ });
605
+ }
606
+ state.recovered.push(recoveryCode);
607
+ state.mutations.push({ type: "dependencies", action: "installed", path: target });
608
+ }
609
+ return void 0;
610
+ },
611
+ compose: ({ target, wantWatch, displayMode, remoteFlagRequest }, tier) => launchExtension(target, tier, wantWatch, displayMode, remoteFlagRequest),
612
+ classify({ target, remoteFlagRequest }, output) {
613
+ if (output.includes("REMOTE_FLAG_NOT_PINNABLE:")) {
614
+ return {
615
+ code: "REMOTE_FLAG_NOT_PINNABLE",
616
+ message: `a verified release artifact cannot carry a remote feature-flag pin (${remoteFlagRequest?.spec ?? ""}); its manifest is signed evidence and is never rewritten. Validate the artifact as shipped (drop --remote-flag and the fixture's remoteFeatureFlags) or validate the variant on a source build.`,
617
+ recoverable: false,
618
+ // The next step must leave the artifact alone: a --build here would replace
619
+ // the artifact under validation with a source build.
620
+ userAction: Object.keys(fixtureFeatureFlags(walletFixturePath(target))).length > 0 ? `remove remoteFeatureFlags from ${shellQuote(walletFixturePath(target))}, then: mm-harness launch --adapter extension --target ${shellQuote(target)}` : `mm-harness launch --adapter extension --target ${shellQuote(target)}`,
621
+ exitCode: EXIT.infra,
622
+ originalError: output.trim() || void 0
623
+ };
624
+ }
625
+ if (extensionProductConfigMissing(output)) {
626
+ const block = extensionProductConfigBlock(target);
627
+ return {
628
+ code: "EXTENSION_PRODUCT_CONFIG_REQUIRED",
629
+ message: block?.message ?? "Extension product configuration was not ready when the build started.",
630
+ recoverable: false,
631
+ userAction: block?.userAction ?? `mm-harness launch --adapter extension --target ${shellQuote(target)}`,
632
+ exitCode: EXIT.infra
633
+ };
634
+ }
635
+ if (extensionBrowserMissing(output)) {
636
+ return {
637
+ code: "EXTENSION_BROWSER_REQUIRED",
638
+ message: "the checkout Playwright browser is not installed; system Chrome is not a compatible unpacked-extension fallback. Installing the browser cache requires user approval.",
639
+ recoverable: false,
640
+ userAction: `ask the user for approval, then run: cd ${shellQuote(target)} && yarn playwright install chromium`,
641
+ exitCode: EXIT.infra
642
+ };
643
+ }
644
+ if (output.includes("EXTENSION_BACKGROUND_UNRESPONSIVE:") || output.includes("EXTENSION_STARTUP_UNVERIFIED:")) {
645
+ return {
646
+ code: output.includes("EXTENSION_BACKGROUND_UNRESPONSIVE:") ? "EXTENSION_BACKGROUND_UNRESPONSIVE" : "EXTENSION_STARTUP_UNVERIFIED",
647
+ message: "Extension startup is not healthy; inspect the background error before restarting or resetting wallet state.",
648
+ recoverable: false,
649
+ userAction: `mm-harness logs --target ${shellQuote(target)} --full`,
650
+ exitCode: EXIT.runtime,
651
+ originalError: output.trim() || void 0
652
+ };
653
+ }
654
+ if (output.includes("EVM_RPC_EXECUTION_FAILED:")) {
655
+ return {
656
+ code: "EVM_RPC_EXECUTION_FAILED",
657
+ message: "Background RPC fetch failed during JavaScript execution; this does not establish an Infura authentication or connectivity failure.",
658
+ recoverable: false,
659
+ userAction: `mm-harness logs --target ${shellQuote(target)} --full`,
660
+ exitCode: EXIT.runtime,
661
+ originalError: output.trim() || void 0
662
+ };
663
+ }
664
+ if (extensionEvmRpcUnreachable(output)) {
665
+ return {
666
+ code: "EVM_RPC_UNREACHABLE",
667
+ message: "EVM RPC readiness failed; Infura configured does not mean RPC reachable.",
668
+ recoverable: false,
669
+ userAction: `Check the effective INFURA_PROJECT_ID from the environment, .metamaskprodrc, or ${shellQuote(path.join(target, ".metamaskrc"))}, then rerun: mm-harness launch --verify --target ${shellQuote(target)}`,
670
+ exitCode: EXIT.runtime,
671
+ originalError: output.trim() || void 0
672
+ };
673
+ }
674
+ return void 0;
675
+ },
676
+ async beforeHeal(launch, attempt, state) {
677
+ if (launch.tier !== "quick" || !extensionQuickReattachFailed(attempt.output)) return void 0;
678
+ const recoveryCode = "chrome.relaunched";
679
+ state.attemptedRecoveries.push(recoveryCode);
680
+ launch.stream.phase("recover");
681
+ const rebuildAttempt = await launch.compose("build");
682
+ if (rebuildAttempt.status === 0) {
683
+ state.recovered.push(recoveryCode);
684
+ return await launch.settle(state, rebuildAttempt.remoteFeatureFlags);
685
+ }
686
+ return launch.fail(state, {
687
+ code: "EXTENSION_RELAUNCH_FAILED",
688
+ message: "quick reattach failed, and clean relaunch failed too.",
689
+ recoverable: false,
690
+ exitCode: EXIT.infra,
691
+ originalError: rebuildAttempt.output.trim() || void 0
692
+ });
693
+ },
694
+ recovery: () => ({ code: RECOVERY_CODE.extension, restartApp: false }),
695
+ // --watch only restarts the webpack watcher; the snapshot, and its pin, are
696
+ // untouched, so the live record is reported rather than verified against a
697
+ // request the watcher could never apply (--remote-flag is refused with it;
698
+ // the fixture baseline stays whatever the last launch pinned).
699
+ provenFlags({ target, wantWatch, remoteFlagRequest }, requested) {
700
+ if (wantWatch) return { flags: readExtensionPinnedFlags(target).pinned };
701
+ const pinned = verifyExtensionPin(target, requested);
702
+ if (pinned.ok) return { flags: pinned.flags };
703
+ const spec = remoteFlagRequest?.spec;
704
+ return {
705
+ code: pinned.code ?? "REMOTE_FLAG_NOT_APPLIED",
706
+ message: pinned.message,
707
+ recoverable: false,
708
+ // A rebuild re-creates the snapshot; the flag is repeated only when one was asked for.
709
+ userAction: `mm-harness launch --adapter extension --build${spec ? ` --remote-flag ${spec}` : ""} --target ${shellQuote(target)}`,
710
+ exitCode: EXIT.runtime
711
+ };
712
+ },
713
+ async finish(launch, state, sidepanelRecoveryAllowed) {
714
+ const { target, machine, displayMode, tier, stream } = launch;
715
+ const sidepanelSh = path.join(runnerDir, "adapters/extension/sidepanel-toggle.sh");
716
+ if (displayMode === "fullscreen") {
717
+ const sidepanelArgs = ["close"];
718
+ if (process.env.CDP_PORT) sidepanelArgs.push("--cdp-port", process.env.CDP_PORT);
719
+ const fullscreen = spawnScript(sidepanelSh, sidepanelArgs, target, machine, { REPO: target });
720
+ if (fullscreen.status !== 0) {
721
+ return launch.fail(state, {
722
+ code: "FULLSCREEN_OPEN_FAILED",
723
+ message: "app launched but restoring the fullscreen Extension surface failed.",
724
+ recoverable: false,
725
+ userAction: `bash adapters/extension/sidepanel-toggle.sh close --cdp-port ${process.env.CDP_PORT ?? "<CDP_PORT>"}`,
726
+ exitCode: EXIT.runtime,
727
+ originalError: fullscreen.output.trim() || void 0
728
+ });
729
+ }
730
+ }
731
+ if (displayMode === "sidepanel") {
732
+ const sidepanelArgs = ["open"];
733
+ if (process.env.CDP_PORT) sidepanelArgs.push("--cdp-port", process.env.CDP_PORT);
734
+ if (!machine) {
735
+ console.error(
736
+ `[sidepanel] opening panel beside ${process.env.EXTENSION_START_URL ?? DEFAULT_EXTENSION_DAPP_URL}`
737
+ );
738
+ }
739
+ const sidepanel = spawnScript(sidepanelSh, sidepanelArgs, target, machine, { REPO: target });
740
+ if (sidepanel.status !== 0) {
741
+ const recoveryCode = "chrome.relaunched";
742
+ if (sidepanelRecoveryAllowed && tier === "quick" && extensionRuntimeBlocked(sidepanel.output) && !state.attemptedRecoveries.includes(recoveryCode)) {
743
+ state.attemptedRecoveries.push(recoveryCode);
744
+ stream.phase("recover");
745
+ const rebuildAttempt = await launch.compose("build");
746
+ if (rebuildAttempt.status === 0) {
747
+ state.recovered.push(recoveryCode);
748
+ return await launch.settle(state, void 0, false);
749
+ }
750
+ return launch.fail(state, {
751
+ code: "EXTENSION_RELAUNCH_FAILED",
752
+ message: "sidepanel open found a blocked extension runtime, and clean relaunch failed too.",
753
+ recoverable: false,
754
+ exitCode: EXIT.infra,
755
+ originalError: rebuildAttempt.output.trim() || void 0
756
+ });
757
+ }
758
+ return launch.fail(state, {
759
+ code: "SIDEPANEL_OPEN_FAILED",
760
+ message: "app launched but opening the side panel failed.",
761
+ recoverable: false,
762
+ userAction: `bash adapters/extension/sidepanel-toggle.sh open --cdp-port ${process.env.CDP_PORT ?? "<CDP_PORT>"}`,
763
+ exitCode: EXIT.runtime,
764
+ originalError: sidepanel.output.trim() || void 0
765
+ });
766
+ }
767
+ }
768
+ try {
769
+ await ensureExtensionConsoleCapture(target);
770
+ } catch (error) {
771
+ if (!machine) {
772
+ console.error(`WARN: Extension console capture unavailable: ${error instanceof Error ? error.message : String(error)}`);
773
+ }
774
+ }
775
+ return void 0;
776
+ },
777
+ verifyArgs: () => process.env.CDP_PORT ? ["--cdp-port", process.env.CDP_PORT] : [],
778
+ platformLabel: ({ mobileTarget, displayMode }) => mobileTarget ?? displayMode,
779
+ deviceLabel: ({ displayMode }) => displayMode
780
+ };
482
781
  export {
483
782
  extensionDepsBlock,
484
783
  extensionLaunchDevelopment,
784
+ extensionLaunchProfile,
485
785
  extensionReattach,
486
786
  extensionRebuild,
487
787
  extensionRuntimeReusable,