feat: vendor and censor the phishing blocklist at build time (closes #219)
The blocklist URL in shipped code named a competitor and pointed at a moving ref, and the extension re-fetched from it every 24 hours, which also meant a third party decided what this wallet warns about. All of that is gone. script/vendor-blocklist fetches upstream at a pinned commit, verifies the sha256 of the bytes that commit serves, and writes src/shared/phishingBlocklist.json. It is build-time tooling, never shipped, and the one place in the repo that names the upstream project; a source reference nobody can verify is not a source reference. The artifact stores truncated sha256 digests rather than domain names. That is what censors it: the previous file contained the competitor's name 6,475 times, as phishing domains impersonating them, and not one of those domains is dropped. It also makes lookups a binary search over a fixed-width string, so nothing is built at module load — which matters on MV3, where the worker re-evaluates the module on every wake — and takes the file from 8.7 MB to 1.7 MB. script/check-censored enforces the rest: it reads the name out of the vendoring script rather than repeating it, and fails on any occurrence in the working tree or under dist/ that is not one of the three literals shipped code cannot avoid — two provider-shim identifiers in src/content/inpage.js and one ERC-20's on-chain name in src/shared/tokenList.js. Each is permitted only at the path that carries it, and at the emitted paths that path is bundled into, so a literal appearing anywhere else fails like any other occurrence. It runs in make check, which inspects dist/ when there is one and says loudly when there is not, and again with --require-dist at the end of every make build. Removing the runtime fetch retires the delta, the extension-storage persistence and the 24-hour alarm from #158. A retired alarm is now cleared rather than left waking the worker forever on installs that already have it. The e2e suite drives the warning end to end from a real blocklisted origin served as a real http(s) site, with a control asserting the banner stays hidden for one that is not listed. Its service-worker interception canary needed a new anchor, since the startup fetch it used to watch for no longer happens: it now wakes the worker with a message and asks it for one throwaway fetch. LICENSE no longer cites a repository that returns 404. eslint.config.js gains one block: script/lib/ holds node programs the shell entrypoints call, and without it they lint with no globals at all.
This commit is contained in:
@@ -80,17 +80,12 @@ describe("alarms module", () => {
|
||||
delete global.chrome;
|
||||
});
|
||||
|
||||
test("ensureRecurringAlarms schedules both recurring jobs", async () => {
|
||||
test("ensureRecurringAlarms schedules the recurring job", async () => {
|
||||
const created = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(created).toEqual({ balance: true, phishing: true });
|
||||
expect(created).toEqual({ balance: true, cleared: [] });
|
||||
|
||||
const names = alarmsStub.created.map((c) => c.name).sort();
|
||||
expect(names).toEqual(
|
||||
[
|
||||
alarmsMod.BALANCE_REFRESH_ALARM,
|
||||
alarmsMod.PHISHING_REFRESH_ALARM,
|
||||
].sort(),
|
||||
);
|
||||
const names = alarmsStub.created.map((c) => c.name);
|
||||
expect(names).toEqual([alarmsMod.BALANCE_REFRESH_ALARM]);
|
||||
});
|
||||
|
||||
test("the balance refresh keeps its 60-second cadence", async () => {
|
||||
@@ -99,12 +94,35 @@ describe("alarms module", () => {
|
||||
expect(balance.periodInMinutes).toBe(1);
|
||||
});
|
||||
|
||||
test("the phishing refresh keeps its 24-hour cadence", async () => {
|
||||
test("a retired job's alarm is cleared, not left running", async () => {
|
||||
// The browser holds an alarm until something clears it. Deleting the
|
||||
// job from the code is not enough: on every install that ever ran the
|
||||
// version which created it, the alarm goes on waking the service
|
||||
// worker on its old schedule with nothing to deliver it to.
|
||||
for (const name of alarmsMod.OBSOLETE_ALARMS) {
|
||||
alarmsStub.create(name, { periodInMinutes: 24 * 60 });
|
||||
}
|
||||
expect(alarmsMod.OBSOLETE_ALARMS.length).toBeGreaterThan(0);
|
||||
|
||||
const result = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(result.cleared).toEqual(alarmsMod.OBSOLETE_ALARMS);
|
||||
for (const name of alarmsMod.OBSOLETE_ALARMS) {
|
||||
expect(alarmsStub.alarms.get(name)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
test("clearing a retired alarm is not re-reported once it is gone", async () => {
|
||||
await alarmsMod.ensureRecurringAlarms();
|
||||
const phishing = alarmsStub.alarms.get(
|
||||
alarmsMod.PHISHING_REFRESH_ALARM,
|
||||
const again = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(again.cleared).toEqual([]);
|
||||
});
|
||||
|
||||
test("no retired name is also a live one", async () => {
|
||||
// A name in both lists would be created and then cleared on every
|
||||
// start, so the job it schedules would never fire.
|
||||
expect(alarmsMod.OBSOLETE_ALARMS).not.toContain(
|
||||
alarmsMod.BALANCE_REFRESH_ALARM,
|
||||
);
|
||||
expect(phishing.periodInMinutes).toBe(24 * 60);
|
||||
});
|
||||
|
||||
test("no period is below the browser-enforced minimum", async () => {
|
||||
@@ -122,14 +140,14 @@ describe("alarms module", () => {
|
||||
|
||||
test("a revived worker does not reset an existing alarm's schedule", async () => {
|
||||
await alarmsMod.ensureRecurringAlarms();
|
||||
expect(alarmsStub.create).toHaveBeenCalledTimes(2);
|
||||
expect(alarmsStub.create).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Every wake re-runs the startup path. Re-creating an alarm restarts
|
||||
// its period, so a busy extension would push the next fire out
|
||||
// forever and the job would never run.
|
||||
const again = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(again).toEqual({ balance: false, phishing: false });
|
||||
expect(alarmsStub.create).toHaveBeenCalledTimes(2);
|
||||
expect(again).toEqual({ balance: false, cleared: [] });
|
||||
expect(alarmsStub.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("a missing alarm is re-created on the next start", async () => {
|
||||
@@ -137,7 +155,7 @@ describe("alarms module", () => {
|
||||
await alarmsStub.clear(alarmsMod.BALANCE_REFRESH_ALARM);
|
||||
|
||||
const again = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(again).toEqual({ balance: true, phishing: false });
|
||||
expect(again).toEqual({ balance: true, cleared: [] });
|
||||
expect(
|
||||
alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM),
|
||||
).toBeDefined();
|
||||
@@ -147,17 +165,17 @@ describe("alarms module", () => {
|
||||
// An install carries its alarms across an extension update, so a
|
||||
// period changed in a new release only ever reaches users if the
|
||||
// stale one is reconciled.
|
||||
alarmsStub.create(alarmsMod.PHISHING_REFRESH_ALARM, {
|
||||
alarmsStub.create(alarmsMod.BALANCE_REFRESH_ALARM, {
|
||||
periodInMinutes: 7 * 24 * 60,
|
||||
});
|
||||
alarmsStub.create.mockClear();
|
||||
|
||||
const created = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(created.phishing).toBe(true);
|
||||
expect(created.balance).toBe(true);
|
||||
expect(
|
||||
alarmsStub.alarms.get(alarmsMod.PHISHING_REFRESH_ALARM)
|
||||
alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM)
|
||||
.periodInMinutes,
|
||||
).toBe(alarmsMod.PHISHING_REFRESH_PERIOD_MINUTES);
|
||||
).toBe(alarmsMod.BALANCE_REFRESH_PERIOD_MINUTES);
|
||||
});
|
||||
|
||||
test("reconciling a period settles instead of re-creating forever", async () => {
|
||||
@@ -168,31 +186,31 @@ describe("alarms module", () => {
|
||||
alarmsStub.create.mockClear();
|
||||
|
||||
const again = await alarmsMod.ensureRecurringAlarms();
|
||||
expect(again).toEqual({ balance: false, phishing: false });
|
||||
expect(again).toEqual({ balance: false, cleared: [] });
|
||||
expect(alarmsStub.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("handlers are dispatched by alarm name from one listener", () => {
|
||||
const balance = jest.fn();
|
||||
const phishing = jest.fn();
|
||||
const other = jest.fn();
|
||||
expect(
|
||||
alarmsMod.registerAlarmHandlers({
|
||||
[alarmsMod.BALANCE_REFRESH_ALARM]: balance,
|
||||
[alarmsMod.PHISHING_REFRESH_ALARM]: phishing,
|
||||
"autistmask-some-other-job": other,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(alarmsStub.listenerCount()).toBe(1);
|
||||
|
||||
alarmsStub.fire(alarmsMod.BALANCE_REFRESH_ALARM);
|
||||
expect(balance).toHaveBeenCalledTimes(1);
|
||||
expect(phishing).not.toHaveBeenCalled();
|
||||
expect(other).not.toHaveBeenCalled();
|
||||
|
||||
alarmsStub.fire(alarmsMod.PHISHING_REFRESH_ALARM);
|
||||
expect(phishing).toHaveBeenCalledTimes(1);
|
||||
alarmsStub.fire("autistmask-some-other-job");
|
||||
expect(other).toHaveBeenCalledTimes(1);
|
||||
|
||||
alarmsStub.fire("some-other-extension-alarm");
|
||||
alarmsStub.fire("an-alarm-with-no-handler");
|
||||
expect(balance).toHaveBeenCalledTimes(1);
|
||||
expect(phishing).toHaveBeenCalledTimes(1);
|
||||
expect(other).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("Firefox MV2 gets the same treatment via browser.alarms", async () => {
|
||||
@@ -205,8 +223,8 @@ describe("alarms module", () => {
|
||||
try {
|
||||
const mod = require("../src/shared/alarms");
|
||||
const created = await mod.ensureRecurringAlarms();
|
||||
expect(created).toEqual({ balance: true, phishing: true });
|
||||
expect(firefoxAlarms.created).toHaveLength(2);
|
||||
expect(created).toEqual({ balance: true, cleared: [] });
|
||||
expect(firefoxAlarms.created).toHaveLength(1);
|
||||
// The Chrome stub must not have been touched.
|
||||
expect(alarmsStub.create).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
@@ -220,7 +238,7 @@ describe("alarms module", () => {
|
||||
const mod = require("../src/shared/alarms");
|
||||
await expect(mod.ensureRecurringAlarms()).resolves.toEqual({
|
||||
balance: false,
|
||||
phishing: false,
|
||||
cleared: [],
|
||||
});
|
||||
expect(mod.registerAlarmHandlers({})).toBe(false);
|
||||
});
|
||||
@@ -274,9 +292,12 @@ function loadBackground(initialStore = {}) {
|
||||
tabs: { query: jest.fn(), sendMessage: jest.fn() },
|
||||
action: { setPopup: jest.fn() },
|
||||
};
|
||||
// Present so that a startup path which went to the network would be
|
||||
// recorded rather than throwing, which is what makes "no request was made"
|
||||
// an observation instead of an assumption.
|
||||
global.fetch = jest.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ blacklist: [] }),
|
||||
json: async () => ({}),
|
||||
}));
|
||||
jest.resetModules();
|
||||
require("../src/background/index");
|
||||
@@ -318,17 +339,21 @@ describe("background worker scheduling", () => {
|
||||
// Let the startup path's promises settle.
|
||||
await settle();
|
||||
|
||||
const names = alarmsStub.created.map((c) => c.name).sort();
|
||||
const {
|
||||
BALANCE_REFRESH_ALARM,
|
||||
PHISHING_REFRESH_ALARM,
|
||||
} = require("../src/shared/alarms");
|
||||
expect(names).toEqual(
|
||||
[BALANCE_REFRESH_ALARM, PHISHING_REFRESH_ALARM].sort(),
|
||||
);
|
||||
const names = alarmsStub.created.map((c) => c.name);
|
||||
const { BALANCE_REFRESH_ALARM } = require("../src/shared/alarms");
|
||||
expect(names).toEqual([BALANCE_REFRESH_ALARM]);
|
||||
expect(mockSetIntervalCalls).toBe(0);
|
||||
});
|
||||
|
||||
test("startup contacts nothing", async () => {
|
||||
// The phishing blocklist is vendored at build time and there is no
|
||||
// other startup fetch, so a worker coming up asks nobody anything.
|
||||
// Every wake used to be a candidate for a blocklist download.
|
||||
loadBackground();
|
||||
await settle();
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("an onAlarm listener is installed on startup", async () => {
|
||||
alarmsStub = loadBackground().alarmsStub;
|
||||
await settle();
|
||||
@@ -348,7 +373,7 @@ describe("background worker scheduling", () => {
|
||||
alarmsStub.created.length = 0;
|
||||
loaded.listeners.onStartup[0]();
|
||||
await settle();
|
||||
expect(alarmsStub.created).toHaveLength(2);
|
||||
expect(alarmsStub.created).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("the install-time listener and the top-level call share one run", async () => {
|
||||
@@ -360,13 +385,10 @@ describe("background worker scheduling", () => {
|
||||
loaded.listeners.onInstalled[0]();
|
||||
await settle();
|
||||
|
||||
expect(alarmsStub.created).toHaveLength(2);
|
||||
expect(alarmsStub.created.map((c) => c.name).sort()).toEqual(
|
||||
[
|
||||
"autistmask-balance-refresh",
|
||||
"autistmask-phishing-refresh",
|
||||
].sort(),
|
||||
);
|
||||
expect(alarmsStub.created).toHaveLength(1);
|
||||
expect(alarmsStub.created.map((c) => c.name)).toEqual([
|
||||
"autistmask-balance-refresh",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -157,12 +157,9 @@ function loadBackground(options) {
|
||||
}));
|
||||
jest.doMock("../src/shared/phishingDomains", () => ({
|
||||
isPhishingDomain: () => false,
|
||||
refreshPhishingListOnSchedule: jest.fn(async () => {}),
|
||||
initPhishingList: jest.fn(async () => {}),
|
||||
}));
|
||||
jest.doMock("../src/shared/alarms", () => ({
|
||||
BALANCE_REFRESH_ALARM: "balance",
|
||||
PHISHING_REFRESH_ALARM: "phishing",
|
||||
BALANCE_REFRESH_PERIOD_MINUTES: 1,
|
||||
ensureRecurringAlarms: jest.fn(async () => {}),
|
||||
registerAlarmHandlers: jest.fn(),
|
||||
|
||||
@@ -13,7 +13,7 @@ const os = require("os");
|
||||
const path = require("path");
|
||||
|
||||
const { chromium } = require("playwright-core");
|
||||
const { installNetworkStubs } = require("./network");
|
||||
const { installNetworkStubs, WORKER_PROBE_URL } = require("./network");
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, "..", "..");
|
||||
const EXT_PATH = path.join(REPO_ROOT, "dist", "chrome");
|
||||
@@ -129,42 +129,109 @@ function attachErrorListeners(ctx, errors) {
|
||||
// if it ever stops being.
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// The most recently seen background worker, waiting for one if none has
|
||||
// appeared yet. Most recent rather than first: Chrome stops an idle MV3
|
||||
// worker and starts a fresh one on the next event, and a handle to a
|
||||
// stopped worker cannot be evaluated in.
|
||||
async function serviceWorker(ctx) {
|
||||
const [existing] = ctx.serviceWorkers();
|
||||
if (existing) return existing;
|
||||
const workers = ctx.serviceWorkers();
|
||||
const latest = workers[workers.length - 1];
|
||||
if (latest) return latest;
|
||||
return ctx.waitForEvent("serviceworker", { timeout: 30000 });
|
||||
}
|
||||
|
||||
// How long to wait for the background worker's first outbound request.
|
||||
//
|
||||
// The margin that actually decides whether this check is sound is not
|
||||
// this timeout — it is whether the route handler is installed before the
|
||||
// worker fetches. Measured over several runs: route installation
|
||||
// completes 11-23ms after the context comes up, and the worker's
|
||||
// blocklist fetch arrives 525-883ms after that, so the route wins by
|
||||
// roughly 25-50x. This 30s figure is only slack for a loaded machine on
|
||||
// top of that; losing the race fails the run rather than passing it
|
||||
// quietly, which was verified by forcing a 3s delay before route
|
||||
// installation.
|
||||
// How long to wait for the probe request the worker is asked to make.
|
||||
const WORKER_TRAFFIC_TIMEOUT_MS = 30000;
|
||||
|
||||
// ctx.route() only sees service-worker requests when Playwright runs with
|
||||
// PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1, which script/test-e2e
|
||||
// sets. Without it the worker's traffic — notably the phishing blocklist
|
||||
// fetch src/background/index.js issues at startup — goes to the real
|
||||
// internet, and nothing says so, because src/shared/phishingDomains.js
|
||||
// swallows fetch failures. A harness whose isolation can lapse in silence
|
||||
// is worthless, so this does not take the flag on trust: the background
|
||||
// worker's own startup fetch has to show up in the route handler, or the
|
||||
// suite refuses to run.
|
||||
// sets. Without it every fetch the background worker makes goes to the
|
||||
// real internet and nothing says so. A harness whose isolation can lapse
|
||||
// in silence is worthless, so this does not take the flag on trust: a
|
||||
// request the worker itself issues has to show up in the route handler,
|
||||
// or the suite refuses to run.
|
||||
//
|
||||
// Deliberately NOT a synthetic probe fetched through worker.evaluate():
|
||||
// evaluating in an extension worker this early kills it (the call fails
|
||||
// with "Target page, context or browser has been closed" and the worker
|
||||
// disappears), which would break the very thing being measured. Observing
|
||||
// traffic the extension already generates costs nothing and cannot
|
||||
// perturb it.
|
||||
async function assertWorkerTrafficIntercepted(stubs) {
|
||||
// The anchor is a probe the harness asks the worker for, not traffic the
|
||||
// extension generates on its own. It used to be the phishing blocklist
|
||||
// fetch src/background/index.js issued at startup; that fetch is gone —
|
||||
// the blocklist is vendored at build time and the extension contacts
|
||||
// nobody when it starts — so there is no longer any startup traffic to
|
||||
// observe and the check generates its own.
|
||||
//
|
||||
// Evaluating in the worker straight after launch does not work, and that
|
||||
// is not a stale observation: it was tried again here and failed with
|
||||
// "Target page, context or browser has been closed" on the first run.
|
||||
// Chrome stops the freshly registered worker as soon as it has nothing to
|
||||
// do, and the extension no longer gives it anything to do — which is the
|
||||
// same change that removed the old anchor. So the probe wakes the worker
|
||||
// before it evaluates in it, by sending it a message from an extension
|
||||
// page and waiting for the reply: delivering a message is what starts a
|
||||
// stopped worker, and a worker that has just answered one is alive.
|
||||
// The evaluated fetch is not awaited, so nothing in the worker is held
|
||||
// open by the probe either.
|
||||
async function wakeWorker(ctx) {
|
||||
const sw = await serviceWorker(ctx);
|
||||
const extensionId = new URL(sw.url()).host;
|
||||
const page = await ctx.newPage();
|
||||
try {
|
||||
await page.goto(
|
||||
"chrome-extension://" + extensionId + "/src/popup/index.html",
|
||||
);
|
||||
// eth_chainId is answered from local state: it wakes the worker
|
||||
// and changes nothing.
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
chrome.runtime.sendMessage(
|
||||
{
|
||||
type: "AUTISTMASK_RPC",
|
||||
method: "eth_chainId",
|
||||
params: [],
|
||||
},
|
||||
() => resolve(null),
|
||||
);
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function probeFromWorker(ctx, url) {
|
||||
let lastError = null;
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
try {
|
||||
await wakeWorker(ctx);
|
||||
const sw = await serviceWorker(ctx);
|
||||
await sw.evaluate((u) => {
|
||||
// Deliberately not awaited and never rejected: what is
|
||||
// being observed is that the request reaches the route
|
||||
// handler, and an unhandled rejection in the worker would
|
||||
// be collected as a suite error if it did not.
|
||||
fetch(u).catch(() => {});
|
||||
}, url);
|
||||
return;
|
||||
} catch (e) {
|
||||
lastError = e;
|
||||
await sleep(500);
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
"could not ask the background worker to fetch " +
|
||||
url +
|
||||
", so service-worker interception was never tested. Last " +
|
||||
"error: " +
|
||||
(lastError && lastError.message),
|
||||
);
|
||||
}
|
||||
|
||||
async function assertWorkerTrafficIntercepted(ctx, stubs) {
|
||||
await probeFromWorker(ctx, WORKER_PROBE_URL);
|
||||
|
||||
const seen = await stubs.waitForServiceWorkerTraffic(
|
||||
WORKER_TRAFFIC_TIMEOUT_MS,
|
||||
);
|
||||
@@ -177,19 +244,16 @@ async function assertWorkerTrafficIntercepted(stubs) {
|
||||
throw new Error(
|
||||
"observed no service-worker request in the route handler within " +
|
||||
WORKER_TRAFFIC_TIMEOUT_MS +
|
||||
"ms. Under working interception the background worker's " +
|
||||
"startup blocklist fetch (src/background/index.js) reaches the " +
|
||||
"handler about half a second after the route is installed. " +
|
||||
"Two causes are plausible and this check cannot distinguish " +
|
||||
"ms, although the background worker was asked to fetch " +
|
||||
WORKER_PROBE_URL +
|
||||
". Two causes are plausible and this check cannot distinguish " +
|
||||
"them: (1) service-worker interception is not in effect, so " +
|
||||
"that traffic went to the real internet unobserved — the suite " +
|
||||
"that request went to the real internet unobserved — the suite " +
|
||||
"must be run through script/test-e2e, which sets " +
|
||||
"PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1, and a " +
|
||||
"Playwright upgrade may have dropped or renamed that flag; " +
|
||||
"(2) no worker request was made in the first place — the route " +
|
||||
"lost the startup race, or the worker no longer fetches at " +
|
||||
"startup, in which case this check needs a new anchor because " +
|
||||
"there is no longer any worker traffic to observe. Either way " +
|
||||
"(2) the probe never ran, because the worker was torn down " +
|
||||
"between being handed over and being evaluated in. Either way " +
|
||||
"the fix is a replacement mechanism or an honest downgrade of " +
|
||||
"the isolation claims in tests/e2e/network.js and README.md — " +
|
||||
"not deleting this check",
|
||||
@@ -241,7 +305,7 @@ async function launch(routeOpts) {
|
||||
routeOpts.report = (text) => errors.record("network", text);
|
||||
const stubs = await installNetworkStubs(ctx, routeOpts);
|
||||
|
||||
await assertWorkerTrafficIntercepted(stubs);
|
||||
await assertWorkerTrafficIntercepted(ctx, stubs);
|
||||
|
||||
// The extension id is derived from the unpacked path, so it
|
||||
// changes and must never be hardcoded. It is the host part of the
|
||||
|
||||
@@ -9,13 +9,12 @@
|
||||
//
|
||||
// Service-worker coverage is not free: ctx.route() only sees worker
|
||||
// traffic when PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1 is set in
|
||||
// the environment, which script/test-e2e does. Without it the phishing
|
||||
// blocklist fetch that src/background/index.js issues at worker startup
|
||||
// silently reaches raw.githubusercontent.com on the open internet, and
|
||||
// src/shared/phishingDomains.js swallows the failure so nothing surfaces
|
||||
// it. That is not left to trust: waitForServiceWorkerTraffic() below
|
||||
// backs the launch-time canary in harness.js, which fails the entire
|
||||
// suite if worker requests stop being visible here.
|
||||
// the environment, which script/test-e2e does. Without it every fetch the
|
||||
// MV3 background worker makes — the JSON-RPC calls behind every approval
|
||||
// in this suite among them — goes to the real internet unobserved. That is
|
||||
// not left to trust: waitForServiceWorkerTraffic() below backs the
|
||||
// launch-time canary in harness.js, which fails the entire suite if worker
|
||||
// requests stop being visible here.
|
||||
//
|
||||
// Anything not explicitly stubbed here is aborted AND reported to the
|
||||
// error collector, so a newly added outbound call shows up as a test
|
||||
@@ -103,6 +102,22 @@ function word(value) {
|
||||
const DAPP_ORIGIN = "https://dapp.e2e.test";
|
||||
const DAPP_URL = DAPP_ORIGIN + "/";
|
||||
|
||||
// The same page, served from a hostname that is on the vendored phishing
|
||||
// blocklist, so the phishing warning can be driven end to end against the real
|
||||
// list rather than a stub of it. It is a live entry at the pinned upstream
|
||||
// commit; upstream prunes, so a re-vendoring run that retires it turns the
|
||||
// phishing test red, and the fix is a current entry, not a weaker assertion.
|
||||
const PHISHING_DAPP_ORIGIN = "https://myetheywallet.com";
|
||||
const PHISHING_DAPP_URL = PHISHING_DAPP_ORIGIN + "/";
|
||||
|
||||
// A request the harness asks the background service worker to make, purely so
|
||||
// that worker interception can be proved before any test runs. Nothing in the
|
||||
// extension fetches at startup any more — the blocklist is vendored at build
|
||||
// time — so the canary in harness.js has no product traffic to anchor on and
|
||||
// generates its own. See assertWorkerTrafficIntercepted().
|
||||
const WORKER_PROBE_ORIGIN = "https://worker-probe.e2e.test";
|
||||
const WORKER_PROBE_URL = WORKER_PROBE_ORIGIN + "/canary";
|
||||
|
||||
// Requests are parked rather than awaited. An approval prompt only exists
|
||||
// while its call is in flight, so a test that awaited the promise could
|
||||
// never drive the popup that has to settle it; start() files the promise
|
||||
@@ -555,10 +570,9 @@ async function installNetworkStubs(ctx, opts) {
|
||||
// E2E_TRACE_NETWORK=1 prints every request that reaches this handler,
|
||||
// tagged [sw] when it originated in the background service worker.
|
||||
// It exists so the isolation claim above can be re-checked by anyone
|
||||
// in one command, without editing files: the phishing blocklist fetch
|
||||
// showing up with an [sw] tag is the proof that the worker really is
|
||||
// intercepted and that the raw.githubusercontent.com stub below is
|
||||
// live code rather than decoration.
|
||||
// in one command, without editing files: the canary probe and then
|
||||
// every JSON-RPC call behind an approval showing up with an [sw] tag
|
||||
// is the proof that the worker really is intercepted.
|
||||
const trace = traceEnabled(process.env.E2E_TRACE_NETWORK);
|
||||
|
||||
// Regex rather than a glob so chrome-extension:// resource loads are
|
||||
@@ -589,7 +603,11 @@ async function installNetworkStubs(ctx, opts) {
|
||||
// trips run against a real http(s) origin — which is what makes the
|
||||
// shipped content scripts inject at all — without any remote origin
|
||||
// being involved.
|
||||
if (url.origin === DAPP_ORIGIN && p === "/") {
|
||||
if (
|
||||
(url.origin === DAPP_ORIGIN ||
|
||||
url.origin === PHISHING_DAPP_ORIGIN) &&
|
||||
p === "/"
|
||||
) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: "text/html; charset=utf-8",
|
||||
@@ -635,18 +653,10 @@ async function installNetworkStubs(ctx, opts) {
|
||||
return jsonResponse(route, { Data: {} });
|
||||
}
|
||||
|
||||
// MetaMask phishing blocklist
|
||||
if (
|
||||
url.hostname === "raw.githubusercontent.com" ||
|
||||
p.endsWith("/eth-phishing-detect/main/src/config.json")
|
||||
) {
|
||||
return jsonResponse(route, {
|
||||
version: 2,
|
||||
tolerance: 2,
|
||||
fuzzylist: [],
|
||||
whitelist: [],
|
||||
blacklist: [],
|
||||
});
|
||||
// The interception canary's own request. Answered with nothing: what
|
||||
// is being observed is that it arrived here at all.
|
||||
if (url.href === WORKER_PROBE_URL) {
|
||||
return route.fulfill({ status: 204, body: "" });
|
||||
}
|
||||
|
||||
// Best-effort Etherscan address labels: served as an empty page.
|
||||
@@ -667,12 +677,12 @@ async function installNetworkStubs(ctx, opts) {
|
||||
* Resolve with the first service-worker-originated request this
|
||||
* handler saw, or null if none arrives within `ms`.
|
||||
*
|
||||
* The background worker fetches the phishing blocklist at
|
||||
* startup, unconditionally, within about a second of the context
|
||||
* coming up — so under working interception this resolves almost
|
||||
* immediately. Nothing arriving means worker traffic is bypassing
|
||||
* the handler entirely and going to the real internet, which the
|
||||
* caller turns into a hard failure of the whole suite.
|
||||
* The caller asks the worker for one request of its own (see
|
||||
* WORKER_PROBE_URL) and then waits here, so under working
|
||||
* interception this resolves almost immediately. Nothing arriving
|
||||
* means worker traffic is bypassing the handler entirely and going
|
||||
* to the real internet, which the caller turns into a hard failure
|
||||
* of the whole suite.
|
||||
*/
|
||||
waitForServiceWorkerTraffic(ms) {
|
||||
if (firstWorkerRequest) return Promise.resolve(firstWorkerRequest);
|
||||
@@ -696,6 +706,9 @@ module.exports = {
|
||||
DAPP_HTML,
|
||||
DAPP_ORIGIN,
|
||||
DAPP_URL,
|
||||
PHISHING_DAPP_ORIGIN,
|
||||
PHISHING_DAPP_URL,
|
||||
WORKER_PROBE_URL,
|
||||
FEE_ESTIMATE_WEI,
|
||||
FEE_RESERVE_WEI,
|
||||
STUB_COUNTERPARTY,
|
||||
|
||||
@@ -33,6 +33,7 @@ const {
|
||||
const {
|
||||
DAPP_ORIGIN,
|
||||
DAPP_URL,
|
||||
PHISHING_DAPP_URL,
|
||||
FEE_ESTIMATE_WEI,
|
||||
FEE_RESERVE_WEI,
|
||||
STUB_COUNTERPARTY,
|
||||
@@ -2069,9 +2070,9 @@ async function extensionActiveAddress(page) {
|
||||
return getAddress(address);
|
||||
}
|
||||
|
||||
async function openDapp(ctx) {
|
||||
async function openDapp(ctx, url = DAPP_URL) {
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(DAPP_URL);
|
||||
await page.goto(url);
|
||||
// window.ethereum is not the fixture's doing — it is the shipped
|
||||
// MAIN-world content script. Waiting for it is waiting for the real
|
||||
// provider to have injected itself into a real http(s) origin.
|
||||
@@ -2543,6 +2544,15 @@ test("eth_requestAccounts rejected at the prompt returns a rejection (#183)", as
|
||||
JSON.stringify(hostname),
|
||||
);
|
||||
|
||||
// The control for the phishing test below: this origin is not on the
|
||||
// blocklist, so the banner must be absent here. Without it a banner
|
||||
// that was simply always visible would satisfy that test.
|
||||
assert(
|
||||
await popup.locator("#approve-site-phishing-warning").isHidden(),
|
||||
"the phishing warning is showing for an origin that is not on " +
|
||||
"the blocklist, so its appearance proves nothing",
|
||||
);
|
||||
|
||||
// Deliberately not remembered: a remembered rejection lands the
|
||||
// origin in deniedSites and every later test in this section is
|
||||
// auto-rejected with no prompt at all, which would look like a pass.
|
||||
@@ -2606,6 +2616,53 @@ test("eth_requestAccounts approved returns the selected address (#183)", async (
|
||||
);
|
||||
});
|
||||
|
||||
test("a connect request from a blocklisted site is flagged (#219)", async (env) => {
|
||||
// The vendored blocklist, end to end: a real entry from the shipped
|
||||
// artifact, served as a real http(s) origin, reaching the real background
|
||||
// check and the real approval screen. Nothing about the list is stubbed —
|
||||
// there is nothing left to stub, since the extension no longer fetches it.
|
||||
const phishingDapp = await openDapp(env.ctx, PHISHING_DAPP_URL);
|
||||
const hostname = new URL(PHISHING_DAPP_URL).hostname;
|
||||
try {
|
||||
await reserveApprovalTab(env);
|
||||
await startRequest(
|
||||
phishingDapp,
|
||||
"phishing-accounts",
|
||||
"eth_requestAccounts",
|
||||
[],
|
||||
);
|
||||
const popup = await openSiteApprovalPopup(env);
|
||||
try {
|
||||
await visible(popup, "#view-approve-site");
|
||||
|
||||
const shown = await popup.locator("#approve-hostname").innerText();
|
||||
assert(
|
||||
shown === hostname,
|
||||
"the site prompt names the wrong origin: " +
|
||||
JSON.stringify(shown),
|
||||
);
|
||||
|
||||
await visible(popup, "#approve-site-phishing-warning");
|
||||
console.log("# phishing warning shown for " + hostname);
|
||||
|
||||
// Not remembered: a remembered decision for this origin would
|
||||
// outlive the test.
|
||||
await popup.uncheck("#approve-remember");
|
||||
await popup.click("#btn-reject");
|
||||
|
||||
await assertUserRejection(
|
||||
phishingDapp,
|
||||
"phishing-accounts",
|
||||
"the blocklisted site's eth_requestAccounts",
|
||||
);
|
||||
} finally {
|
||||
await closeApprovalPages(env.ctx);
|
||||
}
|
||||
} finally {
|
||||
await phishingDapp.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("personal_sign signs, and the signature recovers to the address (#183)", async (env) => {
|
||||
await startRequest(env.dapp, "sign", "personal_sign", [
|
||||
SIGN_HEX,
|
||||
|
||||
@@ -1,573 +1,219 @@
|
||||
// Extension storage stub for the Node test environment. The module resolves
|
||||
// the storage API on use, so this only has to exist before the first call.
|
||||
// Values round-trip through JSON the way structured cloning would, so a test
|
||||
// cannot pass by holding a live reference to the module's own array.
|
||||
const storageStore = {};
|
||||
global.chrome = {
|
||||
storage: {
|
||||
local: {
|
||||
get: async (key) =>
|
||||
Object.prototype.hasOwnProperty.call(storageStore, key)
|
||||
? { [key]: JSON.parse(JSON.stringify(storageStore[key])) }
|
||||
: {},
|
||||
set: async (items) => {
|
||||
for (const [key, value] of Object.entries(items)) {
|
||||
storageStore[key] = JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
},
|
||||
remove: async (key) => {
|
||||
delete storageStore[key];
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
// The phishing blocklist is vendored at build time and shipped as digests:
|
||||
// script/vendor-blocklist writes src/shared/phishingBlocklist.json, and nothing
|
||||
// fetches anything at runtime. Two things therefore have to be proven here, and
|
||||
// the second is the one that would otherwise fail silently:
|
||||
//
|
||||
// - real domains from the vendored list are detected, and clean ones are not.
|
||||
// - a malformed artifact fails loudly. Every way of getting the artifact
|
||||
// wrong produces a blocklist that matches nothing while looking healthy,
|
||||
// which is a phishing check that answers "no" to everything.
|
||||
|
||||
const {
|
||||
isPhishingDomain,
|
||||
loadConfig,
|
||||
getBlocklistSize,
|
||||
getDeltaSize,
|
||||
hostnameVariants,
|
||||
DELTA_STORAGE_KEY,
|
||||
_reset,
|
||||
_getVendoredBlacklistSize,
|
||||
_getDeltaBlacklist,
|
||||
} = require("../src/shared/phishingDomains");
|
||||
const { HASH_HEX_CHARS, hashDomain } = require("../src/shared/domainHash");
|
||||
const vendored = require("../src/shared/phishingBlocklist.json");
|
||||
|
||||
function clearStorage() {
|
||||
for (const key of Object.keys(storageStore)) {
|
||||
delete storageStore[key];
|
||||
}
|
||||
}
|
||||
// Domains present in the vendored list at the pinned upstream commit. Upstream
|
||||
// prunes as well as adds, so re-vendoring can retire one of these and turn this
|
||||
// red; that is the intended prompt to pick a current entry, not a licence to
|
||||
// weaken the assertion into "some domain somewhere matches".
|
||||
const LISTED = [
|
||||
"0-google.ph",
|
||||
"myetheywallet.com",
|
||||
// An underscore is not legal in a hostname, but DNS carries one and
|
||||
// browsers resolve it, and upstream lists well over a hundred phishing
|
||||
// sites that use one. The vendoring transform keeps them.
|
||||
"phntum-wallett.godaddysites.com",
|
||||
"coinbase_prologin1.godaddysites.com",
|
||||
];
|
||||
|
||||
// The MV3 service worker is torn down when idle and re-evaluated on the next
|
||||
// event, which wipes every module-level variable. Re-requiring the module with
|
||||
// the registry reset is exactly that: fresh in-memory state, same extension
|
||||
// storage underneath.
|
||||
function restartWorker() {
|
||||
jest.resetModules();
|
||||
return require("../src/shared/phishingDomains");
|
||||
}
|
||||
// Not on the list, and the kind of host a user actually visits.
|
||||
const CLEAN = ["etherscan.io", "example.com", "opensea.io", "sneak.berlin"];
|
||||
|
||||
// Reset delta state before each test to avoid cross-test contamination.
|
||||
// Note: vendored sets are immutable and always present.
|
||||
beforeEach(() => {
|
||||
_reset();
|
||||
clearStorage();
|
||||
});
|
||||
|
||||
describe("phishingDomains", () => {
|
||||
describe("vendored blocklist", () => {
|
||||
test("vendored blacklist is loaded from bundled JSON", () => {
|
||||
// The vendored blocklist should have a large number of entries
|
||||
expect(_getVendoredBlacklistSize()).toBeGreaterThan(100000);
|
||||
});
|
||||
|
||||
test("detects domains from vendored blacklist", () => {
|
||||
// These are well-known phishing domains in the vendored list
|
||||
expect(isPhishingDomain("hopprotocol.pro")).toBe(true);
|
||||
expect(isPhishingDomain("blast-pools.pages.dev")).toBe(true);
|
||||
});
|
||||
|
||||
test("getBlocklistSize includes vendored entries", () => {
|
||||
expect(getBlocklistSize()).toBeGreaterThan(100000);
|
||||
});
|
||||
describe("vendored blocklist", () => {
|
||||
test("the artifact holds the whole list", () => {
|
||||
expect(getBlocklistSize()).toBeGreaterThan(100000);
|
||||
expect(vendored.hashes).toHaveLength(vendored.count * HASH_HEX_CHARS);
|
||||
});
|
||||
|
||||
describe("hostnameVariants", () => {
|
||||
test("returns exact hostname plus parent domains", () => {
|
||||
const variants = hostnameVariants("sub.evil.com");
|
||||
expect(variants).toEqual(["sub.evil.com", "evil.com"]);
|
||||
});
|
||||
|
||||
test("returns just the hostname for a bare domain", () => {
|
||||
const variants = hostnameVariants("example.com");
|
||||
expect(variants).toEqual(["example.com"]);
|
||||
});
|
||||
|
||||
test("handles deep subdomain chains", () => {
|
||||
const variants = hostnameVariants("a.b.c.d.com");
|
||||
expect(variants).toEqual([
|
||||
"a.b.c.d.com",
|
||||
"b.c.d.com",
|
||||
"c.d.com",
|
||||
"d.com",
|
||||
]);
|
||||
});
|
||||
|
||||
test("lowercases hostnames", () => {
|
||||
const variants = hostnameVariants("Evil.COM");
|
||||
expect(variants).toEqual(["evil.com"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("delta computation via loadConfig", () => {
|
||||
test("loadConfig computes delta of new entries not in vendored list", () => {
|
||||
loadConfig({
|
||||
blacklist: [
|
||||
"brand-new-scam-site-xyz123.com",
|
||||
"hopprotocol.pro", // already in vendored
|
||||
],
|
||||
});
|
||||
// Only the new domain should be in the delta
|
||||
expect(
|
||||
_getDeltaBlacklist().has("brand-new-scam-site-xyz123.com"),
|
||||
).toBe(true);
|
||||
expect(_getDeltaBlacklist().has("hopprotocol.pro")).toBe(false);
|
||||
expect(getDeltaSize()).toBe(1);
|
||||
});
|
||||
|
||||
test("re-loading config replaces previous delta", () => {
|
||||
loadConfig({
|
||||
blacklist: ["first-scam-xyz.com"],
|
||||
});
|
||||
expect(isPhishingDomain("first-scam-xyz.com")).toBe(true);
|
||||
|
||||
loadConfig({
|
||||
blacklist: ["second-scam-xyz.com"],
|
||||
});
|
||||
expect(isPhishingDomain("first-scam-xyz.com")).toBe(false);
|
||||
expect(isPhishingDomain("second-scam-xyz.com")).toBe(true);
|
||||
});
|
||||
|
||||
test("getBlocklistSize includes both vendored and delta", () => {
|
||||
const baseSize = getBlocklistSize();
|
||||
loadConfig({
|
||||
blacklist: ["delta-only-scam-xyz.com"],
|
||||
});
|
||||
expect(getBlocklistSize()).toBe(baseSize + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPhishingDomain with delta + vendored", () => {
|
||||
test("detects domain from delta blacklist", () => {
|
||||
loadConfig({
|
||||
blacklist: ["fresh-scam-xyz.com"],
|
||||
});
|
||||
expect(isPhishingDomain("fresh-scam-xyz.com")).toBe(true);
|
||||
});
|
||||
|
||||
test("detects domain from vendored blacklist", () => {
|
||||
// No delta loaded — vendored still works
|
||||
expect(isPhishingDomain("hopprotocol.pro")).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for clean domains", () => {
|
||||
expect(isPhishingDomain("etherscan.io")).toBe(false);
|
||||
expect(isPhishingDomain("example.com")).toBe(false);
|
||||
});
|
||||
|
||||
test("detects subdomain of blacklisted domain (vendored)", () => {
|
||||
expect(isPhishingDomain("app.hopprotocol.pro")).toBe(true);
|
||||
});
|
||||
|
||||
test("detects subdomain of blacklisted domain (delta)", () => {
|
||||
loadConfig({
|
||||
blacklist: ["delta-phish-xyz.com"],
|
||||
});
|
||||
expect(isPhishingDomain("sub.delta-phish-xyz.com")).toBe(true);
|
||||
});
|
||||
|
||||
test("case-insensitive matching", () => {
|
||||
loadConfig({
|
||||
blacklist: ["Delta-Scam-XYZ.COM"],
|
||||
});
|
||||
expect(isPhishingDomain("delta-scam-xyz.com")).toBe(true);
|
||||
expect(isPhishingDomain("DELTA-SCAM-XYZ.COM")).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for empty/null hostname", () => {
|
||||
expect(isPhishingDomain("")).toBe(false);
|
||||
expect(isPhishingDomain(null)).toBe(false);
|
||||
});
|
||||
|
||||
test("handles config with no blacklist key", () => {
|
||||
loadConfig({});
|
||||
expect(getDeltaSize()).toBe(0);
|
||||
// Vendored list still works
|
||||
expect(isPhishingDomain("hopprotocol.pro")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extension storage persistence", () => {
|
||||
test("delta is persisted to extension storage, not localStorage", async () => {
|
||||
await loadConfig({
|
||||
blacklist: ["persisted-scam-xyz.com"],
|
||||
});
|
||||
const stored = storageStore[DELTA_STORAGE_KEY];
|
||||
expect(stored).toBeDefined();
|
||||
expect(stored.blacklist).toContain("persisted-scam-xyz.com");
|
||||
});
|
||||
|
||||
test("the fetch timestamp is persisted alongside the delta", async () => {
|
||||
const before = Date.now();
|
||||
await loadConfig({ blacklist: ["timestamped-scam-xyz.com"] });
|
||||
const stored = storageStore[DELTA_STORAGE_KEY];
|
||||
expect(typeof stored.lastFetchTime).toBe("number");
|
||||
expect(stored.lastFetchTime).toBeGreaterThanOrEqual(before);
|
||||
});
|
||||
|
||||
test("an oversized delta is dropped entirely, timestamp included", async () => {
|
||||
// A record above the 256 KiB cap is not worth keeping; the
|
||||
// timestamp goes with it so the next start re-fetches rather than
|
||||
// claiming freshness for a delta that was never stored.
|
||||
const huge = [];
|
||||
for (let i = 0; i < 20000; i++) {
|
||||
huge.push(`oversize-scam-${i}-xyzxyzxyzxyzxyz.com`);
|
||||
test("the digests are sorted and unique", () => {
|
||||
// The lookup is a binary search over the concatenated digests. An
|
||||
// unsorted or duplicated artifact would fail lookups quietly rather
|
||||
// than loudly, so the ordering the search depends on is asserted here
|
||||
// against the committed file rather than assumed of the generator.
|
||||
// One assertion at the end rather than one per entry: 100k+ expect()
|
||||
// calls cost seconds, and make test is capped at 30 for the whole
|
||||
// suite. The index of the first offender is reported, so a failure
|
||||
// still says where.
|
||||
let previous = "";
|
||||
let outOfOrderAt = -1;
|
||||
for (let i = 0; i < vendored.count; i++) {
|
||||
const at = vendored.hashes.slice(
|
||||
i * HASH_HEX_CHARS,
|
||||
(i + 1) * HASH_HEX_CHARS,
|
||||
);
|
||||
if (at <= previous) {
|
||||
outOfOrderAt = i;
|
||||
break;
|
||||
}
|
||||
await loadConfig({ blacklist: huge });
|
||||
expect(storageStore[DELTA_STORAGE_KEY]).toBeUndefined();
|
||||
});
|
||||
|
||||
test("delta is cleared on _reset", () => {
|
||||
loadConfig({
|
||||
blacklist: ["temp-scam-xyz.com"],
|
||||
});
|
||||
expect(getDeltaSize()).toBe(1);
|
||||
_reset();
|
||||
expect(getDeltaSize()).toBe(0);
|
||||
});
|
||||
previous = at;
|
||||
}
|
||||
expect(outOfOrderAt).toBe(-1);
|
||||
});
|
||||
|
||||
describe("real-world blocklist patterns", () => {
|
||||
test("detects known phishing domains from vendored list", () => {
|
||||
expect(isPhishingDomain("uniswap-trade.web.app")).toBe(true);
|
||||
expect(isPhishingDomain("hopprotocol.pro")).toBe(true);
|
||||
expect(isPhishingDomain("blast-pools.pages.dev")).toBe(true);
|
||||
});
|
||||
test("every digest is lowercase hex of the declared width", () => {
|
||||
expect(vendored.hashes).toMatch(/^[0-9a-f]*$/);
|
||||
});
|
||||
|
||||
test("does not flag legitimate domains", () => {
|
||||
expect(isPhishingDomain("opensea.io")).toBe(false);
|
||||
expect(isPhishingDomain("etherscan.io")).toBe(false);
|
||||
});
|
||||
test("detects domains from the vendored list", () => {
|
||||
for (const domain of LISTED) {
|
||||
expect(isPhishingDomain(domain)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("does not flag legitimate domains", () => {
|
||||
for (const domain of CLEAN) {
|
||||
expect(isPhishingDomain(domain)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("detects a subdomain of a listed domain", () => {
|
||||
expect(isPhishingDomain("wallet." + LISTED[0])).toBe(true);
|
||||
expect(isPhishingDomain("a.b.c." + LISTED[0])).toBe(true);
|
||||
});
|
||||
|
||||
test("matching is case-insensitive", () => {
|
||||
expect(isPhishingDomain(LISTED[0].toUpperCase())).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for an empty or missing hostname", () => {
|
||||
expect(isPhishingDomain("")).toBe(false);
|
||||
expect(isPhishingDomain(null)).toBe(false);
|
||||
expect(isPhishingDomain(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("the first and last entries are both reachable", () => {
|
||||
// The ends are where an off-by-one in a binary search hides: a search
|
||||
// that never examines index 0 or index count-1 still finds everything
|
||||
// in between, and the real list is not searched exhaustively here.
|
||||
const first = vendored.hashes.slice(0, HASH_HEX_CHARS);
|
||||
const last = vendored.hashes.slice(-HASH_HEX_CHARS);
|
||||
const { _hashListed } = require("../src/shared/phishingDomains");
|
||||
expect(_hashListed(first)).toBe(true);
|
||||
expect(_hashListed(last)).toBe(true);
|
||||
expect(_hashListed("0".repeat(HASH_HEX_CHARS))).toBe(false);
|
||||
expect(_hashListed("f".repeat(HASH_HEX_CHARS))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("phishing list across a service worker restart", () => {
|
||||
beforeEach(() => {
|
||||
clearStorage();
|
||||
jest.resetModules();
|
||||
describe("hostnameVariants", () => {
|
||||
test("returns exact hostname plus parent domains", () => {
|
||||
expect(hostnameVariants("sub.evil.com")).toEqual([
|
||||
"sub.evil.com",
|
||||
"evil.com",
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
test("returns just the hostname for a bare domain", () => {
|
||||
expect(hostnameVariants("example.com")).toEqual(["example.com"]);
|
||||
});
|
||||
|
||||
test("a revived worker restores the persisted delta without re-fetching", async () => {
|
||||
const first = require("../src/shared/phishingDomains");
|
||||
await first.loadConfig({ blacklist: ["restart-scam-xyz.com"] });
|
||||
|
||||
const revived = restartWorker();
|
||||
// Nothing in memory yet — this is a brand new module instance.
|
||||
expect(revived.getDeltaSize()).toBe(0);
|
||||
|
||||
global.fetch = jest.fn();
|
||||
await revived.initPhishingList();
|
||||
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
expect(revived.getDeltaSize()).toBe(1);
|
||||
expect(revived.isPhishingDomain("restart-scam-xyz.com")).toBe(true);
|
||||
test("handles deep subdomain chains", () => {
|
||||
expect(hostnameVariants("a.b.c.d.com")).toEqual([
|
||||
"a.b.c.d.com",
|
||||
"b.c.d.com",
|
||||
"c.d.com",
|
||||
"d.com",
|
||||
]);
|
||||
});
|
||||
|
||||
test("repeated wakes inside the cache window never re-fetch", async () => {
|
||||
const first = require("../src/shared/phishingDomains");
|
||||
await first.loadConfig({ blacklist: ["no-storm-scam-xyz.com"] });
|
||||
|
||||
global.fetch = jest.fn();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const revived = restartWorker();
|
||||
await revived.initPhishingList();
|
||||
}
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("a persisted timestamp older than the TTL causes a fetch on startup", async () => {
|
||||
const first = require("../src/shared/phishingDomains");
|
||||
await first.loadConfig({ blacklist: ["stale-scam-xyz.com"] });
|
||||
|
||||
// Age the persisted record past the 24-hour TTL.
|
||||
storageStore[first.DELTA_STORAGE_KEY].lastFetchTime =
|
||||
Date.now() - first.CACHE_TTL_MS - 1000;
|
||||
|
||||
const revived = restartWorker();
|
||||
global.fetch = jest.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ blacklist: ["refreshed-scam-xyz.com"] }),
|
||||
}));
|
||||
await revived.initPhishingList();
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(revived.isPhishingDomain("refreshed-scam-xyz.com")).toBe(true);
|
||||
expect(revived.isPhishingDomain("stale-scam-xyz.com")).toBe(false);
|
||||
});
|
||||
|
||||
test("a first start with nothing persisted fetches immediately", async () => {
|
||||
const fresh = restartWorker();
|
||||
global.fetch = jest.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ blacklist: ["first-run-scam-xyz.com"] }),
|
||||
}));
|
||||
await fresh.initPhishingList();
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(fresh.isPhishingDomain("first-run-scam-xyz.com")).toBe(true);
|
||||
});
|
||||
|
||||
test("updatePhishingList honours the persisted timestamp on its own", async () => {
|
||||
// The startup path calls updatePhishingList() directly, so it must
|
||||
// load persisted state itself rather than relying on anything else
|
||||
// having finished first.
|
||||
const first = require("../src/shared/phishingDomains");
|
||||
await first.loadConfig({ blacklist: ["alarm-tick-scam-xyz.com"] });
|
||||
|
||||
const revived = restartWorker();
|
||||
global.fetch = jest.fn();
|
||||
await revived.updatePhishingList();
|
||||
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
expect(revived.isPhishingDomain("alarm-tick-scam-xyz.com")).toBe(true);
|
||||
test("lowercases hostnames", () => {
|
||||
expect(hostnameVariants("Evil.COM")).toEqual(["evil.com"]);
|
||||
});
|
||||
});
|
||||
|
||||
// The alarm period alone must set the cadence. lastFetchTime is stamped when
|
||||
// the fetch completes, so it lands one fetch latency after the alarm that
|
||||
// caused it; a freshness guard timed to the alarm period therefore vetoes
|
||||
// every scheduled tick and halves the real refresh rate. These tests measure
|
||||
// the interval between fetches that actually happened.
|
||||
describe("phishing refresh steady-state cadence", () => {
|
||||
const { PHISHING_REFRESH_PERIOD_MINUTES } = require("../src/shared/alarms");
|
||||
const PERIOD_MS = PHISHING_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
||||
|
||||
let clockSpy;
|
||||
let now;
|
||||
|
||||
beforeEach(() => {
|
||||
clearStorage();
|
||||
jest.resetModules();
|
||||
now = Date.UTC(2026, 0, 1, 0, 0, 0);
|
||||
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => now);
|
||||
describe("domain hashing", () => {
|
||||
test("a digest is the declared width of lowercase hex", () => {
|
||||
const hash = hashDomain("example.com");
|
||||
expect(hash).toHaveLength(HASH_HEX_CHARS);
|
||||
expect(hash).toMatch(/^[0-9a-f]+$/);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clockSpy.mockRestore();
|
||||
delete global.fetch;
|
||||
test("hashing is case-insensitive, so lookups are too", () => {
|
||||
expect(hashDomain("Evil.COM")).toBe(hashDomain("evil.com"));
|
||||
});
|
||||
|
||||
function fetchStub(latencyMs, seen) {
|
||||
return jest.fn(async () => {
|
||||
seen.push(now);
|
||||
// A network fetch takes time, and lastFetchTime is stamped after
|
||||
// it, not when the alarm fired.
|
||||
now += latencyMs;
|
||||
return { ok: true, json: async () => ({ blacklist: [] }) };
|
||||
test("different domains get different digests", () => {
|
||||
expect(hashDomain("evil.com")).not.toBe(hashDomain("evil.org"));
|
||||
});
|
||||
});
|
||||
|
||||
// A blocklist that silently matches nothing is the failure this module must not
|
||||
// have, so each way of breaking the artifact is required to throw at load. The
|
||||
// generator is the only thing that writes this file, but "the generator is
|
||||
// correct" is not something the shipped extension can check at runtime — this
|
||||
// is what makes a format drift a build failure rather than a silent one.
|
||||
describe("a malformed artifact fails loudly", () => {
|
||||
const GOOD = {
|
||||
algorithm: "sha256",
|
||||
hashHexChars: HASH_HEX_CHARS,
|
||||
count: 2,
|
||||
hashes: "0".repeat(HASH_HEX_CHARS) + "1".repeat(HASH_HEX_CHARS),
|
||||
};
|
||||
|
||||
function loadWith(artifact) {
|
||||
let mod;
|
||||
jest.isolateModules(() => {
|
||||
jest.doMock(
|
||||
"../src/shared/phishingBlocklist.json",
|
||||
() => artifact,
|
||||
{
|
||||
virtual: false,
|
||||
},
|
||||
);
|
||||
mod = require("../src/shared/phishingDomains");
|
||||
});
|
||||
return mod;
|
||||
}
|
||||
|
||||
test("ten alarm ticks produce ten fetches, one per period", async () => {
|
||||
const fetchedAt = [];
|
||||
global.fetch = fetchStub(5000, fetchedAt);
|
||||
|
||||
const startup = require("../src/shared/phishingDomains");
|
||||
const T0 = now;
|
||||
await startup.initPhishingList();
|
||||
expect(fetchedAt).toEqual([T0]);
|
||||
|
||||
const TICKS = 10;
|
||||
let tickAt = T0 + PERIOD_MS;
|
||||
for (let i = 0; i < TICKS; i++) {
|
||||
now = tickAt;
|
||||
tickAt += PERIOD_MS;
|
||||
// The browser wakes a terminated worker to deliver the alarm, so
|
||||
// every tick starts from cold memory and the persisted record.
|
||||
const revived = restartWorker();
|
||||
await revived.refreshPhishingListOnSchedule();
|
||||
}
|
||||
|
||||
expect(fetchedAt).toHaveLength(TICKS + 1);
|
||||
const intervals = fetchedAt.slice(1).map((t, i) => t - fetchedAt[i]);
|
||||
expect(intervals).toEqual(new Array(TICKS).fill(PERIOD_MS));
|
||||
});
|
||||
|
||||
test("the scheduled tick fetches whatever the last fetch's latency was", async () => {
|
||||
// The alarm fires one period after the previous alarm, which is
|
||||
// `latency` short of one period since the fetch it caused completed.
|
||||
for (const latency of [200, 1000, 5000]) {
|
||||
clearStorage();
|
||||
jest.resetModules();
|
||||
storageStore[DELTA_STORAGE_KEY] = {
|
||||
blacklist: [],
|
||||
lastFetchTime: now - PERIOD_MS + latency,
|
||||
lastAttemptTime: now - PERIOD_MS,
|
||||
};
|
||||
const mod = require("../src/shared/phishingDomains");
|
||||
const fetchedAt = [];
|
||||
global.fetch = fetchStub(latency, fetchedAt);
|
||||
|
||||
await mod.refreshPhishingListOnSchedule();
|
||||
expect(fetchedAt).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
|
||||
test("a worker wake inside the cache window still does not fetch", async () => {
|
||||
// The TTL is not removed, only taken off the scheduled path. Chrome
|
||||
// revives the worker every ~30 seconds and every revival runs the
|
||||
// startup path, so the TTL still has to keep that off the network.
|
||||
storageStore[DELTA_STORAGE_KEY] = {
|
||||
blacklist: [],
|
||||
lastFetchTime: now - PERIOD_MS + 5000,
|
||||
lastAttemptTime: now - PERIOD_MS,
|
||||
};
|
||||
const mod = require("../src/shared/phishingDomains");
|
||||
global.fetch = jest.fn();
|
||||
|
||||
await mod.initPhishingList();
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("phishing list timestamps that cannot be trusted", () => {
|
||||
let clockSpy;
|
||||
let now;
|
||||
|
||||
beforeEach(() => {
|
||||
clearStorage();
|
||||
jest.resetModules();
|
||||
now = Date.UTC(2026, 0, 1, 0, 0, 0);
|
||||
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => now);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
clockSpy.mockRestore();
|
||||
delete global.fetch;
|
||||
jest.dontMock("../src/shared/phishingBlocklist.json");
|
||||
});
|
||||
|
||||
function okFetch() {
|
||||
return jest.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ blacklist: ["recovered-scam-xyz.com"] }),
|
||||
}));
|
||||
}
|
||||
|
||||
// jest.resetModules() clears the call record of a jest.fn, and simulating
|
||||
// a worker restart is exactly that call. Anything counted across restarts
|
||||
// has to be counted outside the mock.
|
||||
function countingFetch(counter, response) {
|
||||
return async () => {
|
||||
counter.calls++;
|
||||
return response();
|
||||
};
|
||||
}
|
||||
|
||||
test("a lastFetchTime in the future is discarded rather than trusted", async () => {
|
||||
// Clock skew or a restored profile backup writes one. Every guard
|
||||
// measures `Date.now() - stamp` and only tests the lower bound, so a
|
||||
// stamp a year ahead would suppress updates for a year, and now that
|
||||
// the value is persisted it would outlive every worker.
|
||||
storageStore[DELTA_STORAGE_KEY] = {
|
||||
blacklist: ["poisoned-scam-xyz.com"],
|
||||
lastFetchTime: now + 365 * 24 * 60 * 60 * 1000,
|
||||
lastAttemptTime: 0,
|
||||
};
|
||||
const mod = require("../src/shared/phishingDomains");
|
||||
global.fetch = okFetch();
|
||||
|
||||
await mod.initPhishingList();
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(mod.isPhishingDomain("recovered-scam-xyz.com")).toBe(true);
|
||||
// And the record it leaves behind is sane, so recovery is permanent.
|
||||
expect(
|
||||
storageStore[DELTA_STORAGE_KEY].lastFetchTime,
|
||||
).toBeLessThanOrEqual(now);
|
||||
test("the control artifact loads", () => {
|
||||
expect(loadWith(GOOD).getBlocklistSize()).toBe(2);
|
||||
});
|
||||
|
||||
test("a lastAttemptTime in the future does not suppress the retry", async () => {
|
||||
storageStore[DELTA_STORAGE_KEY] = {
|
||||
lastAttemptTime: now + 365 * 24 * 60 * 60 * 1000,
|
||||
};
|
||||
const mod = require("../src/shared/phishingDomains");
|
||||
global.fetch = okFetch();
|
||||
|
||||
await mod.initPhishingList();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("an oversized delta does not re-download on every worker wake", async () => {
|
||||
// The delta and its freshness claim are both dropped, which is right,
|
||||
// but nothing then says a fetch just happened. Chrome cycles the
|
||||
// worker roughly every 30 seconds idle, so without the attempt stamp
|
||||
// this is a full blocklist download per wake, forever.
|
||||
const huge = [];
|
||||
for (let i = 0; i < 20000; i++) {
|
||||
huge.push(`oversize-scam-${i}-xyzxyzxyzxyzxyz.com`);
|
||||
}
|
||||
const counter = { calls: 0 };
|
||||
global.fetch = countingFetch(counter, () => ({
|
||||
ok: true,
|
||||
json: async () => ({ blacklist: huge }),
|
||||
}));
|
||||
|
||||
for (let wake = 0; wake < 4; wake++) {
|
||||
const revived = restartWorker();
|
||||
await revived.initPhishingList();
|
||||
now += 30 * 1000; // idle timeout, worker torn down and revived
|
||||
}
|
||||
|
||||
expect(counter.calls).toBe(1);
|
||||
expect(storageStore[DELTA_STORAGE_KEY].blacklist).toBeUndefined();
|
||||
expect(typeof storageStore[DELTA_STORAGE_KEY].lastAttemptTime).toBe(
|
||||
"number",
|
||||
test("a different digest algorithm throws", () => {
|
||||
expect(() => loadWith({ ...GOOD, algorithm: "md5" })).toThrow(
|
||||
/algorithm/,
|
||||
);
|
||||
});
|
||||
|
||||
test("a failing fetch is not retried on every worker wake either", async () => {
|
||||
const counter = { calls: 0 };
|
||||
global.fetch = countingFetch(counter, () => ({
|
||||
ok: false,
|
||||
status: 503,
|
||||
}));
|
||||
|
||||
for (let wake = 0; wake < 4; wake++) {
|
||||
const revived = restartWorker();
|
||||
await revived.initPhishingList();
|
||||
now += 30 * 1000;
|
||||
}
|
||||
|
||||
expect(counter.calls).toBe(1);
|
||||
test("a different digest width throws", () => {
|
||||
expect(() => loadWith({ ...GOOD, hashHexChars: 8 })).toThrow(
|
||||
/hex characters per entry/,
|
||||
);
|
||||
});
|
||||
|
||||
test("the retry floor expires, so a failure is not permanent", async () => {
|
||||
const {
|
||||
MIN_FETCH_ATTEMPT_INTERVAL_MS,
|
||||
} = require("../src/shared/phishingDomains");
|
||||
const counter = { calls: 0 };
|
||||
global.fetch = countingFetch(counter, () => ({
|
||||
ok: false,
|
||||
status: 503,
|
||||
}));
|
||||
|
||||
await restartWorker().initPhishingList();
|
||||
expect(counter.calls).toBe(1);
|
||||
|
||||
// Still inside the floor: no retry.
|
||||
now += MIN_FETCH_ATTEMPT_INTERVAL_MS - 1000;
|
||||
await restartWorker().initPhishingList();
|
||||
expect(counter.calls).toBe(1);
|
||||
|
||||
// Past it: the extension goes back to the network.
|
||||
now += 2000;
|
||||
await restartWorker().initPhishingList();
|
||||
expect(counter.calls).toBe(2);
|
||||
test("a count that does not match the string length throws", () => {
|
||||
expect(() => loadWith({ ...GOOD, count: 3 })).toThrow(
|
||||
/which is not the/,
|
||||
);
|
||||
});
|
||||
|
||||
test("the scheduled tick ignores the retry floor", async () => {
|
||||
// The alarm period is far above the floor, but the floor exists to
|
||||
// throttle wakes, not the schedule.
|
||||
storageStore[DELTA_STORAGE_KEY] = { lastAttemptTime: now - 1000 };
|
||||
const mod = require("../src/shared/phishingDomains");
|
||||
global.fetch = okFetch();
|
||||
test("a missing hashes string throws", () => {
|
||||
expect(() => loadWith({ ...GOOD, hashes: undefined })).toThrow(
|
||||
/no hashes string/,
|
||||
);
|
||||
});
|
||||
|
||||
await mod.refreshPhishingListOnSchedule();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
test("an empty artifact throws rather than matching nothing", () => {
|
||||
expect(() => loadWith({ ...GOOD, count: 0, hashes: "" })).toThrow(
|
||||
/entry count/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -384,7 +384,7 @@ describe("the shipped token list", () => {
|
||||
"0xab5eb14c09d416f0ac63661e57edb7aecdb9befa", // Metronome Synth USD
|
||||
],
|
||||
MUSD: [
|
||||
"0xaca92e438df0b2401ff60da7e4337b687a2435da", // MetaMask USD
|
||||
"0xaca92e438df0b2401ff60da7e4337b687a2435da",
|
||||
"0xdd468a1ddc392dcdbef6db6e34e89aa338f9f186", // Mezo USD
|
||||
],
|
||||
JPYC: [
|
||||
|
||||
Reference in New Issue
Block a user