Five defects traced to one fact: src/background/index.js read and wrote the
module-level `state` singleton in src/shared/state.js, which the MV3 service
worker never populates and which answered an unpopulated read out of
DEFAULT_STATE in silence. Every previous fix added a loadState() before the
access, and that is what produced the fifth: a load detaches the objects an
in-flight handler is holding.
So the reachability goes rather than a sixth call site.
The background now has its own storage layer, src/background/state.js:
getState() is a detached, normalized per-call read, and updateState() is a
queued read-modify-write whose read is one storage round trip ahead of its
write. Nothing in the background holds an in-memory copy of the profile.
- Every handler takes one snapshot and answers from it, including the address
it names: activeAddressOf(s) replaced a second, later storage read that
could disagree with the first.
- wallet_switchEthereumChain applies applyChainSwitchFields() (split out of
chainSwitch.js, which keeps the singleton path for the popup) inside
updateState() instead of calling onChainSwitch() on the singleton.
- The remembered site decision is a read-modify-write, not a load-mutate-save
around a prompt the user takes seconds to answer.
- backgroundRefresh() refreshes a private copy of the wallets and applies the
balances that came back by address, so it never publishes an object other
in-flight work holds, and a wallet added or deleted during the round trip
survives its write.
- The transaction attempt takes its chain id and its endpoint from the same
snapshot. They used to come from different moments, so a chain switch
committed in between moved the endpoint under an artifact already verified
against the old chain.
getProvider(rpcUrl, networkId) now REQUIRES the network id and validates it
against networks.js. That closes the cold-worker wrong-chain send at its shape
rather than at one call site: the hint used to default to currentNetwork() off
the unpopulated singleton, so the endpoint was the user's chain and ethers
fixed chainId at 0x1, and the wallet's own verifySignedTx then refused every
non-mainnet dApp send. refreshBalances(), lookupTokenInfo(), scanForAddresses()
and resolveEnsName() carry the id through; balances.js no longer requires
state.js at all.
The prohibition is enforced mechanically, not by review: a custom ESLint rule
walks the CommonJS require graph from every src/background/ file and fails the
lint when src/shared/state.js is reachable, naming the chain. A re-export from
any shared module cannot put the singleton back in the bundle unnoticed.
The rule's matcher covers every specifier syntax esbuild resolves statically —
quoted require, backtick require, dynamic import(), and a static import/export
`from` clause — because a narrower match is not a matter of tidiness but a sixth
site the build cannot see: each of those shapes was measured to put state.js in
dist/chrome/src/background/index.js while the lint stayed clean.
tests/backgroundStateLintRule.test.js pins all of them, plus the two-hop
re-export, against a real fixture tree. A computed specifier
(require("../shared/" + "state")) is deliberately not matched: esbuild cannot
resolve it either, so it never reaches the bundle.
Reading a persisted field of the singleton before any load now throws
StateNotLoadedError instead of serving DEFAULT_STATE.
Test stubs: chrome.storage.local is a serialization boundary, and eight files
stubbed it with an aliasing get, so the object a module held and the object
"storage" held were one object — an assertion could pass on a build that never
wrote anything. Every test that drives real persistence now goes through
tests/support/storageStub.js, which structured-clones in both directions.
closes #320
210 lines
7.3 KiB
JavaScript
210 lines
7.3 KiB
JavaScript
// What a chain switch does to a worker that has not loaded state yet.
|
|
//
|
|
// The MV3 service worker is terminated when idle and revived by the next
|
|
// message, and nothing loads state at module scope. The chain-switch handler
|
|
// reaches onChainSwitch(), which mutates the module-level `state` singleton
|
|
// and then persists EVERY field of it, so a handler that runs before a load
|
|
// writes DEFAULT_STATE over the user's stored profile — every wallet, every
|
|
// site approval, every tracked token and the custom endpoint
|
|
// (https://git.eeqj.de/sneak/AutistMask/issues/316). The same singleton is
|
|
// what currentNetwork() answers from, so the same-chain early return also
|
|
// compares against the wrong network.
|
|
//
|
|
// This file therefore uses the REAL state module and never calls loadState()
|
|
// itself: the handler has to do it. tests/chainSwitchGate.test.js mocks the
|
|
// state module wholesale and tests/networkEndpoints.test.js always loads
|
|
// first, so neither can see this.
|
|
|
|
const { networkById } = require("../src/shared/networks");
|
|
const { makeStorageStub } = require("./support/storageStub");
|
|
|
|
const ADDRESS = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
|
|
|
|
const CONNECTED_ORIGIN = "https://dapp.example";
|
|
const CONNECTED_HOSTNAME = "dapp.example";
|
|
|
|
const MAINNET = networkById("mainnet");
|
|
const SEPOLIA = networkById("sepolia");
|
|
|
|
// The user's own node, and a wallet whose loss is the whole point.
|
|
const CUSTOM_RPC = "http://127.0.0.1:8545";
|
|
const CUSTOM_BLOCKSCOUT = "http://127.0.0.1:4000/api/v2";
|
|
const TOKEN = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
|
|
|
|
function walletFixture() {
|
|
return [
|
|
{
|
|
name: "Wallet 1",
|
|
type: "hd",
|
|
addresses: [{ address: ADDRESS, balance: "0", tokenBalances: [] }],
|
|
},
|
|
];
|
|
}
|
|
|
|
// A profile as an installed extension holds it, on `networkId`.
|
|
function storedProfile(networkId) {
|
|
return {
|
|
hasWallet: true,
|
|
wallets: walletFixture(),
|
|
activeAddress: ADDRESS,
|
|
networkId,
|
|
rpcUrl: CUSTOM_RPC,
|
|
blockscoutUrl: CUSTOM_BLOCKSCOUT,
|
|
allowedSites: { [ADDRESS]: [CONNECTED_HOSTNAME] },
|
|
deniedSites: {},
|
|
trackedTokens: [{ address: TOKEN, symbol: "DAI", decimals: 18 }],
|
|
theme: "dark",
|
|
};
|
|
}
|
|
|
|
async function settle() {
|
|
for (let i = 0; i < 50; i++) await Promise.resolve();
|
|
}
|
|
|
|
afterEach(() => {
|
|
delete global.chrome;
|
|
});
|
|
|
|
// Load the background worker with the real chain-switch and persistence
|
|
// modules behind it, over a storage stub that actually keeps what is written —
|
|
// a wipe is only observable against storage that remembers — and that clones
|
|
// in both directions, as the real API does. It used to alias, so the record
|
|
// the worker held and the "stored" one were a single object; see
|
|
// tests/support/storageStub.js.
|
|
function loadColdWorker(networkId) {
|
|
jest.resetModules();
|
|
|
|
jest.doMock("../src/shared/balances", () => ({
|
|
getProvider: () => ({}),
|
|
refreshBalances: jest.fn(async () => {}),
|
|
}));
|
|
jest.doMock("../src/shared/phishingDomains", () => ({
|
|
isPhishingDomain: () => false,
|
|
}));
|
|
jest.doMock("../src/shared/alarms", () => ({
|
|
BALANCE_REFRESH_ALARM: "balance",
|
|
BALANCE_REFRESH_PERIOD_MINUTES: 1,
|
|
ensureRecurringAlarms: jest.fn(async () => {}),
|
|
registerAlarmHandlers: jest.fn(),
|
|
}));
|
|
|
|
const storage = makeStorageStub({ autistmask: storedProfile(networkId) });
|
|
|
|
let messageListener = null;
|
|
const toTabs = [];
|
|
|
|
global.chrome = {
|
|
storage,
|
|
runtime: {
|
|
getURL: (path) => "chrome-extension://autistmask/" + path,
|
|
onMessage: {
|
|
addListener: (fn) => {
|
|
messageListener = fn;
|
|
},
|
|
},
|
|
onConnect: { addListener: () => {} },
|
|
lastError: null,
|
|
},
|
|
windows: {
|
|
getLastFocused: (cb) => cb(null),
|
|
create: (options, cb) => cb({ id: 1 }),
|
|
remove: (id, cb) => {
|
|
if (cb) cb();
|
|
},
|
|
onRemoved: { addListener: () => {} },
|
|
},
|
|
tabs: {
|
|
query: (queryInfo, cb) => cb([{ id: 1 }]),
|
|
sendMessage: (tabId, message, cb) => {
|
|
toTabs.push(message);
|
|
if (cb) cb();
|
|
},
|
|
},
|
|
action: { setPopup: () => {} },
|
|
};
|
|
|
|
require("../src/background/index");
|
|
|
|
async function switchChain(chainId) {
|
|
let result = null;
|
|
messageListener(
|
|
{
|
|
type: "AUTISTMASK_RPC",
|
|
method: "wallet_switchEthereumChain",
|
|
params: [{ chainId }],
|
|
},
|
|
{ origin: CONNECTED_ORIGIN },
|
|
(r) => {
|
|
result = r;
|
|
},
|
|
);
|
|
await settle();
|
|
return result;
|
|
}
|
|
|
|
return {
|
|
switchChain,
|
|
persisted: () => storage.read("autistmask"),
|
|
chainChangedEvents: () =>
|
|
toTabs.filter((m) => m.eventName === "chainChanged"),
|
|
};
|
|
}
|
|
|
|
describe("a chain switch on a worker that never loaded state", () => {
|
|
test("keeps the wallets, approvals, tokens and custom endpoint", async () => {
|
|
const bg = loadColdWorker("mainnet");
|
|
|
|
const result = await bg.switchChain(SEPOLIA.chainId);
|
|
expect(result).toEqual({ result: null });
|
|
|
|
const after = bg.persisted();
|
|
// The switch itself happened.
|
|
expect(after.networkId).toBe("sepolia");
|
|
expect(after.rpcUrl).toBe(SEPOLIA.defaultRpcUrl);
|
|
|
|
// And it took nothing else with it. Without the load these come back
|
|
// as [], {}, [] and "system" from DEFAULT_STATE — every wallet in the
|
|
// extension gone, encrypted secrets included.
|
|
expect(after.wallets).toEqual(walletFixture());
|
|
expect(after.hasWallet).toBe(true);
|
|
expect(after.activeAddress).toBe(ADDRESS);
|
|
expect(after.allowedSites).toEqual({ [ADDRESS]: [CONNECTED_HOSTNAME] });
|
|
expect(after.trackedTokens).toEqual([
|
|
{ address: TOKEN, symbol: "DAI", decimals: 18 },
|
|
]);
|
|
expect(after.theme).toBe("dark");
|
|
|
|
// The user's mainnet endpoint is remembered rather than replaced by
|
|
// the public default, so switching back returns it.
|
|
expect(after.networkEndpoints.mainnet).toEqual({
|
|
rpcUrl: CUSTOM_RPC,
|
|
blockscoutUrl: CUSTOM_BLOCKSCOUT,
|
|
});
|
|
|
|
await bg.switchChain(MAINNET.chainId);
|
|
expect(bg.persisted().rpcUrl).toBe(CUSTOM_RPC);
|
|
expect(bg.persisted().blockscoutUrl).toBe(CUSTOM_BLOCKSCOUT);
|
|
expect(bg.persisted().wallets).toEqual(walletFixture());
|
|
});
|
|
|
|
test("compares the requested chain against the stored one, not the default", async () => {
|
|
// Stored on Sepolia, asked for mainnet. Reading the unloaded
|
|
// singleton makes this look like the chain already active, so the
|
|
// page is told the switch succeeded while the wallet stays on the
|
|
// testnet it was on.
|
|
const bg = loadColdWorker("sepolia");
|
|
|
|
const result = await bg.switchChain(MAINNET.chainId);
|
|
expect(result).toEqual({ result: null });
|
|
|
|
expect(bg.persisted().networkId).toBe("mainnet");
|
|
expect(bg.chainChangedEvents()).toEqual([
|
|
{
|
|
type: "AUTISTMASK_EVENT",
|
|
eventName: "chainChanged",
|
|
data: MAINNET.chainId,
|
|
},
|
|
]);
|
|
});
|
|
});
|