harden: make the background physically unable to read the shared state singleton (closes #324)
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
This commit is contained in:
@@ -13,13 +13,15 @@
|
||||
// never persisting it looks identical from `state`, and a build that never
|
||||
// wrote at all would pass a check that only reads `state` back.
|
||||
//
|
||||
// That makes the storage stub load-bearing, so it is a real store that
|
||||
// structured-clones on both `set` and `get`. A stub whose `get` hands back
|
||||
// the same object its `set` was given aliases the caller's own array: the
|
||||
// test then reads its own in-memory mutation and calls it persistence, and
|
||||
// passes against a build that persists nothing (see issue #324). The
|
||||
// aliasing is closed off explicitly by the first test below rather than
|
||||
// left as an assumption about `structuredClone`.
|
||||
// That makes the storage stub load-bearing, so it is the shared one from
|
||||
// tests/support/storageStub.js, a real store that structured-clones on both
|
||||
// `set` and `get`. A stub whose `get` hands back the same object its `set`
|
||||
// was given aliases the caller's own array: the test then reads its own
|
||||
// in-memory mutation and calls it persistence, and passes against a build
|
||||
// that persists nothing
|
||||
// (https://git.eeqj.de/sneak/AutistMask/issues/324). The aliasing is closed
|
||||
// off explicitly by the first test below rather than left as an assumption
|
||||
// about `structuredClone`.
|
||||
//
|
||||
// The view is driven against a minimal DOM stub, in the same shape as
|
||||
// tests/exportPrivkey.test.js: the module reads and writes named nodes and
|
||||
@@ -34,6 +36,7 @@ jest.mock("../src/shared/vault", () => ({
|
||||
}));
|
||||
|
||||
const { RESTORABLE_VIEWS } = require("../src/popup/restorableViews");
|
||||
const { makeStorageStub } = require("./support/storageStub");
|
||||
|
||||
const VIEW = "delete-wallet-lost-password";
|
||||
|
||||
@@ -94,35 +97,6 @@ function makeDocument() {
|
||||
};
|
||||
}
|
||||
|
||||
// --------------------------------------------------------- storage stub
|
||||
|
||||
// A store that behaves the way `chrome.storage.local` does: what goes in is
|
||||
// serialized, so the caller keeps no handle on what came to rest there, and
|
||||
// what comes out is a fresh object the caller may mutate freely.
|
||||
function makeStorage() {
|
||||
let store = {};
|
||||
return {
|
||||
get: async (keys) => {
|
||||
const wanted =
|
||||
keys === undefined || keys === null
|
||||
? Object.keys(store)
|
||||
: [].concat(keys);
|
||||
const out = {};
|
||||
for (const key of wanted) {
|
||||
if (key in store) out[key] = structuredClone(store[key]);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
set: async (items) => {
|
||||
for (const [key, value] of Object.entries(items)) {
|
||||
store[key] = structuredClone(value);
|
||||
}
|
||||
},
|
||||
// Test-only: what the extension would find on a cold start.
|
||||
_raw: () => structuredClone(store),
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ harness
|
||||
|
||||
function wallet(name, secret, addresses) {
|
||||
@@ -144,10 +118,10 @@ function load() {
|
||||
jest.resetModules();
|
||||
mockSettingsShow.mockClear();
|
||||
|
||||
const storage = makeStorage();
|
||||
const storage = makeStorageStub();
|
||||
const sent = [];
|
||||
globalThis.chrome = {
|
||||
storage: { local: storage },
|
||||
storage: { local: storage.local },
|
||||
runtime: { sendMessage: (msg) => sent.push(msg) },
|
||||
};
|
||||
globalThis.document = makeDocument();
|
||||
@@ -205,7 +179,7 @@ async function openLostPassword(deleteWallet, walletIdx) {
|
||||
// every other test in this file against a build that never writes.
|
||||
describe("the storage stub", () => {
|
||||
test("does not hand back the object it was given", async () => {
|
||||
const storage = makeStorage();
|
||||
const storage = makeStorageStub();
|
||||
const written = { wallets: [{ name: "Wallet 1" }] };
|
||||
|
||||
await storage.set({ autistmask: written });
|
||||
@@ -393,8 +367,8 @@ describe("deleting without the password", () => {
|
||||
|
||||
// The deleted wallet's secret is gone from storage entirely, not
|
||||
// merely unreferenced by the wallet list.
|
||||
expect(JSON.stringify(storage._raw())).not.toContain("secret-two");
|
||||
expect(JSON.stringify(storage._raw())).not.toContain("xpub-Wallet 2");
|
||||
expect(JSON.stringify(storage.read())).not.toContain("secret-two");
|
||||
expect(JSON.stringify(storage.read())).not.toContain("xpub-Wallet 2");
|
||||
});
|
||||
|
||||
test("only the deleted wallet's site permissions are dropped", async () => {
|
||||
@@ -462,7 +436,7 @@ describe("deleting without the password", () => {
|
||||
expect(saved.activeAddress).toBeNull();
|
||||
expect(saved.allowedSites).toEqual({});
|
||||
expect(state.currentView).toBe("welcome");
|
||||
expect(JSON.stringify(storage._raw())).not.toContain("secret-one");
|
||||
expect(JSON.stringify(storage.read())).not.toContain("secret-one");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user