The stored profile carried no version, so nothing could tell a record this build wrote from one a later build did, and loadState() coerced scalars while trusting the structure. A wallets that was a string, an array of nulls, or a later schema's wallet records reached the popup and threw on the first dereference: no view, no message, no control, and every dApp call answering a generic -32603 because getActiveAddress() dereferenced the same record. There was no reset or wipe control anywhere in the product, so the only escape was clearing extension storage through browser internals.
saveState() and updateState() now both stamp STATE_SCHEMA_VERSION, and every read goes through assertStateUsable() on the raw bytes before normalization can paper over them. Version 1 is the shape that shipped unversioned, so the profile every existing install holds loads normally and is migrated in place by being stamped on the first write; an upgrade shows nobody a wipe prompt for a wallet that is fine. A record this build cannot vouch for is refused instead, and refused all the way: not normalized, not written back, not half-loaded, and not overwritten by a save either.
The gate covers what nothing downstream can floor. Everything else is normalizePersisted()'s job, and three separate gaps there let a gate-accepted record reach a dereference and blank the popup anyway. trackedTokens and activeAddress were floored on truthiness rather than on type: trackedTokens: "nope" rendered nothing with "Cannot read properties of undefined (reading 'toLowerCase')", activeAddress: 42 rendered nothing with "address.slice is not a function". A container check is not enough either, because [1, 2] IS a list and the dereference is t.address.toLowerCase() one level below the Array.isArray(): [1,2], [null], [{}], [{address:42}] and ["0xAA..."] each still rendered nothing. And each address's tokenBalances had no floor at all — which matters most, since refreshBalances() writes that field wholesale and the partial write the issue names as the live cause of a corrupt record lands exactly there — so "x", 42, [null] and [42] rendered nothing too. All of them are type-checked now, container AND entries: an entry that is not a record with a text address is dropped, the well-formed entries beside it survive, and an empty list is still a legitimate value. activeAddress's empty string now floors to null rather than surviving, because init() auto-selects the first address only on a strict null, so a kept "" would leave the popup with no address ever selected; that restores what the || null this check replaced already did.
The header of stateSchema.js claimed every non-gated field's floor was a type check. It is not, and now it says so field by field: rpcUrl, blockscoutUrl, lastBalanceRefresh, fraudContracts, tokenHolderCache, theme, currentView, selectedToken and viewData are saved.x || default; every boolean flag, dustThresholdGwei, selectedWallet and selectedAddress are taken verbatim when present; allowedSites and deniedSites are checked as containers only, never per entry. The header and the README now list which field is in which category rather than asserting a rule the module does not follow.
The popup shows a new StateRecovery screen. It names the problem in a sentence, exports the stored record into a text box on the page with no normalization or repair on it (and downloads it where the browser allows), and offers an erase behind a typed ERASE MY WALLET. Both controls are required: an export with no reset leaves the user stuck, and a reset with no export destroys the only copy of possibly recoverable key material. The Settings gear is hidden while it is up, and showView() is not used to raise it, because both read the state singleton that by then refuses to be read. The export is JSON.stringify of the deserialized record, so what JSON cannot carry is stated where the export is written: a cycle or a BigInt throws and fails the export entirely, and a Date, a Map, a Set, an undefined property or a NaN is mangled silently instead, which is the worse residual because the box then looks complete.
The background refuses the same record and answers dApps -32007 with a message saying the saved data cannot be read and that nothing was signed or sent, rather than the -32603 it also answers when a signing attempt breaks. EIP-1474 sets aside -32000..-32099 for implementation-defined server errors but assigns meanings to -32000 through -32006, including -32001 "Resource not found" and the -32002 "Resource unavailable" this wallet already uses for a pending approval; -32007..-32099 are the unassigned ones, and a test pins the code against that table.
networkById() now throws on an id it does not know instead of quietly answering mainnet, which also stops NETWORKS["constructor"] resolving off the prototype chain. Every key test in the gate is an own-property test, because networkId is an object key into networkEndpoints and an unvalidated "__proto__" set that map's prototype instead of an own key, dropping the user's endpoint silently; normalizePersisted() copies endpoint entries with defineProperty for the same reason. That own-property discipline is the gate's alone — normalizePersisted() reads the same fields plainly, and the two agree only because a record from storage has been through structuredClone and carries Object.prototype.
The three corrupt blobs from the issue drive the real popup entry point and the real worker in tests; each rendered nothing at all and answered -32603 before this, and the unversioned-but-valid case is tested too. Every corrupt-field shape that has ever been observed to blank the popup is a row in tests/stateRecovery.test.js, measured through the same entry point; none has been removed. Three test files used fixture wallets the product cannot produce (a bare address string where an address record belongs, a wallet with no address list) and now use whole records. src/popup/restorableViews.js moved to src/shared/restorableViews.js, since persistedState.js requires it and that module is in the background bundle.
95 lines
3.7 KiB
JavaScript
95 lines
3.7 KiB
JavaScript
// Tests for the recovery phrase display (issue #161).
|
|
//
|
|
// These cover the parts that do not need a DOM: which wallet types may be
|
|
// offered the action at all, the exclusion of the screen from the set of
|
|
// views the popup may reopen onto, and the absence of any path from this
|
|
// module to the logger. The DOM behaviour it guards — nothing rendered
|
|
// before the password is accepted, a wrong password revealing nothing, and
|
|
// the wipe on leaving — is driven against the real popup in a real browser
|
|
// by tests/e2e/run.js, which is where every other view behaviour is tested.
|
|
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const { walletHasRecoveryPhrase } = require("../src/shared/wallet");
|
|
const { RESTORABLE_VIEWS } = require("../src/shared/restorableViews");
|
|
|
|
const SHOW_PHRASE_VIEW = "show-phrase";
|
|
|
|
// helpers.js pulls in state.js, which reads chrome.storage.local at load.
|
|
function loadHelpers() {
|
|
globalThis.chrome = {
|
|
storage: { local: { get: async () => ({}), set: async () => {} } },
|
|
};
|
|
return require("../src/popup/views/helpers");
|
|
}
|
|
|
|
describe("which wallets have a recovery phrase", () => {
|
|
test("an HD wallet does", () => {
|
|
expect(walletHasRecoveryPhrase({ type: "hd" })).toBe(true);
|
|
});
|
|
|
|
// A key wallet holds a bare private key and an xprv wallet an extended
|
|
// private key. Neither can be turned back into words, so neither may be
|
|
// offered the action.
|
|
test("a key wallet does not", () => {
|
|
expect(walletHasRecoveryPhrase({ type: "key" })).toBe(false);
|
|
});
|
|
|
|
test("an xprv wallet does not", () => {
|
|
expect(walletHasRecoveryPhrase({ type: "xprv" })).toBe(false);
|
|
});
|
|
|
|
test("an unknown or missing wallet type does not", () => {
|
|
expect(walletHasRecoveryPhrase({ type: "something-new" })).toBe(false);
|
|
expect(walletHasRecoveryPhrase({})).toBe(false);
|
|
expect(walletHasRecoveryPhrase(undefined)).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("views the popup may reopen onto", () => {
|
|
// Restoring onto a secret screen would put the phrase on screen with no
|
|
// password prompt in front of it, on a popup the user may have reopened
|
|
// by accident.
|
|
test("the recovery phrase screen is not restorable", () => {
|
|
expect(RESTORABLE_VIEWS.has(SHOW_PHRASE_VIEW)).toBe(false);
|
|
});
|
|
|
|
test("the private key export screen is not restorable either", () => {
|
|
expect(RESTORABLE_VIEWS.has("export-privkey")).toBe(false);
|
|
});
|
|
|
|
test("the recovery phrase screen is still a registered view", () => {
|
|
const { VIEWS } = loadHelpers();
|
|
expect(VIEWS).toContain(SHOW_PHRASE_VIEW);
|
|
});
|
|
|
|
// Guards the other direction: a restorable name that is not a real view
|
|
// would leave restoreView() showing nothing at all.
|
|
test("every restorable view is a registered view", () => {
|
|
const { VIEWS } = loadHelpers();
|
|
for (const view of RESTORABLE_VIEWS) {
|
|
expect(VIEWS).toContain(view);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("the phrase cannot reach the logger", () => {
|
|
const source = fs.readFileSync(
|
|
path.join(__dirname, "..", "src", "popup", "views", "showPhrase.js"),
|
|
"utf8",
|
|
);
|
|
|
|
// The decrypted phrase only ever lives in a local and in the DOM node
|
|
// that displays it. The module has no logger to hand it to, and this
|
|
// pins that: src/shared/log.js writes to the console, and a console
|
|
// record of a recovery phrase outlives the popup.
|
|
test("the view does not import src/shared/log.js", () => {
|
|
expect(source).not.toMatch(/require\(["'][^"']*shared\/log["']\)/);
|
|
});
|
|
|
|
test("the view calls no logger method", () => {
|
|
expect(source).not.toMatch(/\blog\.(debugf|infof|warnf|errorf)\b/);
|
|
});
|
|
});
|