fix: version the stored profile, and give a record that cannot be read a way out (closes #311)
All checks were successful
check / check (push) Successful in 32s
e2e / e2e-chrome (push) Successful in 1m44s
e2e / e2e-firefox (push) Successful in 29s

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 two of those floors were written on truthiness rather than on type, so a truthy value of the wrong type walked straight through and threw on the first dereference — the same blank popup, by a longer route. trackedTokens: "nope" rendered nothing with "Cannot read properties of undefined (reading 'toLowerCase')", and activeAddress: 42 rendered nothing with "address.slice is not a function", for profiles whose wallets were perfectly readable. Both are type checks now, matching what networkEndpoints and viewStack already did in the same file, and an empty list or an empty string still survives.

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 a value JSON cannot represent — a cycle, or a BigInt, which Firefox's storage can hold — fails the export entirely and leaves erase as the only control; that is now stated where the export is written.

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. 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.
This commit is contained in:
2026-08-23 16:23:58 +00:00
parent 28a527295a
commit a10a98438f
25 changed files with 1990 additions and 50 deletions

View File

@@ -16,6 +16,7 @@ const { applyChainSwitchFields } = require("../shared/chainSwitchFields");
// script/lib/forbiddenBundleInputs.js). The ESLint rule of the same name is
// the same prohibition reported early, not the guarantee.
const { getState, updateState } = require("./state");
const { StateUnusableError } = require("../shared/stateSchema");
const { refreshBalances, getProvider } = require("../shared/balances");
const { debugFetch, log } = require("../shared/log");
const {
@@ -179,6 +180,45 @@ const INTERNAL_ERROR_CODE = -32603;
const INTERNAL_ERROR_MESSAGE =
"AutistMask could not complete this request because of an internal error.";
// What the page is told when the wallet's own stored profile cannot be read.
//
// This used to be the generic answer above: getActiveAddress() dereferenced
// the stored wallet list on nearly every method, so a corrupt or
// newer-than-this-build record turned EVERY request from EVERY page into
// "internal error", which is also what a failed signing attempt answers. The
// page cannot tell those apart, and the user is told nothing about the one
// thing that is actually wrong or where to fix it
// (https://git.eeqj.de/sneak/AutistMask/issues/311).
//
// Its own code rather than -32603, because the condition is specific,
// diagnosable and has a user action attached — none of which "internal error"
// conveys.
//
// -32007 specifically: EIP-1474 sets aside -32000..-32099 for
// implementation-defined server errors, but it ASSIGNS meanings to -32000
// through -32006 (Invalid input, Resource not found, Resource unavailable,
// Transaction rejected, Method not supported, Limit exceeded, JSON-RPC version
// not supported). -32007..-32099 are the unassigned ones, and this condition
// is not any of the seven. Nothing above it is free to be overloaded either:
// this wallet already answers EIP-1474's -32002 "Resource unavailable" for a
// pending approval, the conventional way, so a page is entitled to read these
// codes by that table.
const STATE_UNUSABLE_CODE = -32007;
const STATE_UNUSABLE_MESSAGE =
"AutistMask cannot read its saved data, so nothing was signed or sent." +
" Open the AutistMask extension to export or reset it.";
// The EIP-1193 error for a handler that threw, by cause. Everything that
// consults the profile goes through getState(), so this one mapping covers
// every method rather than each one having to know about the condition.
function failureError(err) {
if (err instanceof StateUnusableError) {
log.errorf("state is unusable:", err.problem);
return { code: STATE_UNUSABLE_CODE, message: STATE_UNUSABLE_MESSAGE };
}
return { code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE };
}
// The active address of a profile snapshot. Pure, and taking the snapshot as
// an argument rather than reading storage itself: a handler that has already
// read state must not answer "which account is this" from a SECOND, later read
@@ -883,6 +923,11 @@ async function handleRpc(method, params, origin) {
const result = await proxyRpc(method, params);
return { result };
} catch (e) {
// A node that answered with an error is reported as itself. The
// wallet being unable to read its own profile is not that, and it
// must not be flattened into a message with no code: it goes back
// to the dispatcher, which has the one answer for it.
if (e instanceof StateUnusableError) throw e;
return { error: { message: e.message } };
}
}
@@ -1142,7 +1187,14 @@ async function backgroundRefresh() {
// module-level state does not outlive it. Alarms are held by the browser and
// wake the worker to deliver them.
registerAlarmHandlers({
[BALANCE_REFRESH_ALARM]: backgroundRefresh,
// Caught here rather than left to the alarm dispatcher, which does not
// await what it calls: a profile this build cannot read makes every
// refresh throw, and an unhandled rejection per alarm tick says less than
// one logged line per tick does.
[BALANCE_REFRESH_ALARM]: () =>
backgroundRefresh().catch((e) => {
log.errorf("background balance refresh failed:", e);
}),
});
// Everything the background context needs re-established on start. This runs
@@ -1241,12 +1293,7 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
// "it does not throw today" is not a property anyone is
// maintaining.
log.errorf("RPC request failed:", msg.method, err);
sendResponse({
error: {
code: INTERNAL_ERROR_CODE,
message: INTERNAL_ERROR_MESSAGE,
},
});
sendResponse({ error: failureError(err) });
});
return true;
}
@@ -1481,18 +1528,10 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
// the popup nor the page is ever answered. Settle both, through
// the same chokepoint as every other retirement.
log.errorf("transaction approval response failed:", e);
settleApproval(
msg.id,
{
error: {
code: INTERNAL_ERROR_CODE,
message: INTERNAL_ERROR_MESSAGE,
},
},
{ holdsClaim: true },
);
const failure = failureError(e);
settleApproval(msg.id, { error: failure }, { holdsClaim: true });
sendResponse({
error: INTERNAL_ERROR_MESSAGE,
error: failure.message,
retryable: false,
stage: lastResortStage,
});
@@ -1584,18 +1623,10 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
// Same shape as the transaction path: a throw out of the catch
// block above would leave the popup and the page both waiting.
log.errorf("sign approval response failed:", e);
settleApproval(
msg.id,
{
error: {
code: INTERNAL_ERROR_CODE,
message: INTERNAL_ERROR_MESSAGE,
},
},
{ holdsClaim: true },
);
const failure = failureError(e);
settleApproval(msg.id, { error: failure }, { holdsClaim: true });
sendResponse({
error: INTERNAL_ERROR_MESSAGE,
error: failure.message,
retryable: false,
});
});