Compare commits
11 Commits
a94110ed6c
...
48f1edae57
| Author | SHA1 | Date | |
|---|---|---|---|
| 48f1edae57 | |||
| ba35282092 | |||
| 158278d251 | |||
| 6f6bc2e7b5 | |||
| 74c137dadf | |||
| edea22f7ed | |||
| b155c0fcd6 | |||
| fb9e8f5542 | |||
| 3e5d6323ce | |||
| 12acf4dc8c | |||
| f455b0ae7f |
240
README.md
240
README.md
@@ -123,8 +123,12 @@ unavailable). The suite lives in `tests/e2e/` and is driven by
|
|||||||
`playwright-core`, whose version must stay matched to the container's Playwright
|
`playwright-core`, whose version must stay matched to the container's Playwright
|
||||||
version — the browsers ship inside the image.
|
version — the browsers ship inside the image.
|
||||||
|
|
||||||
It covers popup load, wallet creation through the UI, the Add Token screen and
|
It covers popup load, wallet creation through the UI, the Add Token screen, the
|
||||||
the transaction detail screen for an ERC-20 transfer. All outbound network is
|
transaction detail screen for an ERC-20 transfer, and the recovery phrase screen
|
||||||
|
— which wallet types are offered it, that it holds nothing before the password
|
||||||
|
is accepted, that a wrong password reveals nothing, that leaving it by either
|
||||||
|
route wipes it — including a leave taken while the decrypt is still running —
|
||||||
|
and that reopening the popup does not land on it. All outbound network is
|
||||||
intercepted at the browser level and served from fixtures in
|
intercepted at the browser level and served from fixtures in
|
||||||
`tests/e2e/network.js`, so the run is deterministic and fully offline;
|
`tests/e2e/network.js`, so the run is deterministic and fully offline;
|
||||||
unrecognised outbound requests are reported as failures rather than silently
|
unrecognised outbound requests are reported as failures rather than silently
|
||||||
@@ -145,10 +149,11 @@ page, which it does not by default — `script/test-e2e` sets
|
|||||||
`PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1` for it. Because that flag is
|
`PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS=1` for it. Because that flag is
|
||||||
experimental, the harness does not take it on trust. At launch it waits for the
|
experimental, the harness does not take it on trust. At launch it waits for the
|
||||||
background worker's **own** startup request — the phishing blocklist fetch that
|
background worker's **own** startup request — the phishing blocklist fetch that
|
||||||
`src/background/index.js` issues unconditionally — to arrive in the route
|
`src/background/index.js` issues on startup, which on the suite's throwaway
|
||||||
handler, and aborts the entire suite if none does within 30 seconds
|
profile always happens because no previous fetch timestamp is persisted — to
|
||||||
(`tests/e2e/harness.js`). The check is passive on purpose: a synthetic probe
|
arrive in the route handler, and aborts the entire suite if none does within 30
|
||||||
fetched from inside the worker via `worker.evaluate()` was tried first and
|
seconds (`tests/e2e/harness.js`). The check is passive on purpose: a synthetic
|
||||||
|
probe fetched from inside the worker via `worker.evaluate()` was tried first and
|
||||||
rejected, because evaluating in an extension service worker that early kills the
|
rejected, because evaluating in an extension service worker that early kills the
|
||||||
worker outright, destroying the thing being measured. Observing traffic the
|
worker outright, destroying the thing being measured. Observing traffic the
|
||||||
extension already generates perturbs nothing. Losing the race fails closed — the
|
extension already generates perturbs nothing. Losing the race fails closed — the
|
||||||
@@ -208,9 +213,10 @@ src/
|
|||||||
styles/main.css — Tailwind source
|
styles/main.css — Tailwind source
|
||||||
views/ — one JS module per screen (home, send, approval, etc.)
|
views/ — one JS module per screen (home, send, approval, etc.)
|
||||||
shared/ — modules used by both popup and background
|
shared/ — modules used by both popup and background
|
||||||
|
alarms.js — recurring background jobs (extension alarms API)
|
||||||
balances.js — ETH + ERC-20 balance fetching via RPC + Blockscout
|
balances.js — ETH + ERC-20 balance fetching via RPC + Blockscout
|
||||||
constants.js — chain IDs, default RPC endpoint, ERC-20 ABI
|
constants.js — chain IDs, default RPC endpoint, ERC-20 ABI
|
||||||
ens.js — ENS forward/reverse resolution
|
ens.js — ENS forward/reverse resolution (popup only)
|
||||||
prices.js — ETH/USD and token/USD via CoinDesk API
|
prices.js — ETH/USD and token/USD via CoinDesk API
|
||||||
scamlist.js — known fraud contract addresses
|
scamlist.js — known fraud contract addresses
|
||||||
state.js — persisted state (extension storage)
|
state.js — persisted state (extension storage)
|
||||||
@@ -224,6 +230,74 @@ manifest/
|
|||||||
firefox.json — Manifest V2 for Firefox
|
firefox.json — Manifest V2 for Firefox
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Background scheduling
|
||||||
|
|
||||||
|
Chrome runs `src/background/index.js` as a Manifest V3 service worker, which the
|
||||||
|
browser terminates after roughly 30 seconds idle and re-evaluates from scratch
|
||||||
|
on the next event. Two consequences shape every recurring job in the background:
|
||||||
|
|
||||||
|
- `setInterval` and `setTimeout` are useless. They are destroyed with the
|
||||||
|
worker, so a job scheduled that way runs until the first idle period and never
|
||||||
|
again. Both recurring jobs — the 60-second balance refresh and the 24-hour
|
||||||
|
phishing blocklist refresh — are scheduled through the extension alarms API
|
||||||
|
(`src/shared/alarms.js`) instead. The browser holds the schedule and wakes the
|
||||||
|
worker to deliver it. Alarm periods are clamped to a one-minute minimum, so
|
||||||
|
the balance refresh is expressed as exactly one minute and nothing is silently
|
||||||
|
slowed down.
|
||||||
|
- Module-level variables do not survive either. Anything that must be remembered
|
||||||
|
across a restart goes in extension storage, including the timestamp of the
|
||||||
|
last phishing list fetch: without it a revived worker would either re-fetch on
|
||||||
|
every wake or, with a naive in-memory guard, never notice that an update is
|
||||||
|
due. `localStorage` does not exist in a service worker at all — the one
|
||||||
|
remaining user of it, `src/shared/ens.js`, runs only in the popup and is
|
||||||
|
marked as such.
|
||||||
|
|
||||||
|
Both jobs also carry a freshness guard, and a guard must never be timed to the
|
||||||
|
alarm period it gates. Each guard is measured from the moment the last run
|
||||||
|
finished, which is one run-duration after the alarm that started it, so a guard
|
||||||
|
of exactly one period vetoes the very next tick and the real cadence becomes two
|
||||||
|
periods. The two jobs solve this differently, because their guards exist for
|
||||||
|
different reasons:
|
||||||
|
|
||||||
|
- The phishing refresh has a 24-hour cache TTL whose job is to keep the worker
|
||||||
|
off the network on the wakes between scheduled refreshes — Chrome revives the
|
||||||
|
worker every ~30 seconds while the browser is busy, and every revival runs the
|
||||||
|
startup path. The scheduled alarm tick is not one of those wakes, so it
|
||||||
|
bypasses the TTL and fetches unconditionally. Shortening the TTL instead would
|
||||||
|
not work: the startup path re-checks it on every wake, so a shorter TTL simply
|
||||||
|
becomes the real refresh rate.
|
||||||
|
- The balance refresh guard exists to skip work an open popup has already done —
|
||||||
|
the popup refreshes every 10 seconds and stamps the same field. That has to
|
||||||
|
keep applying on the scheduled tick, so the guard is shortened to half the
|
||||||
|
alarm period instead of bypassed: comfortably above the popup's 10 seconds, so
|
||||||
|
an open popup still suppresses the background job, and comfortably below the
|
||||||
|
60-second period, so the schedule always wins.
|
||||||
|
|
||||||
|
Two timestamps are persisted for the phishing list, not one. `lastFetchTime`
|
||||||
|
records a fetch that produced a usable delta and drives the TTL.
|
||||||
|
`lastAttemptTime` records that the network was contacted at all, and is written
|
||||||
|
even when the result is unusable — a failed request, or a delta over the 256 KiB
|
||||||
|
cap. Without it those cases leave no freshness mark and the worker re-downloads
|
||||||
|
the full blocklist on every wake, indefinitely; with it, unscheduled retries are
|
||||||
|
floored at one hour. Both are discarded on load if they are in the future, since
|
||||||
|
a stamp from a skewed clock or a restored backup would otherwise suppress
|
||||||
|
updates until that time arrives, permanently and with no way out.
|
||||||
|
|
||||||
|
The startup path (`ensureRecurringAlarms()` plus the phishing list init) runs on
|
||||||
|
`onInstalled`, on `onStartup`, and at the top level of the worker, so every way
|
||||||
|
the background context can start re-establishes the schedule. On a fresh install
|
||||||
|
more than one of those fires, so they share a single in-flight run rather than
|
||||||
|
racing. It is idempotent: an alarm that already exists with the period the code
|
||||||
|
asks for is left alone, because re-creating one restarts its schedule and a busy
|
||||||
|
extension would push the next fire out indefinitely. An alarm carrying a
|
||||||
|
different period — one created by an earlier version — is re-created once, or a
|
||||||
|
period changed in a new release would never reach an existing install.
|
||||||
|
|
||||||
|
Firefox uses Manifest V2 with a persistent background page, where timers would
|
||||||
|
survive. Both browsers are built from one bundle and both take the alarm path,
|
||||||
|
so there is a single code path to reason about; `"alarms"` is declared in both
|
||||||
|
`manifest/chrome.json` and `manifest/firefox.json`.
|
||||||
|
|
||||||
### UI Design Philosophy
|
### UI Design Philosophy
|
||||||
|
|
||||||
The UI is inspired by _Universal Paperclips_. It's deliberately minimal,
|
The UI is inspired by _Universal Paperclips_. It's deliberately minimal,
|
||||||
@@ -369,9 +443,9 @@ The core hierarchy is **Wallets → Addresses**:
|
|||||||
Which tokens an address shows is decided by `fetchTokenBalances()` in
|
Which tokens an address shows is decided by `fetchTokenBalances()` in
|
||||||
`src/shared/balances.js`, from the Blockscout `token-balances` response, so
|
`src/shared/balances.js`, from the Blockscout `token-balances` response, so
|
||||||
tokens do appear without the user adding them. An ERC-20 is shown when its
|
tokens do appear without the user adding them. An ERC-20 is shown when its
|
||||||
balance is nonzero and it is in the bundled top-250 token list, is tracked by
|
balance is nonzero and it is in the bundled known-token list, is tracked by the
|
||||||
the user, or has 1,000 or more holders; a token claiming a symbol from the
|
user, or has 1,000 or more holders; a token claiming a symbol from the bundled
|
||||||
bundled list from any other contract address is always dropped. That filter is
|
list from any other contract address is always dropped. That filter is
|
||||||
unconditional — the "Hide tokens with fewer than 1,000 holders" setting governs
|
unconditional — the "Hide tokens with fewer than 1,000 holders" setting governs
|
||||||
the transaction history and the send-screen token selector, not this list.
|
the transaction history and the send-screen token selector, not this list.
|
||||||
Tracked tokens with a zero balance are listed as well while "Show tracked tokens
|
Tracked tokens with a zero balance are listed as well while "Show tracked tokens
|
||||||
@@ -406,8 +480,11 @@ runtime debug mode is on, or when the active network is a testnet. They are not
|
|||||||
repeated in the element lists below.
|
repeated in the element lists below.
|
||||||
|
|
||||||
Closing and reopening the popup returns to the screen the user was last on only
|
Closing and reopening the popup returns to the screen the user was last on only
|
||||||
for the views listed in `RESTORABLE_VIEWS` (`src/popup/index.js`). Every other
|
for the views listed in `RESTORABLE_VIEWS` (`src/popup/restorableViews.js`).
|
||||||
screen, including ExportPrivKey, falls back to Home.
|
Every other screen falls back to Home. The screens that display a secret —
|
||||||
|
ExportPrivKey and ShowRecoveryPhrase — are deliberately absent from that list,
|
||||||
|
so the popup can never reopen onto one of them with no password prompt in front
|
||||||
|
of it.
|
||||||
|
|
||||||
#### Welcome (`welcome`)
|
#### Welcome (`welcome`)
|
||||||
|
|
||||||
@@ -575,16 +652,26 @@ screen, including ExportPrivKey, falls back to Home.
|
|||||||
- To: blockie + color dot + full address + etherscan link + ENS name
|
- To: blockie + color dot + full address + etherscan link + ENS name
|
||||||
- Amount: value + symbol (USD in parentheses)
|
- Amount: value + symbol (USD in parentheses)
|
||||||
- Your balance: value + symbol (USD in parentheses)
|
- Your balance: value + symbol (USD in parentheses)
|
||||||
- Estimated network fee: "Estimating..." then the ETH amount (USD in
|
- Network fee: "Estimating..." then two lines, or "Unable to estimate",
|
||||||
parentheses) or "Unable to estimate", fetched async
|
fetched async. The first line is what the transfer is expected to cost,
|
||||||
|
`gasLimit * gasPrice` (USD in parentheses); the second is the
|
||||||
|
`gasLimit * maxFeePerGas` reserve the node requires, which is what the
|
||||||
|
balance check gates on. The second line is omitted on a network with no
|
||||||
|
type-2 pricing, where the two are the same number, but its space is
|
||||||
|
reserved either way
|
||||||
- Warnings: inline warnings from the local checks (scam address, self-send)
|
- Warnings: inline warnings from the local checks (scam address, self-send)
|
||||||
plus four reserved warning boxes made visible by the async checks —
|
plus four reserved warning boxes made visible by the async checks —
|
||||||
recipient with no transaction history, recipient is a contract, burn
|
recipient with no transaction history, recipient is a contract, burn
|
||||||
address, and an Etherscan phishing/scam label
|
address, and an Etherscan phishing/scam label
|
||||||
- Errors (insufficient balance)
|
- Errors (insufficient balance), plus three reserved error boxes — the
|
||||||
|
amount plus the fee exceeds the balance (ETH transfers), not enough ETH to
|
||||||
|
pay the fee for the transfer (ERC-20 transfers), and the fee could not be
|
||||||
|
estimated. The first two are mutually exclusive per transfer type, so only
|
||||||
|
the applicable one holds space
|
||||||
- Password: an inline field on this screen, not a modal, with its own error
|
- Password: an inline field on this screen, not a modal, with its own error
|
||||||
line
|
line
|
||||||
- "Sign & Send" button (disabled if errors)
|
- "Sign & Send" button (disabled if errors, and while the network fee
|
||||||
|
estimate is pending or unavailable)
|
||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
- "Sign & Send" (correct password) → broadcast tx → **WaitTx**
|
||||||
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
- "Sign & Send" (correct password) → broadcast fails → **ErrorTx**
|
||||||
@@ -707,12 +794,13 @@ screen, including ExportPrivKey, falls back to Home.
|
|||||||
- **When**: User tapped the Settings gear.
|
- **When**: User tapped the Settings gear.
|
||||||
- **Elements**:
|
- **Elements**:
|
||||||
- "Back" button, "Settings" heading
|
- "Back" button, "Settings" heading
|
||||||
- Wallets: one row per wallet with its name (tap to rename inline) and an
|
- Wallets: one row per wallet with its name (tap to rename inline), a
|
||||||
`[x]` delete button, plus a "+ Add wallet" button
|
`[recovery phrase]` button on HD wallets only, and an `[x]` delete button,
|
||||||
|
plus a "+ Add wallet" button
|
||||||
- Tracked Tokens: one row per tracked token with an `[x]` remove button,
|
- Tracked Tokens: one row per tracked token with an `[x]` remove button,
|
||||||
plus a "+ Add token" button
|
plus a "+ Add token" button
|
||||||
- Display: "Show tracked tokens with zero balance" checkbox and a Theme
|
- Display: "Show tracked tokens with zero balance" checkbox, "UTC
|
||||||
selector (System / Light / Dark)
|
Timestamps" checkbox, and a Theme selector (System / Light / Dark)
|
||||||
- Network: network selector (Ethereum Mainnet / Sepolia Testnet); switching
|
- Network: network selector (Ethereum Mainnet / Sepolia Testnet); switching
|
||||||
resets the RPC and Blockscout endpoints to that network's defaults
|
resets the RPC and Blockscout endpoints to that network's defaults
|
||||||
- Ethereum RPC: endpoint URL input + "Save" button (validated against
|
- Ethereum RPC: endpoint URL input + "Save" button (validated against
|
||||||
@@ -720,10 +808,10 @@ screen, including ExportPrivKey, falls back to Home.
|
|||||||
- Blockscout API: endpoint URL input + "Save" button (validated against
|
- Blockscout API: endpoint URL input + "Save" button (validated against
|
||||||
`/stats` before being saved)
|
`/stats` before being saved)
|
||||||
- Token Spam Protection:
|
- Token Spam Protection:
|
||||||
|
- "Hide fake tokens impersonating a known symbol" checkbox
|
||||||
- "Hide tokens with fewer than 1,000 holders" checkbox
|
- "Hide tokens with fewer than 1,000 holders" checkbox
|
||||||
- "Hide transactions from detected fraud contracts" checkbox
|
- "Hide transactions from detected fraud contracts" checkbox
|
||||||
- "Hide dust transactions below N gwei" checkbox + threshold input
|
- "Hide dust transactions below N gwei" checkbox + threshold input
|
||||||
- "UTC Timestamps" checkbox
|
|
||||||
- Allowed Sites: list with remove buttons
|
- Allowed Sites: list with remove buttons
|
||||||
- Denied Sites: list with remove buttons
|
- Denied Sites: list with remove buttons
|
||||||
- About: project link, license, author, version, release date, and the
|
- About: project link, license, author, version, release date, and the
|
||||||
@@ -733,6 +821,7 @@ screen, including ExportPrivKey, falls back to Home.
|
|||||||
- **Transitions**:
|
- **Transitions**:
|
||||||
- "+ Add wallet" → **AddWallet**
|
- "+ Add wallet" → **AddWallet**
|
||||||
- "+ Add token" → **SettingsAddToken**
|
- "+ Add token" → **SettingsAddToken**
|
||||||
|
- `[recovery phrase]` on an HD wallet → **ShowRecoveryPhrase**
|
||||||
- `[x]` on a wallet → **DeleteWallet**
|
- `[x]` on a wallet → **DeleteWallet**
|
||||||
- Tap wallet name → inline rename field (no screen change)
|
- Tap wallet name → inline rename field (no screen change)
|
||||||
- `[x]` on a tracked token or a site → removes it in place (no screen
|
- `[x]` on a tracked token or a site → removes it in place (no screen
|
||||||
@@ -740,6 +829,33 @@ screen, including ExportPrivKey, falls back to Home.
|
|||||||
- Ten clicks on the version → reveals the Debug well (no screen change)
|
- Ten clicks on the version → reveals the Debug well (no screen change)
|
||||||
- "Back" (or Settings gear again) → previous screen (Home)
|
- "Back" (or Settings gear again) → previous screen (Home)
|
||||||
|
|
||||||
|
#### ShowRecoveryPhrase (`show-phrase`)
|
||||||
|
|
||||||
|
- **When**: User tapped `[recovery phrase]` on a wallet row in Settings. HD
|
||||||
|
wallets only: key and xprv wallets have no recovery phrase, so their rows do
|
||||||
|
not offer the action at all.
|
||||||
|
- **Elements**:
|
||||||
|
- "Back" button, "Recovery Phrase" heading
|
||||||
|
- Wallet name
|
||||||
|
- Warning box stating that anyone holding these words can take everything in
|
||||||
|
the wallet, from any device, without the password
|
||||||
|
- Error line
|
||||||
|
- Password input + "Reveal" button, shown until the password is accepted
|
||||||
|
- The recovery phrase itself, in full and click-to-copy, shown only after a
|
||||||
|
correct password and in place of the password prompt
|
||||||
|
- **Transitions**:
|
||||||
|
- "Reveal" (correct password) → the phrase replaces the password prompt (no
|
||||||
|
screen change)
|
||||||
|
- "Reveal" (wrong password) → full-sentence error, nothing revealed (no
|
||||||
|
screen change)
|
||||||
|
- "Back" → previous screen (Settings)
|
||||||
|
- **Secret handling**: nothing is decrypted or written into the page until the
|
||||||
|
password is accepted; the phrase is never stored in state, and it is wiped
|
||||||
|
from the page whenever the screen is left by any route, including the Settings
|
||||||
|
gear. A decrypt still running when the screen is left is discarded rather than
|
||||||
|
written. The screen is not restorable, so reopening the popup lands on Home
|
||||||
|
rather than back on the phrase.
|
||||||
|
|
||||||
#### DeleteWallet (`delete-wallet-confirm`)
|
#### DeleteWallet (`delete-wallet-confirm`)
|
||||||
|
|
||||||
- **When**: User tapped the `[x]` next to a wallet in Settings.
|
- **When**: User tapped the `[x]` next to a wallet in Settings.
|
||||||
@@ -892,7 +1008,7 @@ communicates with three external services to function as a wallet:
|
|||||||
What the extension does NOT do:
|
What the extension does NOT do:
|
||||||
|
|
||||||
- No analytics or telemetry services
|
- No analytics or telemetry services
|
||||||
- No token list APIs (the top-250 token list is bundled at build time)
|
- No token list APIs (the known-token list is bundled at build time)
|
||||||
- No Infura/Alchemy dependency (any JSON-RPC endpoint works)
|
- No Infura/Alchemy dependency (any JSON-RPC endpoint works)
|
||||||
- No backend servers operated by the developer
|
- No backend servers operated by the developer
|
||||||
|
|
||||||
@@ -902,9 +1018,14 @@ CoinDesk price API, and Blockscout API), AutistMask also contacts:
|
|||||||
- **Phishing domain blocklist**: A community-maintained phishing domain
|
- **Phishing domain blocklist**: A community-maintained phishing domain
|
||||||
blocklist is vendored into the extension at build time. At runtime, the
|
blocklist is vendored into the extension at build time. At runtime, the
|
||||||
extension fetches the live list once every 24 hours to detect newly added
|
extension fetches the live list once every 24 hours to detect newly added
|
||||||
domains. Only the delta (domains not already in the vendored list) is kept in
|
domains, plus once on a start where the list is more than 24 hours old. Only
|
||||||
memory, keeping runtime memory usage small. The delta is persisted to
|
the delta (domains not already in the vendored list) is kept in memory,
|
||||||
localStorage if it is under 256 KiB.
|
keeping runtime memory usage small. The delta and the timestamp of the fetch
|
||||||
|
that produced it are persisted to extension storage if the record is under 256
|
||||||
|
KiB; an oversized delta is dropped along with its timestamp, so a later start
|
||||||
|
fetches again rather than claiming freshness for data it no longer holds. A
|
||||||
|
fetch that fails, or one whose delta was too large to store, is not retried
|
||||||
|
more than once an hour outside the 24-hour schedule.
|
||||||
- **Etherscan address labels**: When confirming a transaction, the extension
|
- **Etherscan address labels**: When confirming a transaction, the extension
|
||||||
performs a best-effort lookup of the recipient address on Etherscan to check
|
performs a best-effort lookup of the recipient address on Etherscan to check
|
||||||
for phishing/scam labels. This is a direct page fetch with no API key; the
|
for phishing/scam labels. This is a direct page fetch with no API key; the
|
||||||
@@ -1015,8 +1136,8 @@ hardcoded test phrase.
|
|||||||
- Add multiple addresses within an HD wallet
|
- Add multiple addresses within an HD wallet
|
||||||
- Manage multiple wallets simultaneously
|
- Manage multiple wallets simultaneously
|
||||||
- View ETH balance per address
|
- View ETH balance per address
|
||||||
- View ERC-20 token balances (bundled top-250 tokens, tokens with 1,000 or more
|
- View ERC-20 token balances (tokens on the bundled known-token list, tokens
|
||||||
holders, and tokens the user adds by contract address)
|
with 1,000 or more holders, and tokens the user adds by contract address)
|
||||||
- Send ETH to an address
|
- Send ETH to an address
|
||||||
- Send ERC-20 tokens to an address
|
- Send ERC-20 tokens to an address
|
||||||
- Receive ETH/tokens (display address, copy to clipboard, QR code)
|
- Receive ETH/tokens (display address, copy to clipboard, QR code)
|
||||||
@@ -1074,14 +1195,30 @@ indexes it as a real token transfer.
|
|||||||
address. Users should always verify the full address on the confirmation
|
address. Users should always verify the full address on the confirmation
|
||||||
screen before signing or sending.
|
screen before signing or sending.
|
||||||
|
|
||||||
- **Known token symbol verification**: AutistMask ships a hardcoded list of the
|
- **Known token symbol verification**: AutistMask ships a hardcoded list of
|
||||||
top 250 ERC-20 tokens with their legitimate contract addresses and symbols.
|
high-market-cap ERC-20 tokens with their legitimate contract addresses and
|
||||||
Any token transfer claiming a symbol from this list (e.g. "ETH", "USDT",
|
symbols. The list is a point-in-time snapshot of the highest-market-cap
|
||||||
"USDC") but originating from an unrecognized contract address is identified as
|
Ethereum mainnet ERC-20s taken from the CoinGecko API, with decimals verified
|
||||||
a spoof and filtered from display. The fake "Ethereum" token in the attack
|
on-chain and addresses EIP-55 checksummed; `TOKENS` in
|
||||||
above used symbol "ETH" from contract
|
`src/shared/tokenList.js` is the authoritative set. It is bundled at build
|
||||||
`0xD05339f9Ea5ab9d9F03B9d57F671d2abD1F55c82`, which does not match the known
|
time and only changes when that file is regenerated. Any token transfer
|
||||||
WETH contract — so it would be caught by this check.
|
claiming a symbol from this list (e.g. "ETH", "USDT", "USDC") but originating
|
||||||
|
from an unrecognized contract address is identified as a spoof and filtered
|
||||||
|
from display. The fake "Ethereum" token in the attack above used symbol "ETH"
|
||||||
|
from contract `0xD05339f9Ea5ab9d9F03B9d57F671d2abD1F55c82`, which does not
|
||||||
|
match the known WETH contract — so it would be caught by this check. Detecting
|
||||||
|
a spoof is also what adds a contract to the fraud contract blocklist below;
|
||||||
|
that is the only thing that populates it. In the transaction history the check
|
||||||
|
is the "Hide fake tokens impersonating a known symbol" setting, on by default;
|
||||||
|
with it off, spoofed transfers are shown and no new blocklist entries are
|
||||||
|
learned from them. The send-screen token selector applies the same check
|
||||||
|
unconditionally, because it decides which tokens the user can act on rather
|
||||||
|
than what the history displays. The balance list applies it unconditionally
|
||||||
|
too, but not identically: it exempts symbols that `KNOWN_SYMBOLS` maps to
|
||||||
|
`null`, and `"ETH"` is the only one. So the fake "Ethereum" token above is
|
||||||
|
filtered from the transaction history and from the send selector, but a
|
||||||
|
fake-`ETH` ERC-20 that clears the balance list's own 1,000-holder floor — or
|
||||||
|
that the user tracked manually — is still shown in the balance list.
|
||||||
|
|
||||||
- **Low-holder token filtering**: Token transfers from ERC-20 contracts with
|
- **Low-holder token filtering**: Token transfers from ERC-20 contracts with
|
||||||
fewer than 1,000 holders are hidden from transaction history by default.
|
fewer than 1,000 holders are hidden from transaction history by default.
|
||||||
@@ -1108,13 +1245,22 @@ indexes it as a real token transfer.
|
|||||||
it. AutistMask hides transactions below a configurable dust threshold
|
it. AutistMask hides transactions below a configurable dust threshold
|
||||||
(default: 100,000 gwei / 0.0001 ETH). This is high enough to filter poisoning
|
(default: 100,000 gwei / 0.0001 ETH). This is high enough to filter poisoning
|
||||||
dust while low enough to preserve any transfer a user would plausibly care
|
dust while low enough to preserve any transfer a user would plausibly care
|
||||||
about. The threshold is user-configurable in Settings.
|
about. The threshold is user-configurable in Settings; a threshold of `0`
|
||||||
|
hides nothing, exactly as clearing the checkbox does.
|
||||||
|
|
||||||
- **User-configurable**: All of the above filters (known symbol verification,
|
- **User-configurable**: All four filters (known symbol verification, low-holder
|
||||||
low-holder threshold, fraud contract blocklist, dust threshold) are settings
|
threshold, fraud contract blocklist, dust threshold) are settings that default
|
||||||
that default to on but can be individually disabled by the user. AutistMask is
|
to on but can be individually disabled by the user. AutistMask is designed as
|
||||||
designed as a sharp tool — users who understand the risks can configure the
|
a sharp tool — users who understand the risks can configure the wallet to show
|
||||||
wallet to show everything unfiltered, unix-style.
|
everything unfiltered, unix-style. All four settings govern the transaction
|
||||||
|
history; what else each one reaches varies. The known-symbol check also runs
|
||||||
|
unconditionally on the send-screen token selector, and on the balance list
|
||||||
|
except for symbols mapped to `null` (`"ETH"` alone), which the balance list
|
||||||
|
does not filter. The fraud contract blocklist is applied unconditionally on
|
||||||
|
that selector and is not consulted by the balance list at all. The low-holder
|
||||||
|
setting also gates the send selector, while the balance list's own
|
||||||
|
1,000-holder floor is unconditional (see Data Model). The dust threshold
|
||||||
|
applies to the transaction history alone.
|
||||||
|
|
||||||
#### Phishing Domain Protection
|
#### Phishing Domain Protection
|
||||||
|
|
||||||
@@ -1126,6 +1272,12 @@ live list once every 24 hours and keeps only the delta (newly added domains not
|
|||||||
in the vendored list) in memory. This architecture keeps runtime memory usage
|
in the vendored list) in memory. This architecture keeps runtime memory usage
|
||||||
small while ensuring fresh coverage of new phishing domains.
|
small while ensuring fresh coverage of new phishing domains.
|
||||||
|
|
||||||
|
The 24-hour cadence is an alarm, not a timer; the alarm tick fetches
|
||||||
|
unconditionally rather than re-checking the 24-hour cache TTL that gates the
|
||||||
|
startup path; and the fetch timestamps live in extension storage rather than in
|
||||||
|
module variables — see [Background scheduling](#background-scheduling) for why
|
||||||
|
all three are required.
|
||||||
|
|
||||||
When a dApp on a blocklisted domain requests a wallet connection, transaction
|
When a dApp on a blocklisted domain requests a wallet connection, transaction
|
||||||
approval, or signature, the approval popup displays a prominent red warning
|
approval, or signature, the approval popup displays a prominent red warning
|
||||||
banner alerting the user. The domain checker matches exact hostnames and all
|
banner alerting the user. The domain checker matches exact hostnames and all
|
||||||
@@ -1181,7 +1333,7 @@ Currently supported:
|
|||||||
|
|
||||||
- [x] Delete wallet (with confirmation)
|
- [x] Delete wallet (with confirmation)
|
||||||
- [ ] Delete address from HD wallet (with confirmation)
|
- [ ] Delete address from HD wallet (with confirmation)
|
||||||
- [ ] Show wallet's recovery phrase (requires password)
|
- [x] Show wallet's recovery phrase (requires password)
|
||||||
|
|
||||||
### Transactions
|
### Transactions
|
||||||
|
|
||||||
@@ -1189,8 +1341,8 @@ Currently supported:
|
|||||||
|
|
||||||
### Testing
|
### Testing
|
||||||
|
|
||||||
- [ ] Tests for mnemonic generation and address derivation
|
- [x] Tests for mnemonic generation and address derivation
|
||||||
- [ ] Tests for xpub derivation and child address generation
|
- [x] Tests for xpub derivation and child address generation
|
||||||
- [ ] Test on Firefox (Manifest V2)
|
- [ ] Test on Firefox (Manifest V2)
|
||||||
|
|
||||||
### Scam List
|
### Scam List
|
||||||
|
|||||||
52
TODO.md
52
TODO.md
@@ -44,11 +44,56 @@ undefined identifiers, which is how
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-08-12: Bundled token list documentation no longer states a count. The
|
||||||
|
four "top 250" claims in `README.md` and the "roughly 500" claim in
|
||||||
|
`docs/README.md` are replaced with a description of how the list is actually
|
||||||
|
selected — a point-in-time CoinGecko snapshot of the highest-market-cap
|
||||||
|
Ethereum mainnet ERC-20s — with `TOKENS` in `src/shared/tokenList.js` named as
|
||||||
|
the authoritative set
|
||||||
|
([#239](https://git.eeqj.de/sneak/AutistMask/issues/239)).
|
||||||
- 2026-08-11: Approval verification became an allowlist — transaction type
|
- 2026-08-11: Approval verification became an allowlist — transaction type
|
||||||
restricted to 0/1/2 so an EIP-7702 delegation can no longer ride along on an
|
restricted to 0/1/2 so an EIP-7702 delegation can no longer ride along on an
|
||||||
approved transfer, every consequential field compared, and the artifact
|
approved transfer, every consequential field compared, the artifact
|
||||||
re-serialized from the checked fields alone; broadcast failure is now terminal
|
re-serialized from the checked fields alone and its exact bytes required to be
|
||||||
|
the canonical encoding of what was broadcast, and one approval now yields at
|
||||||
|
most one broadcast; broadcast failure is terminal
|
||||||
([#174](https://git.eeqj.de/sneak/AutistMask/issues/174)).
|
([#174](https://git.eeqj.de/sneak/AutistMask/issues/174)).
|
||||||
|
- 2026-08-11: Known-symbol spoof verification became a Settings toggle
|
||||||
|
(`hideSpoofedSymbols`), on by default, governing the transaction-history
|
||||||
|
filter and the fraud-contract learning it feeds
|
||||||
|
([#176](https://git.eeqj.de/sneak/AutistMask/issues/176)).
|
||||||
|
- 2026-08-11: `script/verify-build` now walks `dist/` NUL-delimited and asserts
|
||||||
|
`dist/` is a real directory, so a path with a trailing space or a newline can
|
||||||
|
no longer carry a debug marker past the unlisted-bundle check
|
||||||
|
([#223](https://git.eeqj.de/sneak/AutistMask/issues/223)).
|
||||||
|
- 2026-08-11: UTC Timestamps checkbox moved from the Token Spam Protection well
|
||||||
|
into Display, next to the theme selector
|
||||||
|
([#212](https://git.eeqj.de/sneak/AutistMask/issues/212)).
|
||||||
|
- 2026-08-11: Network fee counted in the confirmation-screen balance check for
|
||||||
|
both ETH and ERC-20 sends, reserving what the node actually charges a type-2
|
||||||
|
transaction, with the arithmetic in a pure, unit-tested
|
||||||
|
`src/shared/txValidation.js`
|
||||||
|
([#154](https://git.eeqj.de/sneak/AutistMask/issues/154)).
|
||||||
|
- 2026-08-11: A dust threshold of `0` now means "hide nothing" instead of
|
||||||
|
falling back to the 100,000 gwei default, and every address comparison in
|
||||||
|
`src/shared/transactions.js` goes through one case-normalising helper so a
|
||||||
|
checksummed genuine contract is no longer read as a spoof
|
||||||
|
([#179](https://git.eeqj.de/sneak/AutistMask/issues/179)).
|
||||||
|
- 2026-08-11: Password-gated recovery phrase display for HD wallets, reached
|
||||||
|
from the wallet row in Settings, wiped on leaving the screen and excluded from
|
||||||
|
the views the popup can reopen onto
|
||||||
|
([#161](https://git.eeqj.de/sneak/AutistMask/issues/161)).
|
||||||
|
- 2026-08-11: Extended-key import hardened — the base58 checksum is now enforced
|
||||||
|
on every xprv and xpub, and a non-master key is refused with an explanation
|
||||||
|
instead of being derived beneath
|
||||||
|
([#210](https://git.eeqj.de/sneak/AutistMask/issues/210)).
|
||||||
|
- 2026-08-11: the balance refresh and the 24-hour phishing list refresh moved
|
||||||
|
from `setInterval` to the extension alarms API, with the phishing delta and
|
||||||
|
its fetch timestamps persisted to extension storage, so neither job dies with
|
||||||
|
the MV3 service worker. Each job's freshness guard was decoupled from its
|
||||||
|
alarm period at the same time — timed to the period, a guard vetoes its own
|
||||||
|
scheduled tick and halves the real refresh rate
|
||||||
|
([#158](https://git.eeqj.de/sneak/AutistMask/issues/158)).
|
||||||
- 2026-08-11: Policy compliance sweep — conditional verbose test rerun, local
|
- 2026-08-11: Policy compliance sweep — conditional verbose test rerun, local
|
||||||
Tailwind binary instead of `npx`, `--frozen-lockfile` on `make install`, and
|
Tailwind binary instead of `npx`, `--frozen-lockfile` on `make install`, and
|
||||||
the Makefile-only targets documented in the README
|
the Makefile-only targets documented in the README
|
||||||
@@ -59,6 +104,9 @@ undefined identifiers, which is how
|
|||||||
lives only in `build.js`, and the unlisted-bundle scan hard-fails when it
|
lives only in `build.js`, and the unlisted-bundle scan hard-fails when it
|
||||||
cannot enumerate `dist/`
|
cannot enumerate `dist/`
|
||||||
([#180](https://git.eeqj.de/sneak/AutistMask/issues/180)).
|
([#180](https://git.eeqj.de/sneak/AutistMask/issues/180)).
|
||||||
|
- 2026-08-11: Known-answer test coverage for the crypto core — BIP-39/BIP-32
|
||||||
|
derivation in `wallet.js` and the Argon2id vault in `vault.js`
|
||||||
|
([#159](https://git.eeqj.de/sneak/AutistMask/issues/159)).
|
||||||
- 2026-08-11: Three `README.md` claims corrected against the code — blocklist
|
- 2026-08-11: Three `README.md` claims corrected against the code — blocklist
|
||||||
attribution, token-display rule, navigation model
|
attribution, token-display rule, navigation model
|
||||||
([#213](https://git.eeqj.de/sneak/AutistMask/issues/213)).
|
([#213](https://git.eeqj.de/sneak/AutistMask/issues/213)).
|
||||||
|
|||||||
@@ -130,10 +130,14 @@ live list to pick up newly added domains, keeping only the entries not already
|
|||||||
in the bundled copy (persisted locally if under 256 KiB). This endpoint is not
|
in the bundled copy (persisted locally if under 256 KiB). This endpoint is not
|
||||||
user-configurable.
|
user-configurable.
|
||||||
|
|
||||||
When it is contacted: once when the background script starts, and every 24 hours
|
When it is contacted: when the background script starts, if the last fetch was
|
||||||
after that. It is a plain download of a public file — nothing about you is sent,
|
more than 24 hours ago, and every 24 hours after that. The time of the last
|
||||||
but the host sees your IP address. If the fetch fails, the bundled copy is still
|
fetch is remembered across browser and background restarts, so restarting does
|
||||||
used.
|
not cause a re-download. If a fetch fails, or the list is too large to keep, the
|
||||||
|
extension waits an hour before trying again outside that 24-hour schedule rather
|
||||||
|
than retrying on every restart. It is a plain download of a public file —
|
||||||
|
nothing about you is sent, but the host sees your IP address. If the fetch
|
||||||
|
fails, the bundled copy is still used.
|
||||||
|
|
||||||
**Etherscan address labels** (`etherscan.io`; `sepolia.etherscan.io` on Sepolia)
|
**Etherscan address labels** (`etherscan.io`; `sepolia.etherscan.io` on Sepolia)
|
||||||
|
|
||||||
@@ -265,7 +269,10 @@ The confirmation screen shows:
|
|||||||
- **From and To addresses** with identicons and Etherscan links
|
- **From and To addresses** with identicons and Etherscan links
|
||||||
- **Amount** with USD estimate
|
- **Amount** with USD estimate
|
||||||
- **Your current balance** with USD estimate
|
- **Your current balance** with USD estimate
|
||||||
- **Estimated network fee** in ETH with USD estimate
|
- **Network fee** — what the transfer is expected to cost, in ETH with a USD
|
||||||
|
estimate, and below it the larger amount reserved until it confirms. The
|
||||||
|
reserve is what the network requires up front and what the balance check gates
|
||||||
|
on; the refund of the difference is why the two differ
|
||||||
- **Warnings** if the recipient is a contract, a burn address, one of your own
|
- **Warnings** if the recipient is a contract, a burn address, one of your own
|
||||||
addresses, on the bundled scam-address list, or labelled as a phisher on
|
addresses, on the bundled scam-address list, or labelled as a phisher on
|
||||||
Etherscan
|
Etherscan
|
||||||
@@ -320,10 +327,19 @@ individually removed to reset their permissions.
|
|||||||
AutistMask includes several defenses against common Ethereum scams, all enabled
|
AutistMask includes several defenses against common Ethereum scams, all enabled
|
||||||
by default:
|
by default:
|
||||||
|
|
||||||
**Known token symbol verification.** AutistMask ships a list of roughly 500
|
**Known token symbol verification.** AutistMask ships a bundled list of
|
||||||
legitimate ERC-20 tokens with their contract addresses. If a transaction or
|
high-market-cap ERC-20 tokens with their legitimate contract addresses — a
|
||||||
balance claims to involve a known symbol (like "ETH" or "USDT") but comes from
|
point-in-time snapshot of the highest-market-cap Ethereum mainnet ERC-20s, fixed
|
||||||
an unrecognized contract, it is identified as a spoof and hidden.
|
at build time and updated only when a new release ships a newer snapshot. If a
|
||||||
|
transaction or balance claims to involve a known symbol (like "ETH" or "USDT")
|
||||||
|
but comes from an unrecognized contract, it is identified as a spoof and hidden.
|
||||||
|
In your transaction history this is the "Hide fake tokens impersonating a known
|
||||||
|
symbol" setting, which you can switch off; doing so also stops new entries being
|
||||||
|
added to the fraud contract blocklist below, since detecting a spoof is what
|
||||||
|
fills it. The send token list always applies the check. Your balances apply it
|
||||||
|
too, with one exception: a token claiming the symbol "ETH" is not filtered
|
||||||
|
there, so a fake "ETH" token can still show up in your balance list even though
|
||||||
|
it is hidden from your transaction history and from the send token list.
|
||||||
|
|
||||||
**Low-holder token filtering.** Tokens with fewer than 1,000 holders are hidden
|
**Low-holder token filtering.** Tokens with fewer than 1,000 holders are hidden
|
||||||
from transaction history and the send token list, and are left out of your
|
from transaction history and the send token list, and are left out of your
|
||||||
@@ -359,16 +375,16 @@ Click the gear icon on the home screen to access settings:
|
|||||||
- **Wallets**: Your wallets, and "+ Add wallet".
|
- **Wallets**: Your wallets, and "+ Add wallet".
|
||||||
- **Tracked Tokens**: The ERC-20 tokens tracked across all addresses, and "+ Add
|
- **Tracked Tokens**: The ERC-20 tokens tracked across all addresses, and "+ Add
|
||||||
token".
|
token".
|
||||||
- **Display**: Toggle whether tracked tokens with zero balance are shown, and
|
- **Display**: Toggle whether tracked tokens with zero balance are shown, switch
|
||||||
choose the theme (System, Light, or Dark).
|
timestamps to UTC, and choose the theme (System, Light, or Dark).
|
||||||
- **Network**: Switch between Ethereum Mainnet and Sepolia Testnet. Switching
|
- **Network**: Switch between Ethereum Mainnet and Sepolia Testnet. Switching
|
||||||
resets the RPC and Blockscout endpoints to that network's defaults.
|
resets the RPC and Blockscout endpoints to that network's defaults.
|
||||||
- **Ethereum RPC**: Change the Ethereum node endpoint. Default is a public RPC.
|
- **Ethereum RPC**: Change the Ethereum node endpoint. Default is a public RPC.
|
||||||
You can use your own node for maximum privacy.
|
You can use your own node for maximum privacy.
|
||||||
- **Blockscout API**: Change the Blockscout instance used for token balances and
|
- **Blockscout API**: Change the Blockscout instance used for token balances and
|
||||||
transaction history. You can use a self-hosted instance.
|
transaction history. You can use a self-hosted instance.
|
||||||
- **Token Spam Protection**: Toggle individual scam filters, set the dust
|
- **Token Spam Protection**: Toggle individual scam filters and set the dust
|
||||||
transaction threshold, and switch timestamps to UTC.
|
transaction threshold.
|
||||||
- **Allowed Sites / Denied Sites**: View and manage web3 site permissions.
|
- **Allowed Sites / Denied Sites**: View and manage web3 site permissions.
|
||||||
- **About**: License, author, version, release date, and a link to the commit
|
- **About**: License, author, version, release date, and a link to the commit
|
||||||
this build came from.
|
this build came from.
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "AutistMask",
|
"name": "AutistMask",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Minimal Ethereum wallet for Chrome",
|
"description": "Minimal Ethereum wallet for Chrome",
|
||||||
"permissions": ["storage", "activeTab"],
|
"permissions": ["storage", "activeTab", "alarms"],
|
||||||
"host_permissions": ["<all_urls>"],
|
"host_permissions": ["<all_urls>"],
|
||||||
"action": {
|
"action": {
|
||||||
"default_popup": "src/popup/index.html"
|
"default_popup": "src/popup/index.html"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "AutistMask",
|
"name": "AutistMask",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Minimal Ethereum wallet for Firefox",
|
"description": "Minimal Ethereum wallet for Firefox",
|
||||||
"permissions": ["storage", "activeTab", "<all_urls>"],
|
"permissions": ["storage", "activeTab", "alarms", "<all_urls>"],
|
||||||
"browser_action": {
|
"browser_action": {
|
||||||
"default_popup": "src/popup/index.html"
|
"default_popup": "src/popup/index.html"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,6 +22,18 @@ set -eu
|
|||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
|
# Absolute path to this script, resolved before anything cd's anywhere.
|
||||||
|
# check_unlisted_bundles re-invokes it through xargs, and $0 on its own may be
|
||||||
|
# relative to a directory we are about to leave.
|
||||||
|
SELF="$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")"
|
||||||
|
|
||||||
|
# Internal re-entry flag; see scan_dist_paths.
|
||||||
|
SCAN_FLAG="--scan-dist-paths"
|
||||||
|
|
||||||
|
# A literal newline, for the is_listed guard.
|
||||||
|
NEWLINE='
|
||||||
|
'
|
||||||
|
|
||||||
MANIFEST="dist/constants-bundles.txt"
|
MANIFEST="dist/constants-bundles.txt"
|
||||||
MARKER_ON="autistmask-build-debug=on"
|
MARKER_ON="autistmask-build-debug=on"
|
||||||
MARKER_OFF="autistmask-build-debug=off"
|
MARKER_OFF="autistmask-build-debug=off"
|
||||||
@@ -29,11 +41,20 @@ MARKER_OFF="autistmask-build-debug=off"
|
|||||||
# Set by read_marker.
|
# Set by read_marker.
|
||||||
MARKER=""
|
MARKER=""
|
||||||
|
|
||||||
|
# Temporary file holding the NUL-delimited dist/ listing, removed by the EXIT
|
||||||
|
# trap because fail() exits from wherever it is called.
|
||||||
|
LISTING=""
|
||||||
|
|
||||||
fail() {
|
fail() {
|
||||||
echo "verify-build: FAIL: $*" >&2
|
echo "verify-build: FAIL: $*" >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
[ -z "$LISTING" ] || rm -f "$LISTING"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
# Is the literal $1 present in the file $2? Match (grep exit 0) and no-match
|
# Is the literal $1 present in the file $2? Match (grep exit 0) and no-match
|
||||||
# (exit 1) are answers about the emitted output. Anything else (exit 2: the
|
# (exit 1) are answers about the emitted output. Anything else (exit 2: the
|
||||||
# file could not be read) is not an answer at all, and must not be reported as
|
# file could not be read) is not an answer at all, and must not be reported as
|
||||||
@@ -58,7 +79,17 @@ has_marker() {
|
|||||||
# manifest could not be read and is not an answer at all. Without this, an
|
# manifest could not be read and is not an answer at all. Without this, an
|
||||||
# unreadable manifest reads as "this file is not listed" and every emitted
|
# unreadable manifest reads as "this file is not listed" and every emitted
|
||||||
# bundle gets reported as an unlisted one.
|
# bundle gets reported as an unlisted one.
|
||||||
|
#
|
||||||
|
# A path containing a newline is answered without asking grep, because grep
|
||||||
|
# would read the pattern as two patterns and report a match on either. That is
|
||||||
|
# how such a path escaped this check even once the walk stopped splitting it:
|
||||||
|
# the half before the newline matched a listed line and the file was skipped.
|
||||||
|
# The manifest is line-delimited, so it cannot name such a path at all, and
|
||||||
|
# "not listed" is the only true answer.
|
||||||
is_listed() {
|
is_listed() {
|
||||||
|
case "$1" in
|
||||||
|
*"$NEWLINE"*) return 1 ;;
|
||||||
|
esac
|
||||||
_il_status=0
|
_il_status=0
|
||||||
grep -q -x -F -e "$1" -- "$MANIFEST" || _il_status=$?
|
grep -q -x -F -e "$1" -- "$MANIFEST" || _il_status=$?
|
||||||
case "$_il_status" in
|
case "$_il_status" in
|
||||||
@@ -117,35 +148,66 @@ read_marker() {
|
|||||||
# an endsWith(".js") test; repeating that literal here would mean a bundle
|
# an endsWith(".js") test; repeating that literal here would mean a bundle
|
||||||
# emitted under some other extension escaped the manifest AND this check at
|
# emitted under some other extension escaped the manifest AND this check at
|
||||||
# once, which is the correlated blind spot the two-source design exists to
|
# once, which is the correlated blind spot the two-source design exists to
|
||||||
# avoid. Every file under dist/ is searched, so build.js's filter is the only
|
# avoid. Every regular file and every symlink under dist/ is searched — that
|
||||||
# place the assumption lives and this check is what catches it being wrong.
|
# is the whole of what a build emits — so build.js's filter is the only place
|
||||||
|
# the assumption lives and this check is what catches it being wrong.
|
||||||
#
|
#
|
||||||
# That claim only holds if the walk is exhaustive, so two things are enforced
|
# That claim only holds if the walk is exhaustive and every name survives it
|
||||||
# here rather than assumed:
|
# intact, so four things are enforced here rather than assumed:
|
||||||
#
|
#
|
||||||
|
# - the walk is NUL-delimited and the paths reach the check as arguments, so
|
||||||
|
# no name can be reshaped on the way in. Read line by line, a name with a
|
||||||
|
# trailing space lost it to read's field splitting and the remnant then
|
||||||
|
# matched a manifest line, and a name containing a newline arrived as a
|
||||||
|
# listed path plus an empty one. Both left a marker-carrying, unlisted file
|
||||||
|
# unchecked while the script still reported success. Delivering such a name
|
||||||
|
# intact is only half of it; is_listed also has to keep it out of grep's
|
||||||
|
# pattern, for the same reason.
|
||||||
# - find's exit status is checked. A subtree it cannot descend is reported on
|
# - find's exit status is checked. A subtree it cannot descend is reported on
|
||||||
# stderr and then simply missing from the listing, so an unchecked status
|
# stderr and then simply missing from the listing, so an unchecked status
|
||||||
# turns "could not look" into "nothing was there" — the same conflation
|
# turns "could not look" into "nothing was there" — the same conflation
|
||||||
# has_marker exists to prevent. The status cannot be read off a pipeline
|
# has_marker exists to prevent. The status cannot be read off a pipeline,
|
||||||
# ending in sort, so the sort is a separate step.
|
# so the listing lands in a file that xargs then reads back.
|
||||||
# - symlinks are walked too (-type l), not skipped. A marker-carrying bundle
|
# - symlinks are walked too (-type l), not skipped. A marker-carrying bundle
|
||||||
# reachable under an unlisted path in dist/ is a stale manifest whether the
|
# reachable under an unlisted path in dist/ is a stale manifest whether the
|
||||||
# path is a link or a file, and grep reads through the link. A link that
|
# path is a link or a file, and grep reads through the link. A link that
|
||||||
# cannot be read through — dangling, or pointing at a directory — fails
|
# cannot be read through — dangling, or pointing at a directory — fails
|
||||||
# hard via has_marker's exit-2 path, which is the fail-closed answer: the
|
# hard via has_marker's exit-2 path, which is the fail-closed answer: the
|
||||||
# build emits neither, so their DEBUG state is unproven, not fine.
|
# build emits neither, so their DEBUG state is unproven, not fine.
|
||||||
|
# - dist/ itself must be a directory and not a symlink, which main asserts
|
||||||
|
# before anything reads through it. find does not follow a symlink named on
|
||||||
|
# its own command line, so a linked dist/ collapses this walk to one entry
|
||||||
|
# and cross-checks nothing.
|
||||||
|
#
|
||||||
|
# Types other than regular files and symlinks are left out on purpose: a build
|
||||||
|
# emits none of them, and grep on a fifo would hang rather than fail.
|
||||||
check_unlisted_bundles() {
|
check_unlisted_bundles() {
|
||||||
|
LISTING="$(mktemp "${TMPDIR:-/tmp}/verify-build-dist.XXXXXX")" ||
|
||||||
|
fail "could not create a temporary file for the dist/ listing, so the
|
||||||
|
tree was never walked. Refusing to report success."
|
||||||
|
|
||||||
_find_status=0
|
_find_status=0
|
||||||
_listing="$(find dist \( -type f -o -type l \) -print)" || _find_status=$?
|
find dist \( -type f -o -type l \) -print0 >"$LISTING" || _find_status=$?
|
||||||
[ "$_find_status" -eq 0 ] ||
|
[ "$_find_status" -eq 0 ] ||
|
||||||
fail "find exited $_find_status enumerating dist/, so part of the tree
|
fail "find exited $_find_status enumerating dist/, so part of the tree
|
||||||
was never walked and nothing was established about the files in it. Any
|
was never walked and nothing was established about the files in it. Any
|
||||||
unlisted bundle there went unchecked. That is a permissions or I/O fault on
|
unlisted bundle there went unchecked. That is a permissions or I/O fault on
|
||||||
the artifact, not a stale manifest. Refusing to report success."
|
the artifact, not a stale manifest. Refusing to report success."
|
||||||
_listing="$(printf '%s\n' "$_listing" | sort)"
|
|
||||||
|
|
||||||
while read -r _file; do
|
_scan_status=0
|
||||||
[ -n "$_file" ] || continue
|
xargs -0 "$SELF" "$SCAN_FLAG" <"$LISTING" || _scan_status=$?
|
||||||
|
[ "$_scan_status" -eq 0 ] ||
|
||||||
|
fail "the unlisted-bundle scan exited $_scan_status: either a path
|
||||||
|
under dist/ failed the check reported above, or the scan could not be run
|
||||||
|
at all. Refusing to report success."
|
||||||
|
}
|
||||||
|
|
||||||
|
# The per-path half of check_unlisted_bundles. It runs in a re-invocation of
|
||||||
|
# this script, so it uses the same is_listed and has_marker as the rest of the
|
||||||
|
# file rather than a second copy of them that could drift. Paths arrive as
|
||||||
|
# arguments and are never split, joined or trimmed.
|
||||||
|
scan_dist_paths() {
|
||||||
|
for _file in "$@"; do
|
||||||
if is_listed "$_file"; then
|
if is_listed "$_file"; then
|
||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
@@ -154,9 +216,7 @@ check_unlisted_bundles() {
|
|||||||
fail "$_file carries a debug marker but is absent from $MANIFEST,
|
fail "$_file carries a debug marker but is absent from $MANIFEST,
|
||||||
so the manifest no longer describes the emitted bundles."
|
so the manifest no longer describes the emitted bundles."
|
||||||
fi
|
fi
|
||||||
done <<EOF
|
done
|
||||||
$_listing
|
|
||||||
EOF
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# The requested mode, read from our own environment using build.js's exact
|
# The requested mode, read from our own environment using build.js's exact
|
||||||
@@ -173,9 +233,32 @@ expected_marker() {
|
|||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
|
|
||||||
|
# Internal re-entry from check_unlisted_bundles' xargs. Not part of the
|
||||||
|
# command-line interface: nothing else invokes it, and it is a distinct
|
||||||
|
# entry point rather than a mode flag threaded through the checks below.
|
||||||
|
if [ "${1-}" = "$SCAN_FLAG" ]; then
|
||||||
|
shift
|
||||||
|
scan_dist_paths "$@"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
expected="$(expected_marker)"
|
expected="$(expected_marker)"
|
||||||
echo "Verifying emitted bundles (expecting $expected)..."
|
echo "Verifying emitted bundles (expecting $expected)..."
|
||||||
|
|
||||||
|
# Asserted here rather than left to grep. A symlinked dist/ used to fail
|
||||||
|
# only because GNU grep exits 2 on a directory, so check_unlisted_bundles'
|
||||||
|
# single entry hit has_marker's I/O path by luck; under a grep that exits 1
|
||||||
|
# instead, the whole cross-check would have collapsed into a pass.
|
||||||
|
if [ -h dist ]; then
|
||||||
|
fail "dist is a symlink, not a directory. find does not follow a
|
||||||
|
symlink named on its own command line, so the unlisted-bundle cross-check
|
||||||
|
would see one entry instead of the emitted tree and establish nothing about
|
||||||
|
it. Refusing to report success."
|
||||||
|
fi
|
||||||
|
[ -d dist ] ||
|
||||||
|
fail "dist is not a directory, so there is no emitted tree to verify.
|
||||||
|
build.js writes it; run make build first."
|
||||||
|
|
||||||
[ -f "$MANIFEST" ] ||
|
[ -f "$MANIFEST" ] ||
|
||||||
fail "$MANIFEST is missing. build.js writes it at the end of a
|
fail "$MANIFEST is missing. build.js writes it at the end of a
|
||||||
successful build; run make build first."
|
successful build; run make build first."
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const {
|
|||||||
currentNetwork,
|
currentNetwork,
|
||||||
} = require("../shared/state");
|
} = require("../shared/state");
|
||||||
const { refreshBalances, getProvider } = require("../shared/balances");
|
const { refreshBalances, getProvider } = require("../shared/balances");
|
||||||
const { debugFetch } = require("../shared/log");
|
const { debugFetch, log } = require("../shared/log");
|
||||||
const {
|
const {
|
||||||
verifySignedTx,
|
verifySignedTx,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
@@ -24,9 +24,16 @@ const {
|
|||||||
} = require("../shared/approvalVerify");
|
} = require("../shared/approvalVerify");
|
||||||
const {
|
const {
|
||||||
isPhishingDomain,
|
isPhishingDomain,
|
||||||
updatePhishingList,
|
refreshPhishingListOnSchedule,
|
||||||
startPeriodicRefresh,
|
initPhishingList,
|
||||||
} = require("../shared/phishingDomains");
|
} = require("../shared/phishingDomains");
|
||||||
|
const {
|
||||||
|
BALANCE_REFRESH_ALARM,
|
||||||
|
PHISHING_REFRESH_ALARM,
|
||||||
|
BALANCE_REFRESH_PERIOD_MINUTES,
|
||||||
|
ensureRecurringAlarms,
|
||||||
|
registerAlarmHandlers,
|
||||||
|
} = require("../shared/alarms");
|
||||||
|
|
||||||
const storageApi =
|
const storageApi =
|
||||||
typeof browser !== "undefined"
|
typeof browser !== "undefined"
|
||||||
@@ -117,6 +124,29 @@ function finishApproval(id) {
|
|||||||
resetPopupUrl();
|
resetPopupUrl();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Take exclusive hold of a pending approval for one attempt, or refuse.
|
||||||
|
//
|
||||||
|
// An approval that failed retryably has to stay in pendingApprovals, so its
|
||||||
|
// presence cannot be the interlock against a second attempt; this flag is. It
|
||||||
|
// is set synchronously, before the handler's first await, so a second response
|
||||||
|
// carrying the same id — a reloaded approval window re-rendering a live
|
||||||
|
// Approve button, a popup that emits the message twice — finds the attempt
|
||||||
|
// already running instead of starting an independent verify and broadcast.
|
||||||
|
// Without it one approval can put two transactions on the chain: with the
|
||||||
|
// ordinary dApp approval shape the page fixes no nonce, so two artifacts
|
||||||
|
// signed at different nonces both verify.
|
||||||
|
function claimApproval(approval) {
|
||||||
|
if (approval.attemptInFlight) return false;
|
||||||
|
approval.attemptInFlight = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release an approval whose attempt failed in a way the user can retry.
|
||||||
|
// Nothing was broadcast, so the next attempt may claim it.
|
||||||
|
function releaseApproval(approval) {
|
||||||
|
approval.attemptInFlight = false;
|
||||||
|
}
|
||||||
|
|
||||||
// Open approval in a separate popup window.
|
// Open approval in a separate popup window.
|
||||||
// This is the primary mechanism for tx/sign approvals (triggered programmatically,
|
// This is the primary mechanism for tx/sign approvals (triggered programmatically,
|
||||||
// not from a user gesture) and the fallback for site-connection approvals.
|
// not from a user gesture) and the fallback for site-connection approvals.
|
||||||
@@ -608,12 +638,22 @@ async function broadcastAccountsChanged() {
|
|||||||
// Background balance refresh: every 60 seconds when the popup isn't open.
|
// Background balance refresh: every 60 seconds when the popup isn't open.
|
||||||
// When the popup IS open, its 10-second interval keeps lastBalanceRefresh
|
// When the popup IS open, its 10-second interval keeps lastBalanceRefresh
|
||||||
// fresh, so this naturally skips.
|
// fresh, so this naturally skips.
|
||||||
const BACKGROUND_REFRESH_INTERVAL = 60000;
|
//
|
||||||
|
// The alarm period alone sets the cadence; this guard only suppresses a
|
||||||
|
// refresh something else has just done, so it must stay strictly shorter than
|
||||||
|
// the period. Timed to the period it would veto every tick it gates —
|
||||||
|
// lastBalanceRefresh is stamped after the refresh runs, so a tick one period
|
||||||
|
// after the last one always lands inside a guard of equal length and the real
|
||||||
|
// cadence becomes two periods. Half the period keeps it comfortably above the
|
||||||
|
// popup's 10-second refresh, so an open popup still suppresses the background
|
||||||
|
// job, and comfortably below the alarm period, so the schedule always wins.
|
||||||
|
const BALANCE_REFRESH_PERIOD_MS = BALANCE_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
||||||
|
const RECENT_BALANCE_REFRESH_MS = Math.floor(BALANCE_REFRESH_PERIOD_MS / 2);
|
||||||
|
|
||||||
async function backgroundRefresh() {
|
async function backgroundRefresh() {
|
||||||
await loadState();
|
await loadState();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - (state.lastBalanceRefresh || 0) < BACKGROUND_REFRESH_INTERVAL)
|
if (now - (state.lastBalanceRefresh || 0) < RECENT_BALANCE_REFRESH_MS)
|
||||||
return;
|
return;
|
||||||
if (state.wallets.length === 0) return;
|
if (state.wallets.length === 0) return;
|
||||||
await refreshBalances(
|
await refreshBalances(
|
||||||
@@ -626,12 +666,58 @@ async function backgroundRefresh() {
|
|||||||
await saveState();
|
await saveState();
|
||||||
}
|
}
|
||||||
|
|
||||||
setInterval(backgroundRefresh, BACKGROUND_REFRESH_INTERVAL);
|
// Both recurring jobs run off alarms, not timers. On Chrome MV3 this file is
|
||||||
|
// a service worker that the browser terminates after about 30 seconds idle,
|
||||||
|
// so a setInterval would only ever survive until the first idle period and
|
||||||
|
// 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,
|
||||||
|
// The scheduled refresh, which restores persisted state on a freshly
|
||||||
|
// revived worker and then fetches unconditionally. The freshness guards
|
||||||
|
// belong to the startup path; applying them here would make the tick skip
|
||||||
|
// itself.
|
||||||
|
[PHISHING_REFRESH_ALARM]: refreshPhishingListOnSchedule,
|
||||||
|
});
|
||||||
|
|
||||||
// Fetch the phishing domain blocklist delta on startup and refresh every 24h.
|
// Everything the background context needs re-established on start. This runs
|
||||||
// The vendored blocklist is bundled at build time; this fetches only new entries.
|
// on a fresh install, on browser startup, and on every revival of a
|
||||||
updatePhishingList();
|
// terminated worker, so it must be idempotent: ensureRecurringAlarms() only
|
||||||
startPeriodicRefresh();
|
// creates alarms that are missing or carrying a stale period, and
|
||||||
|
// initPhishingList() fetches only when the persisted timestamps say the list
|
||||||
|
// is stale.
|
||||||
|
//
|
||||||
|
// On a fresh install the top-level call and the onInstalled listener both run,
|
||||||
|
// close enough together that both could see an alarm missing and create it.
|
||||||
|
// Sharing one in-flight run makes the "create only when missing" check
|
||||||
|
// race-free; the memo is dropped once it settles so a later onStartup runs
|
||||||
|
// again.
|
||||||
|
let backgroundJobsRun = null;
|
||||||
|
|
||||||
|
function startBackgroundJobs() {
|
||||||
|
if (backgroundJobsRun) return backgroundJobsRun;
|
||||||
|
backgroundJobsRun = Promise.all([
|
||||||
|
ensureRecurringAlarms(),
|
||||||
|
initPhishingList(),
|
||||||
|
])
|
||||||
|
.catch((err) => {
|
||||||
|
// An alarm that failed to schedule means a recurring job silently
|
||||||
|
// never runs again; it must not be an unhandled rejection.
|
||||||
|
log.errorf("background job startup failed:", err);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
backgroundJobsRun = null;
|
||||||
|
});
|
||||||
|
return backgroundJobsRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runtime.onInstalled) {
|
||||||
|
runtime.onInstalled.addListener(startBackgroundJobs);
|
||||||
|
}
|
||||||
|
if (runtime.onStartup) {
|
||||||
|
runtime.onStartup.addListener(startBackgroundJobs);
|
||||||
|
}
|
||||||
|
startBackgroundJobs();
|
||||||
|
|
||||||
// When approval window is closed without a response, treat as rejection
|
// When approval window is closed without a response, treat as rejection
|
||||||
if (windowsApi && windowsApi.onRemoved) {
|
if (windowsApi && windowsApi.onRemoved) {
|
||||||
@@ -752,6 +838,16 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exactly one broadcast per approval, whatever the popup sends.
|
||||||
|
if (!claimApproval(approval)) {
|
||||||
|
sendResponse({
|
||||||
|
error: "This transaction is already being sent.",
|
||||||
|
retryable: false,
|
||||||
|
stage: TX_STAGE_BROADCAST,
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await loadState();
|
await loadState();
|
||||||
@@ -775,6 +871,8 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|||||||
if (outcome.spendApproval) {
|
if (outcome.spendApproval) {
|
||||||
finishApproval(msg.id);
|
finishApproval(msg.id);
|
||||||
approval.resolve({ error: { message: outcome.error } });
|
approval.resolve({ error: { message: outcome.error } });
|
||||||
|
} else {
|
||||||
|
releaseApproval(approval);
|
||||||
}
|
}
|
||||||
sendResponse({
|
sendResponse({
|
||||||
error: outcome.error,
|
error: outcome.error,
|
||||||
@@ -829,6 +927,15 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exactly one signature handed back per approval.
|
||||||
|
if (!claimApproval(approval)) {
|
||||||
|
sendResponse({
|
||||||
|
error: "This request is already being signed.",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
const activeAddress = await getActiveAddress();
|
const activeAddress = await getActiveAddress();
|
||||||
@@ -847,6 +954,8 @@ runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
|||||||
if (!retryable) {
|
if (!retryable) {
|
||||||
finishApproval(msg.id);
|
finishApproval(msg.id);
|
||||||
approval.resolve({ error: { message: errMsg } });
|
approval.resolve({ error: { message: errMsg } });
|
||||||
|
} else {
|
||||||
|
releaseApproval(approval);
|
||||||
}
|
}
|
||||||
sendResponse({ error: errMsg, retryable });
|
sendResponse({ error: errMsg, retryable });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -136,7 +136,9 @@
|
|||||||
<div id="add-wallet-section-xprv" class="hidden">
|
<div id="add-wallet-section-xprv" class="hidden">
|
||||||
<p class="mb-2">
|
<p class="mb-2">
|
||||||
Paste your extended private key (xprv) below. This will
|
Paste your extended private key (xprv) below. This will
|
||||||
import the HD wallet and scan for used addresses.
|
import the HD wallet and scan for used addresses. It
|
||||||
|
must be the master key for the wallet; an account-level
|
||||||
|
or child key is not supported.
|
||||||
</p>
|
</p>
|
||||||
<div class="mb-2">
|
<div class="mb-2">
|
||||||
<input
|
<input
|
||||||
@@ -582,10 +584,18 @@
|
|||||||
<div id="confirm-balance" class="text-xs"></div>
|
<div id="confirm-balance" class="text-xs"></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="confirm-fee" class="mb-3" style="visibility: hidden">
|
<div id="confirm-fee" class="mb-3" style="visibility: hidden">
|
||||||
<div class="text-xs text-muted mb-1">
|
<div class="text-xs text-muted mb-1">Network fee</div>
|
||||||
Estimated network fee
|
|
||||||
</div>
|
|
||||||
<div id="confirm-fee-amount" class="text-xs"></div>
|
<div id="confirm-fee-amount" class="text-xs"></div>
|
||||||
|
<!-- Holds its one line of space from the first paint, so
|
||||||
|
the reserve appearing when the estimate lands moves
|
||||||
|
nothing. The placeholder is never seen. -->
|
||||||
|
<div
|
||||||
|
id="confirm-fee-reserve"
|
||||||
|
class="text-xs text-muted"
|
||||||
|
style="visibility: hidden"
|
||||||
|
>
|
||||||
|
reserve pending
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
id="confirm-warnings"
|
id="confirm-warnings"
|
||||||
@@ -647,6 +657,31 @@
|
|||||||
class="mb-2 border border-border border-dashed p-2"
|
class="mb-2 border border-border border-dashed p-2"
|
||||||
style="visibility: hidden; min-height: 1.25rem"
|
style="visibility: hidden; min-height: 1.25rem"
|
||||||
></div>
|
></div>
|
||||||
|
<div
|
||||||
|
id="confirm-amount-fee-error"
|
||||||
|
class="mb-2 border border-border border-dashed p-2 text-xs"
|
||||||
|
style="visibility: hidden"
|
||||||
|
>
|
||||||
|
Your balance does not cover this amount plus the network
|
||||||
|
fee. Please go back and send a smaller amount.
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="confirm-gas-error"
|
||||||
|
class="mb-2 border border-border border-dashed p-2 text-xs"
|
||||||
|
style="visibility: hidden"
|
||||||
|
>
|
||||||
|
You do not have enough ETH to pay the network fee for this
|
||||||
|
transfer. Please add ETH to this address and try again.
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="confirm-fee-unknown-error"
|
||||||
|
class="mb-2 border border-border border-dashed p-2 text-xs"
|
||||||
|
style="visibility: hidden"
|
||||||
|
>
|
||||||
|
The network fee could not be estimated, so this transaction
|
||||||
|
cannot be checked against your balance. Please go back and
|
||||||
|
try again.
|
||||||
|
</div>
|
||||||
<div class="mb-2">
|
<div class="mb-2">
|
||||||
<label class="block mb-1 text-xs">Password</label>
|
<label class="block mb-1 text-xs">Password</label>
|
||||||
<input
|
<input
|
||||||
@@ -869,6 +904,12 @@
|
|||||||
/>
|
/>
|
||||||
Show tracked tokens with zero balance
|
Show tracked tokens with zero balance
|
||||||
</label>
|
</label>
|
||||||
|
<label
|
||||||
|
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
||||||
|
>
|
||||||
|
<input type="checkbox" id="settings-utc-timestamps" />
|
||||||
|
UTC Timestamps
|
||||||
|
</label>
|
||||||
<div class="text-xs flex items-center gap-1">
|
<div class="text-xs flex items-center gap-1">
|
||||||
<label for="settings-theme">Theme:</label>
|
<label for="settings-theme">Theme:</label>
|
||||||
<select
|
<select
|
||||||
@@ -948,6 +989,15 @@
|
|||||||
transfers and prevent interaction with suspicious
|
transfers and prevent interaction with suspicious
|
||||||
tokens.
|
tokens.
|
||||||
</p>
|
</p>
|
||||||
|
<label
|
||||||
|
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="settings-hide-spoofed-symbols"
|
||||||
|
/>
|
||||||
|
Hide fake tokens impersonating a known symbol
|
||||||
|
</label>
|
||||||
<label
|
<label
|
||||||
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
class="text-xs flex items-center gap-1 cursor-pointer mb-2"
|
||||||
>
|
>
|
||||||
@@ -979,12 +1029,6 @@
|
|||||||
/>
|
/>
|
||||||
<span class="text-xs text-muted">gwei</span>
|
<span class="text-xs text-muted">gwei</span>
|
||||||
</div>
|
</div>
|
||||||
<label
|
|
||||||
class="text-xs flex items-center gap-1 cursor-pointer mb-1"
|
|
||||||
>
|
|
||||||
<input type="checkbox" id="settings-utc-timestamps" />
|
|
||||||
UTC Timestamps
|
|
||||||
</label>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="bg-well p-3 mx-1 mb-3">
|
<div class="bg-well p-3 mx-1 mb-3">
|
||||||
@@ -1098,6 +1142,52 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- ============ SHOW RECOVERY PHRASE ============ -->
|
||||||
|
<div id="view-show-phrase" class="view hidden">
|
||||||
|
<button
|
||||||
|
id="btn-show-phrase-back"
|
||||||
|
class="border border-border px-2 py-1 hover:bg-fg hover:text-bg cursor-pointer mb-2"
|
||||||
|
>
|
||||||
|
< Back
|
||||||
|
</button>
|
||||||
|
<h2 class="font-bold mb-1">Recovery Phrase</h2>
|
||||||
|
<p class="text-xs mb-3" id="show-phrase-wallet-name"></p>
|
||||||
|
<div
|
||||||
|
class="text-xs mb-3 border border-border border-dashed p-2"
|
||||||
|
>
|
||||||
|
Anyone who has these words can take every coin and token in
|
||||||
|
this wallet, from any device, without your password. Never
|
||||||
|
type them into a website and never show them to anyone.
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
id="show-phrase-flash"
|
||||||
|
class="text-xs text-red-500 mb-2 min-h-[1.25rem]"
|
||||||
|
style="visibility: hidden"
|
||||||
|
></div>
|
||||||
|
<div id="show-phrase-password-section" class="mb-2">
|
||||||
|
<label class="block mb-1">Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="show-phrase-password"
|
||||||
|
class="border border-border p-1 w-full font-mono text-sm bg-bg text-fg"
|
||||||
|
placeholder="Enter your password to continue"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
id="btn-show-phrase-reveal"
|
||||||
|
class="border border-border px-2 py-1 hover:bg-fg hover:text-bg cursor-pointer mt-2"
|
||||||
|
>
|
||||||
|
Reveal
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div id="show-phrase-result" class="hidden">
|
||||||
|
<div
|
||||||
|
id="show-phrase-value"
|
||||||
|
class="bg-danger-well rounded p-2 font-mono text-xs break-all cursor-pointer mb-1"
|
||||||
|
title="Click to copy"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- ============ SETTINGS: ADD TOKEN ============ -->
|
<!-- ============ SETTINGS: ADD TOKEN ============ -->
|
||||||
<div id="view-settings-addtoken" class="view hidden">
|
<div id="view-settings-addtoken" class="view hidden">
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -15,6 +15,10 @@ const {
|
|||||||
clearViewStack,
|
clearViewStack,
|
||||||
} = require("./views/helpers");
|
} = require("./views/helpers");
|
||||||
const { applyTheme } = require("./theme");
|
const { applyTheme } = require("./theme");
|
||||||
|
// Views that can be fully re-rendered from persisted state. All others fall
|
||||||
|
// back to the nearest restorable parent; see the module for why the
|
||||||
|
// secret-bearing views are absent.
|
||||||
|
const { RESTORABLE_VIEWS } = require("./restorableViews");
|
||||||
|
|
||||||
const home = require("./views/home");
|
const home = require("./views/home");
|
||||||
const welcome = require("./views/welcome");
|
const welcome = require("./views/welcome");
|
||||||
@@ -99,21 +103,6 @@ const ctx = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Views that can be fully re-rendered from persisted state.
|
|
||||||
// All others fall back to the nearest restorable parent.
|
|
||||||
const RESTORABLE_VIEWS = new Set([
|
|
||||||
"main",
|
|
||||||
"address",
|
|
||||||
"address-token",
|
|
||||||
"receive",
|
|
||||||
"settings",
|
|
||||||
"settings-addtoken",
|
|
||||||
"confirm-tx",
|
|
||||||
"transaction",
|
|
||||||
"success-tx",
|
|
||||||
"error-tx",
|
|
||||||
]);
|
|
||||||
|
|
||||||
function needsAddress(view) {
|
function needsAddress(view) {
|
||||||
return (
|
return (
|
||||||
view === "address" ||
|
view === "address" ||
|
||||||
|
|||||||
29
src/popup/restorableViews.js
Normal file
29
src/popup/restorableViews.js
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// Views the popup may reopen onto.
|
||||||
|
//
|
||||||
|
// The popup persists the current view so that reopening the toolbar popup
|
||||||
|
// lands the user back where they were. Only views that can be fully
|
||||||
|
// re-rendered from persisted state belong here; every other view falls back
|
||||||
|
// to the nearest restorable parent (src/popup/index.js restoreView()).
|
||||||
|
//
|
||||||
|
// A view that displays a secret must NEVER be listed. Restoring onto one
|
||||||
|
// would put a private key or a recovery phrase on screen with no password
|
||||||
|
// prompt in front of it, on a popup the user may have reopened by accident.
|
||||||
|
// That is why "export-privkey" and "show-phrase" are absent.
|
||||||
|
//
|
||||||
|
// Kept in its own module, with no dependencies, so tests can assert the
|
||||||
|
// exclusion directly rather than trusting a reading of the popup entry
|
||||||
|
// point, which cannot be required outside a browser.
|
||||||
|
const RESTORABLE_VIEWS = new Set([
|
||||||
|
"main",
|
||||||
|
"address",
|
||||||
|
"address-token",
|
||||||
|
"receive",
|
||||||
|
"settings",
|
||||||
|
"settings-addtoken",
|
||||||
|
"confirm-tx",
|
||||||
|
"transaction",
|
||||||
|
"success-tx",
|
||||||
|
"error-tx",
|
||||||
|
]);
|
||||||
|
|
||||||
|
module.exports = { RESTORABLE_VIEWS };
|
||||||
@@ -6,6 +6,7 @@ const {
|
|||||||
addressFromPrivateKey,
|
addressFromPrivateKey,
|
||||||
hdWalletFromXprv,
|
hdWalletFromXprv,
|
||||||
isValidXprv,
|
isValidXprv,
|
||||||
|
isMasterExtendedKey,
|
||||||
} = require("../../shared/wallet");
|
} = require("../../shared/wallet");
|
||||||
const { encryptWithPassword } = require("../../shared/vault");
|
const { encryptWithPassword } = require("../../shared/vault");
|
||||||
const { state, saveState } = require("../../shared/state");
|
const { state, saveState } = require("../../shared/state");
|
||||||
@@ -213,14 +214,25 @@ async function importXprvKey(ctx) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isValidXprv(xprv)) {
|
if (!isValidXprv(xprv)) {
|
||||||
showFlash("Invalid extended private key.");
|
showFlash(
|
||||||
|
"That extended private key is not valid. Please check it and try again.",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isMasterExtendedKey(xprv)) {
|
||||||
|
showFlash(
|
||||||
|
"That is an account-level or child key, which cannot be imported. " +
|
||||||
|
"Please paste the master extended private key for the wallet.",
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = hdWalletFromXprv(xprv);
|
result = hdWalletFromXprv(xprv);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showFlash("Invalid extended private key.");
|
showFlash(
|
||||||
|
"That extended private key is not valid. Please check it and try again.",
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { xpub, firstAddress } = result;
|
const { xpub, firstAddress } = result;
|
||||||
|
|||||||
@@ -148,6 +148,7 @@ async function loadTransactions(address) {
|
|||||||
state.blockscoutUrl,
|
state.blockscoutUrl,
|
||||||
);
|
);
|
||||||
const result = filterTransactions(rawTxs, {
|
const result = filterTransactions(rawTxs, {
|
||||||
|
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -222,6 +222,7 @@ async function loadTransactions(address, tokenId) {
|
|||||||
state.blockscoutUrl,
|
state.blockscoutUrl,
|
||||||
);
|
);
|
||||||
const result = filterTransactions(rawTxs, {
|
const result = filterTransactions(rawTxs, {
|
||||||
|
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -32,11 +32,24 @@ const {
|
|||||||
getFullWarnings,
|
getFullWarnings,
|
||||||
} = require("../../shared/addressWarnings");
|
} = require("../../shared/addressWarnings");
|
||||||
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
const { ERC20_ABI, isBurnAddress } = require("../../shared/constants");
|
||||||
|
const {
|
||||||
|
CODES,
|
||||||
|
FEE_PENDING,
|
||||||
|
FEE_KNOWN,
|
||||||
|
FEE_UNAVAILABLE,
|
||||||
|
feeReserveWei,
|
||||||
|
feeEstimateWei,
|
||||||
|
validateTransfer,
|
||||||
|
} = require("../../shared/txValidation");
|
||||||
const { log } = require("../../shared/log");
|
const { log } = require("../../shared/log");
|
||||||
const makeBlockie = require("ethereum-blockies-base64");
|
const makeBlockie = require("ethereum-blockies-base64");
|
||||||
const txStatus = require("./txStatus");
|
const txStatus = require("./txStatus");
|
||||||
|
|
||||||
let pendingTx = null;
|
let pendingTx = null;
|
||||||
|
// Network fee for the transaction currently on screen. Reset by show() and
|
||||||
|
// filled in by estimateGas() when the estimate resolves or fails.
|
||||||
|
let feeStatus = FEE_PENDING;
|
||||||
|
let feeWei = null;
|
||||||
|
|
||||||
function restore() {
|
function restore() {
|
||||||
const d = state.viewData;
|
const d = state.viewData;
|
||||||
@@ -67,6 +80,8 @@ function valueWithUsd(text, usdAmount) {
|
|||||||
|
|
||||||
function show(txInfo) {
|
function show(txInfo) {
|
||||||
pendingTx = txInfo;
|
pendingTx = txInfo;
|
||||||
|
feeStatus = FEE_PENDING;
|
||||||
|
feeWei = null;
|
||||||
|
|
||||||
const isErc20 = txInfo.token !== "ETH";
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
||||||
@@ -153,50 +168,14 @@ function show(txInfo) {
|
|||||||
warningsEl.style.visibility = "hidden";
|
warningsEl.style.visibility = "hidden";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for errors
|
// The two fee messages are mutually exclusive per transaction type, and
|
||||||
const errors = [];
|
// the type is known here, before the first paint. Drop the one that can
|
||||||
if (isErc20) {
|
// never apply and reserve the space of the one that can, so the async
|
||||||
const tokenBal = parseFloat(txInfo.tokenBalance || "0");
|
// estimate landing later never moves anything.
|
||||||
if (parseFloat(txInfo.amount) > tokenBal) {
|
$("confirm-amount-fee-error").classList.toggle("hidden", isErc20);
|
||||||
errors.push(
|
$("confirm-gas-error").classList.toggle("hidden", !isErc20);
|
||||||
"Insufficient " +
|
|
||||||
symbol +
|
|
||||||
" balance. You have " +
|
|
||||||
txInfo.tokenBalance +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
" but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" " +
|
|
||||||
symbol +
|
|
||||||
".",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} else if (parseFloat(txInfo.amount) > parseFloat(txInfo.balance)) {
|
|
||||||
errors.push(
|
|
||||||
"Insufficient balance. You have " +
|
|
||||||
txInfo.balance +
|
|
||||||
" ETH but are trying to send " +
|
|
||||||
txInfo.amount +
|
|
||||||
" ETH.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const errorsEl = $("confirm-errors");
|
renderValidation(txInfo);
|
||||||
const sendBtn = $("btn-confirm-send");
|
|
||||||
if (errors.length > 0) {
|
|
||||||
errorsEl.innerHTML = errors
|
|
||||||
.map((e) => `<div class="text-xs">${e}</div>`)
|
|
||||||
.join("");
|
|
||||||
errorsEl.style.visibility = "visible";
|
|
||||||
sendBtn.disabled = true;
|
|
||||||
sendBtn.classList.add("text-muted");
|
|
||||||
} else {
|
|
||||||
errorsEl.innerHTML = "";
|
|
||||||
errorsEl.style.visibility = "hidden";
|
|
||||||
sendBtn.disabled = false;
|
|
||||||
sendBtn.classList.remove("text-muted");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset password field and error
|
// Reset password field and error
|
||||||
$("confirm-tx-password").value = "";
|
$("confirm-tx-password").value = "";
|
||||||
@@ -205,6 +184,7 @@ function show(txInfo) {
|
|||||||
// Gas estimate — show placeholder then fetch async
|
// Gas estimate — show placeholder then fetch async
|
||||||
$("confirm-fee").style.visibility = "visible";
|
$("confirm-fee").style.visibility = "visible";
|
||||||
$("confirm-fee-amount").textContent = "Estimating...";
|
$("confirm-fee-amount").textContent = "Estimating...";
|
||||||
|
setVisible("confirm-fee-reserve", false);
|
||||||
state.viewData = { pendingTx: txInfo };
|
state.viewData = { pendingTx: txInfo };
|
||||||
showView("confirm-tx");
|
showView("confirm-tx");
|
||||||
attachCopyHandlers("view-confirm-tx");
|
attachCopyHandlers("view-confirm-tx");
|
||||||
@@ -224,11 +204,101 @@ function show(txInfo) {
|
|||||||
checkRecipientHistory(txInfo);
|
checkRecipientHistory(txInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Render the balance check for the transaction on screen. Called once during
|
||||||
|
// show() and again when the fee estimate resolves or fails. Every element it
|
||||||
|
// touches already occupies its space, so re-running it never moves anything.
|
||||||
|
function renderValidation(txInfo) {
|
||||||
|
const isErc20 = txInfo.token !== "ETH";
|
||||||
|
const symbol = isErc20 ? txInfo.tokenSymbol || "?" : "ETH";
|
||||||
|
|
||||||
|
const { canSend, codes } = validateTransfer({
|
||||||
|
isErc20,
|
||||||
|
amount: txInfo.amount,
|
||||||
|
ethBalance: txInfo.balance,
|
||||||
|
tokenBalance: txInfo.tokenBalance,
|
||||||
|
feeStatus,
|
||||||
|
feeWei,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Messages carrying the user's own numbers are built here; the fixed
|
||||||
|
// sentences live in the reserved elements in index.html.
|
||||||
|
const messages = [];
|
||||||
|
if (codes.includes(CODES.AMOUNT_INVALID)) {
|
||||||
|
messages.push("Please enter a valid amount to send.");
|
||||||
|
}
|
||||||
|
if (codes.includes(CODES.INSUFFICIENT_TOKEN)) {
|
||||||
|
messages.push(
|
||||||
|
"Insufficient " +
|
||||||
|
symbol +
|
||||||
|
" balance. You have " +
|
||||||
|
txInfo.tokenBalance +
|
||||||
|
" " +
|
||||||
|
symbol +
|
||||||
|
" but are trying to send " +
|
||||||
|
txInfo.amount +
|
||||||
|
" " +
|
||||||
|
symbol +
|
||||||
|
".",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (codes.includes(CODES.INSUFFICIENT_ETH)) {
|
||||||
|
messages.push(
|
||||||
|
"Insufficient balance. You have " +
|
||||||
|
txInfo.balance +
|
||||||
|
" ETH but are trying to send " +
|
||||||
|
txInfo.amount +
|
||||||
|
" ETH.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorsEl = $("confirm-errors");
|
||||||
|
if (messages.length > 0) {
|
||||||
|
errorsEl.innerHTML = messages
|
||||||
|
.map((m) => `<div class="text-xs">${escapeHtml(m)}</div>`)
|
||||||
|
.join("");
|
||||||
|
errorsEl.style.visibility = "visible";
|
||||||
|
} else {
|
||||||
|
errorsEl.innerHTML = "";
|
||||||
|
errorsEl.style.visibility = "hidden";
|
||||||
|
}
|
||||||
|
|
||||||
|
setVisible(
|
||||||
|
"confirm-amount-fee-error",
|
||||||
|
codes.includes(CODES.INSUFFICIENT_ETH_WITH_FEE),
|
||||||
|
);
|
||||||
|
setVisible(
|
||||||
|
"confirm-gas-error",
|
||||||
|
codes.includes(CODES.INSUFFICIENT_ETH_FOR_FEE),
|
||||||
|
);
|
||||||
|
setVisible(
|
||||||
|
"confirm-fee-unknown-error",
|
||||||
|
codes.includes(CODES.FEE_UNAVAILABLE),
|
||||||
|
);
|
||||||
|
|
||||||
|
// While the estimate is in flight there is no error to show — the fee
|
||||||
|
// line already reads "Estimating..." — but sending stays blocked so a
|
||||||
|
// transaction the fee would break cannot be signed in the meantime.
|
||||||
|
const sendBtn = $("btn-confirm-send");
|
||||||
|
sendBtn.disabled = !canSend;
|
||||||
|
sendBtn.classList.toggle("text-muted", !canSend);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setVisible(id, visible) {
|
||||||
|
$(id).style.visibility = visible ? "visible" : "hidden";
|
||||||
|
}
|
||||||
|
|
||||||
|
// A fee in wei as an ETH string, truncated to 6 decimal places.
|
||||||
|
function formatFeeEth(wei) {
|
||||||
|
const parts = formatEther(wei).split(".");
|
||||||
|
const dec =
|
||||||
|
parts.length > 1 ? parts[1].slice(0, 6).replace(/0+$/, "") || "0" : "0";
|
||||||
|
return parts[0] + "." + dec + " ETH";
|
||||||
|
}
|
||||||
|
|
||||||
async function estimateGas(txInfo) {
|
async function estimateGas(txInfo) {
|
||||||
try {
|
try {
|
||||||
const provider = getProvider(state.rpcUrl);
|
const provider = getProvider(state.rpcUrl);
|
||||||
const feeData = await provider.getFeeData();
|
const feeData = await provider.getFeeData();
|
||||||
const gasPrice = feeData.gasPrice;
|
|
||||||
let gasLimit;
|
let gasLimit;
|
||||||
|
|
||||||
if (txInfo.token === "ETH") {
|
if (txInfo.token === "ETH") {
|
||||||
@@ -246,21 +316,55 @@ async function estimateGas(txInfo) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const gasCostWei = gasLimit * gasPrice;
|
// What the node will require to be reserved, which is what the gate
|
||||||
const gasCostEth = formatEther(gasCostWei);
|
// must be: the send pins no fee fields, so it is broadcast as a
|
||||||
// Format to 6 significant decimal places
|
// type-2 transaction priced at maxFeePerGas.
|
||||||
const parts = gasCostEth.split(".");
|
const gasCostWei = feeReserveWei(gasLimit, feeData);
|
||||||
const dec =
|
if (gasCostWei === null) {
|
||||||
parts.length > 1
|
throw new Error("no usable gas price from the provider");
|
||||||
? parts[1].slice(0, 6).replace(/0+$/, "") || "0"
|
}
|
||||||
: "0";
|
// What the transaction is expected to cost, which is a different and
|
||||||
const feeStr = parts[0] + "." + dec + " ETH";
|
// usually much smaller number. Both are shown: quoting only the
|
||||||
|
// reserve overstates the typical cost by roughly double on mainnet,
|
||||||
|
// and quoting only the estimate contradicts the balance check.
|
||||||
|
const estimateWei = feeEstimateWei(gasLimit, feeData);
|
||||||
|
// The user may have left this transaction while the estimate was in
|
||||||
|
// flight; a stale fee must not reach the screen or the balance check.
|
||||||
|
if (pendingTx !== txInfo) return;
|
||||||
|
|
||||||
const ethPrice = getPrice("ETH");
|
const ethPrice = getPrice("ETH");
|
||||||
const feeUsd = ethPrice ? parseFloat(gasCostEth) * ethPrice : null;
|
const usd = (wei) =>
|
||||||
$("confirm-fee-amount").textContent = valueWithUsd(feeStr, feeUsd);
|
ethPrice ? parseFloat(formatEther(wei)) * ethPrice : null;
|
||||||
|
|
||||||
|
if (estimateWei !== null && estimateWei < gasCostWei) {
|
||||||
|
$("confirm-fee-amount").textContent = valueWithUsd(
|
||||||
|
"~" + formatFeeEth(estimateWei),
|
||||||
|
usd(estimateWei),
|
||||||
|
);
|
||||||
|
$("confirm-fee-reserve").textContent =
|
||||||
|
"up to " + formatFeeEth(gasCostWei) + " reserved";
|
||||||
|
setVisible("confirm-fee-reserve", true);
|
||||||
|
} else {
|
||||||
|
// No spread to report: either there is no estimate, or the node
|
||||||
|
// quotes a gas price at or above maxFeePerGas, so the expected
|
||||||
|
// cost is not below the reserve. Show the reserve alone.
|
||||||
|
$("confirm-fee-amount").textContent = valueWithUsd(
|
||||||
|
formatFeeEth(gasCostWei),
|
||||||
|
usd(gasCostWei),
|
||||||
|
);
|
||||||
|
setVisible("confirm-fee-reserve", false);
|
||||||
|
}
|
||||||
|
feeStatus = FEE_KNOWN;
|
||||||
|
feeWei = gasCostWei;
|
||||||
|
renderValidation(txInfo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.errorf("gas estimation failed:", e.message);
|
log.errorf("gas estimation failed:", e.message);
|
||||||
|
if (pendingTx !== txInfo) return;
|
||||||
$("confirm-fee-amount").textContent = "Unable to estimate";
|
$("confirm-fee-amount").textContent = "Unable to estimate";
|
||||||
|
setVisible("confirm-fee-reserve", false);
|
||||||
|
feeStatus = FEE_UNAVAILABLE;
|
||||||
|
feeWei = null;
|
||||||
|
renderValidation(txInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,8 +31,20 @@ const VIEWS = [
|
|||||||
"approve-tx",
|
"approve-tx",
|
||||||
"approve-sign",
|
"approve-sign",
|
||||||
"export-privkey",
|
"export-privkey",
|
||||||
|
"show-phrase",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Cleanup callbacks for views that hold a secret in the DOM. The view
|
||||||
|
// registers one for itself and showView() runs it whenever that view is
|
||||||
|
// navigated away from, so the secret is wiped no matter which control
|
||||||
|
// caused the navigation — "Back", the settings gear, or a jump from
|
||||||
|
// anywhere else. A per-button clear would only cover the one path.
|
||||||
|
const viewLeaveHandlers = new Map();
|
||||||
|
|
||||||
|
function onViewLeave(name, fn) {
|
||||||
|
viewLeaveHandlers.set(name, fn);
|
||||||
|
}
|
||||||
|
|
||||||
function $(id) {
|
function $(id) {
|
||||||
return document.getElementById(id);
|
return document.getElementById(id);
|
||||||
}
|
}
|
||||||
@@ -50,6 +62,11 @@ function hideError(id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function showView(name) {
|
function showView(name) {
|
||||||
|
const leaving = state.currentView;
|
||||||
|
if (leaving && leaving !== name) {
|
||||||
|
const onLeave = viewLeaveHandlers.get(leaving);
|
||||||
|
if (onLeave) onLeave();
|
||||||
|
}
|
||||||
for (const v of VIEWS) {
|
for (const v of VIEWS) {
|
||||||
const el = document.getElementById(`view-${v}`);
|
const el = document.getElementById(`view-${v}`);
|
||||||
if (el) {
|
if (el) {
|
||||||
@@ -431,10 +448,12 @@ function flashCopyFeedback(el) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
VIEWS,
|
||||||
$,
|
$,
|
||||||
showError,
|
showError,
|
||||||
hideError,
|
hideError,
|
||||||
showView,
|
showView,
|
||||||
|
onViewLeave,
|
||||||
updateDebugBanner,
|
updateDebugBanner,
|
||||||
setRenderMain,
|
setRenderMain,
|
||||||
pushCurrentView,
|
pushCurrentView,
|
||||||
|
|||||||
@@ -163,6 +163,7 @@ async function loadHomeTxs(ctx) {
|
|||||||
if (allAddresses.length === 0) return;
|
if (allAddresses.length === 0) return;
|
||||||
|
|
||||||
const filters = {
|
const filters = {
|
||||||
|
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ const { NETWORKS, SUPPORTED_CHAIN_IDS } = require("../../shared/networks");
|
|||||||
const { onChainSwitch } = require("../../shared/chainSwitch");
|
const { onChainSwitch } = require("../../shared/chainSwitch");
|
||||||
const { log, debugFetch, setRuntimeDebug } = require("../../shared/log");
|
const { log, debugFetch, setRuntimeDebug } = require("../../shared/log");
|
||||||
const deleteWallet = require("./deleteWallet");
|
const deleteWallet = require("./deleteWallet");
|
||||||
|
const showPhrase = require("./showPhrase");
|
||||||
|
const { walletHasRecoveryPhrase } = require("../../shared/wallet");
|
||||||
const {
|
const {
|
||||||
BUILD_VERSION,
|
BUILD_VERSION,
|
||||||
BUILD_LICENSE,
|
BUILD_LICENSE,
|
||||||
@@ -99,7 +101,14 @@ function renderWalletListSettings() {
|
|||||||
const name = escapeHtml(wallet.name || "Wallet " + (idx + 1));
|
const name = escapeHtml(wallet.name || "Wallet " + (idx + 1));
|
||||||
html += `<div class="flex justify-between items-center text-xs py-1 border-b border-border-light">`;
|
html += `<div class="flex justify-between items-center text-xs py-1 border-b border-border-light">`;
|
||||||
html += `<span class="settings-wallet-name cursor-pointer underline decoration-dashed" data-idx="${idx}">${name}</span>`;
|
html += `<span class="settings-wallet-name cursor-pointer underline decoration-dashed" data-idx="${idx}">${name}</span>`;
|
||||||
|
html += `<span class="flex items-center gap-1 flex-shrink-0">`;
|
||||||
|
// Key and xprv wallets have no recovery phrase, so they are never
|
||||||
|
// offered the action at all.
|
||||||
|
if (walletHasRecoveryPhrase(wallet)) {
|
||||||
|
html += `<button class="btn-show-phrase border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}" title="Show recovery phrase">[recovery phrase]</button>`;
|
||||||
|
}
|
||||||
html += `<button class="btn-delete-wallet border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}">[x]</button>`;
|
html += `<button class="btn-delete-wallet border border-border px-1 hover:bg-fg hover:text-bg cursor-pointer" data-idx="${idx}">[x]</button>`;
|
||||||
|
html += `</span>`;
|
||||||
html += `</div>`;
|
html += `</div>`;
|
||||||
});
|
});
|
||||||
container.innerHTML = html;
|
container.innerHTML = html;
|
||||||
@@ -111,6 +120,15 @@ function renderWalletListSettings() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
container.querySelectorAll(".btn-show-phrase").forEach((btn) => {
|
||||||
|
btn.addEventListener("click", () => {
|
||||||
|
const idx = parseInt(btn.dataset.idx, 10);
|
||||||
|
// No pushCurrentView() here: showPhrase.show() refuses
|
||||||
|
// non-HD wallets and pushes only when it navigates.
|
||||||
|
showPhrase.show(idx);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Inline rename on click
|
// Inline rename on click
|
||||||
container.querySelectorAll(".settings-wallet-name").forEach((span) => {
|
container.querySelectorAll(".settings-wallet-name").forEach((span) => {
|
||||||
span.addEventListener("click", () => {
|
span.addEventListener("click", () => {
|
||||||
@@ -191,6 +209,7 @@ function renderSiteLists() {
|
|||||||
|
|
||||||
function init(ctx) {
|
function init(ctx) {
|
||||||
deleteWallet.init(ctx);
|
deleteWallet.init(ctx);
|
||||||
|
showPhrase.init();
|
||||||
|
|
||||||
$("btn-save-rpc").addEventListener("click", async () => {
|
$("btn-save-rpc").addEventListener("click", async () => {
|
||||||
const url = $("settings-rpc").value.trim();
|
const url = $("settings-rpc").value.trim();
|
||||||
@@ -284,6 +303,12 @@ function init(ctx) {
|
|||||||
applyTheme(state.theme);
|
applyTheme(state.theme);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$("settings-hide-spoofed-symbols").checked = state.hideSpoofedSymbols;
|
||||||
|
$("settings-hide-spoofed-symbols").addEventListener("change", async () => {
|
||||||
|
state.hideSpoofedSymbols = $("settings-hide-spoofed-symbols").checked;
|
||||||
|
await saveState();
|
||||||
|
});
|
||||||
|
|
||||||
$("settings-hide-low-holders").checked = state.hideLowHolderTokens;
|
$("settings-hide-low-holders").checked = state.hideLowHolderTokens;
|
||||||
$("settings-hide-low-holders").addEventListener("change", async () => {
|
$("settings-hide-low-holders").addEventListener("change", async () => {
|
||||||
state.hideLowHolderTokens = $("settings-hide-low-holders").checked;
|
state.hideLowHolderTokens = $("settings-hide-low-holders").checked;
|
||||||
@@ -304,11 +329,17 @@ function init(ctx) {
|
|||||||
|
|
||||||
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
||||||
$("settings-dust-threshold").addEventListener("change", async () => {
|
$("settings-dust-threshold").addEventListener("change", async () => {
|
||||||
const val = parseInt($("settings-dust-threshold").value, 10);
|
const raw = $("settings-dust-threshold").value.trim();
|
||||||
if (!isNaN(val) && val >= 0) {
|
const val = Number(raw);
|
||||||
|
// 0 is accepted and means "hide nothing". Empty, negative,
|
||||||
|
// fractional and non-numeric input is rejected outright rather than
|
||||||
|
// coerced, and the field is put back to the stored threshold so it
|
||||||
|
// never shows a value the wallet is not using.
|
||||||
|
if (raw !== "" && Number.isInteger(val) && val >= 0) {
|
||||||
state.dustThresholdGwei = val;
|
state.dustThresholdGwei = val;
|
||||||
await saveState();
|
await saveState();
|
||||||
}
|
}
|
||||||
|
$("settings-dust-threshold").value = state.dustThresholdGwei;
|
||||||
});
|
});
|
||||||
|
|
||||||
$("settings-utc-timestamps").checked = state.utcTimestamps;
|
$("settings-utc-timestamps").checked = state.utcTimestamps;
|
||||||
|
|||||||
154
src/popup/views/showPhrase.js
Normal file
154
src/popup/views/showPhrase.js
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
// Recovery phrase display for HD wallets.
|
||||||
|
//
|
||||||
|
// The phrase is the secret that owns every address in the wallet, so it is
|
||||||
|
// handled under four rules:
|
||||||
|
//
|
||||||
|
// 1. Only an HD wallet reaches this screen (walletHasRecoveryPhrase).
|
||||||
|
// 2. Nothing is decrypted, and nothing is written into the DOM, until
|
||||||
|
// decryptWithPassword has accepted the password.
|
||||||
|
// 3. Leaving the screen by any path wipes it, via the onViewLeave hook,
|
||||||
|
// and a decrypt still in flight when that happens is discarded
|
||||||
|
// instead of written (revealGeneration).
|
||||||
|
// 4. The phrase never reaches the logger. This module deliberately does
|
||||||
|
// not import src/shared/log.js, and the failed-decrypt path reports a
|
||||||
|
// fixed sentence rather than the caught error.
|
||||||
|
//
|
||||||
|
// The phrase is also never assigned to `state`, so it cannot be persisted
|
||||||
|
// to extension storage, and "show-phrase" is excluded from RESTORABLE_VIEWS
|
||||||
|
// so the popup can never reopen onto it.
|
||||||
|
|
||||||
|
const {
|
||||||
|
$,
|
||||||
|
showView,
|
||||||
|
showFlash,
|
||||||
|
flashCopyFeedback,
|
||||||
|
goBack,
|
||||||
|
onViewLeave,
|
||||||
|
pushCurrentView,
|
||||||
|
} = require("./helpers");
|
||||||
|
const { state } = require("../../shared/state");
|
||||||
|
const { decryptWithPassword } = require("../../shared/vault");
|
||||||
|
const { walletHasRecoveryPhrase } = require("../../shared/wallet");
|
||||||
|
|
||||||
|
const VIEW = "show-phrase";
|
||||||
|
|
||||||
|
let walletIndex = null;
|
||||||
|
|
||||||
|
// Bumped by every clear(), which is what leaving the screen runs. reveal()
|
||||||
|
// captures it before awaiting the decrypt and refuses to touch the DOM if
|
||||||
|
// it has moved: a decrypt still in flight when the screen is left would
|
||||||
|
// otherwise write the phrase *after* the wipe, with nothing scheduled to
|
||||||
|
// wipe it again, leaving it in the hidden view for the life of the popup.
|
||||||
|
let revealGeneration = 0;
|
||||||
|
|
||||||
|
// True only if the reveal that captured `generation` is still the live one:
|
||||||
|
// the screen has not been left, cleared, or re-entered for another wallet
|
||||||
|
// since it started.
|
||||||
|
function isCurrentReveal(generation) {
|
||||||
|
return (
|
||||||
|
generation === revealGeneration &&
|
||||||
|
walletIndex !== null &&
|
||||||
|
state.currentView === VIEW
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
$("show-phrase-flash").textContent = message;
|
||||||
|
$("show-phrase-flash").style.visibility = "visible";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wipe every trace of the phrase and drop the wallet selection. Safe to
|
||||||
|
// call when nothing was ever revealed, and safe to call twice.
|
||||||
|
function clear() {
|
||||||
|
walletIndex = null;
|
||||||
|
revealGeneration += 1;
|
||||||
|
$("show-phrase-value").textContent = "";
|
||||||
|
$("show-phrase-password").value = "";
|
||||||
|
$("show-phrase-result").classList.add("hidden");
|
||||||
|
$("show-phrase-password-section").classList.remove("hidden");
|
||||||
|
$("show-phrase-flash").textContent = "";
|
||||||
|
$("show-phrase-flash").style.visibility = "hidden";
|
||||||
|
}
|
||||||
|
|
||||||
|
function show(walletIdx) {
|
||||||
|
const wallet = state.wallets[walletIdx];
|
||||||
|
if (!walletHasRecoveryPhrase(wallet)) {
|
||||||
|
showFlash("This wallet does not have a recovery phrase.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clear();
|
||||||
|
walletIndex = walletIdx;
|
||||||
|
$("show-phrase-wallet-name").textContent =
|
||||||
|
wallet.name || "Wallet " + (walletIdx + 1);
|
||||||
|
// Pushed here rather than by the caller: this function can return
|
||||||
|
// without navigating, and a push that happened anyway would leave an
|
||||||
|
// entry on the stack that no screen transition matches.
|
||||||
|
pushCurrentView();
|
||||||
|
showView(VIEW);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reveal() {
|
||||||
|
const password = $("show-phrase-password").value;
|
||||||
|
if (!password) {
|
||||||
|
fail("Please enter your password.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (walletIndex === null) {
|
||||||
|
fail("No wallet is selected.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const wallet = state.wallets[walletIndex];
|
||||||
|
if (!walletHasRecoveryPhrase(wallet)) {
|
||||||
|
fail("This wallet does not have a recovery phrase.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const btn = $("btn-show-phrase-reveal");
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.classList.add("text-muted");
|
||||||
|
const generation = revealGeneration;
|
||||||
|
try {
|
||||||
|
const phrase = await decryptWithPassword(
|
||||||
|
wallet.encryptedSecret,
|
||||||
|
password,
|
||||||
|
);
|
||||||
|
// The only suspension point in this view, and the only place a
|
||||||
|
// secret is written: if the screen was left while the decrypt ran,
|
||||||
|
// the wipe has already happened and this write must not land.
|
||||||
|
if (!isCurrentReveal(generation)) return;
|
||||||
|
$("show-phrase-password").value = "";
|
||||||
|
$("show-phrase-password-section").classList.add("hidden");
|
||||||
|
$("show-phrase-value").textContent = phrase;
|
||||||
|
$("show-phrase-result").classList.remove("hidden");
|
||||||
|
$("show-phrase-flash").textContent = "";
|
||||||
|
$("show-phrase-flash").style.visibility = "hidden";
|
||||||
|
} catch {
|
||||||
|
if (!isCurrentReveal(generation)) return;
|
||||||
|
// Deliberately not the caught error: the message is fixed so that
|
||||||
|
// nothing derived from the ciphertext or the attempt can surface.
|
||||||
|
fail("That password is not correct. Please try again.");
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.classList.remove("text-muted");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function init() {
|
||||||
|
onViewLeave(VIEW, clear);
|
||||||
|
|
||||||
|
$("btn-show-phrase-back").addEventListener("click", () => {
|
||||||
|
goBack();
|
||||||
|
});
|
||||||
|
|
||||||
|
$("btn-show-phrase-reveal").addEventListener("click", reveal);
|
||||||
|
|
||||||
|
$("show-phrase-value").addEventListener("click", () => {
|
||||||
|
const phrase = $("show-phrase-value").textContent;
|
||||||
|
if (!phrase) return;
|
||||||
|
navigator.clipboard.writeText(phrase);
|
||||||
|
showFlash("Copied!");
|
||||||
|
flashCopyFeedback($("show-phrase-value"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, show };
|
||||||
114
src/shared/alarms.js
Normal file
114
src/shared/alarms.js
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
// Periodic scheduling for the background context.
|
||||||
|
//
|
||||||
|
// The Chrome MV3 service worker is terminated after roughly 30 seconds idle,
|
||||||
|
// which takes every setInterval/setTimeout with it. The extension alarms API
|
||||||
|
// is the mechanism that survives: the browser holds the schedule and wakes
|
||||||
|
// the worker to deliver onAlarm. Firefox MV2 runs a persistent background
|
||||||
|
// page where timers would survive, but alarms behave identically there, so
|
||||||
|
// both targets share this path and both manifests declare the "alarms"
|
||||||
|
// permission.
|
||||||
|
//
|
||||||
|
// Periods are whole minutes at or above the browser-enforced one-minute
|
||||||
|
// minimum, so nothing here is silently clamped to a slower cadence.
|
||||||
|
//
|
||||||
|
// Trap for anyone changing a period: each job also carries a freshness guard
|
||||||
|
// that can veto its own scheduled tick. A guard timed to the alarm period
|
||||||
|
// halves the real cadence, because the guard is measured from when the last
|
||||||
|
// run finished and the alarm fires one run-duration earlier than that. Every
|
||||||
|
// guard must therefore either be strictly shorter than the period it gates or
|
||||||
|
// be bypassed on the scheduled tick — see backgroundRefresh() in
|
||||||
|
// src/background/index.js and updatePhishingList() in shared/phishingDomains.js.
|
||||||
|
|
||||||
|
const BALANCE_REFRESH_ALARM = "autistmask-balance-refresh";
|
||||||
|
const PHISHING_REFRESH_ALARM = "autistmask-phishing-refresh";
|
||||||
|
|
||||||
|
const MIN_ALARM_PERIOD_MINUTES = 1;
|
||||||
|
const BALANCE_REFRESH_PERIOD_MINUTES = 1;
|
||||||
|
const PHISHING_REFRESH_PERIOD_MINUTES = 24 * 60;
|
||||||
|
|
||||||
|
// Resolved on use rather than captured at module load: the worker is torn
|
||||||
|
// down and re-evaluated repeatedly, and tests install a stub after requiring
|
||||||
|
// the module.
|
||||||
|
function alarmsApi() {
|
||||||
|
if (typeof browser !== "undefined" && browser.alarms) return browser.alarms;
|
||||||
|
if (typeof chrome !== "undefined" && chrome.alarms) return chrome.alarms;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create an alarm unless one with the requested period already exists.
|
||||||
|
*
|
||||||
|
* The existence check is load-bearing: creating an alarm resets its schedule,
|
||||||
|
* and this runs on every worker wake. Creating unconditionally would push the
|
||||||
|
* next fire time out on every incoming message, so a busy extension would
|
||||||
|
* never see the alarm fire at all.
|
||||||
|
*
|
||||||
|
* The period comparison is equally load-bearing in the other direction: an
|
||||||
|
* alarm created by an older version keeps its old period forever unless a
|
||||||
|
* changed constant re-creates it, so a period edit would never reach an
|
||||||
|
* existing install. Re-creating on a period change happens once and then
|
||||||
|
* settles into the existence check above.
|
||||||
|
*
|
||||||
|
* @param {string} name
|
||||||
|
* @param {number} periodInMinutes
|
||||||
|
* @returns {Promise<boolean>} true if the alarm was created by this call.
|
||||||
|
*/
|
||||||
|
async function ensureAlarm(name, periodInMinutes) {
|
||||||
|
const api = alarmsApi();
|
||||||
|
if (!api) return false;
|
||||||
|
const period = Math.max(periodInMinutes, MIN_ALARM_PERIOD_MINUTES);
|
||||||
|
const existing = await api.get(name);
|
||||||
|
if (existing && existing.periodInMinutes === period) return false;
|
||||||
|
api.create(name, {
|
||||||
|
periodInMinutes: period,
|
||||||
|
delayInMinutes: period,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure both recurring background jobs are scheduled. Safe to call on every
|
||||||
|
* worker start, on onInstalled and on onStartup.
|
||||||
|
*
|
||||||
|
* @returns {Promise<{balance: boolean, phishing: boolean}>} which alarms this
|
||||||
|
* call had to create.
|
||||||
|
*/
|
||||||
|
async function ensureRecurringAlarms() {
|
||||||
|
const balance = await ensureAlarm(
|
||||||
|
BALANCE_REFRESH_ALARM,
|
||||||
|
BALANCE_REFRESH_PERIOD_MINUTES,
|
||||||
|
);
|
||||||
|
const phishing = await ensureAlarm(
|
||||||
|
PHISHING_REFRESH_ALARM,
|
||||||
|
PHISHING_REFRESH_PERIOD_MINUTES,
|
||||||
|
);
|
||||||
|
return { balance, phishing };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register per-alarm handlers. One listener dispatches by alarm name so the
|
||||||
|
* worker only ever installs a single onAlarm listener.
|
||||||
|
*
|
||||||
|
* @param {Object<string, function>} handlers
|
||||||
|
* @returns {boolean} true if the listener was installed.
|
||||||
|
*/
|
||||||
|
function registerAlarmHandlers(handlers) {
|
||||||
|
const api = alarmsApi();
|
||||||
|
if (!api || !api.onAlarm) return false;
|
||||||
|
api.onAlarm.addListener((alarm) => {
|
||||||
|
const handler = handlers[alarm && alarm.name];
|
||||||
|
if (handler) handler();
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
BALANCE_REFRESH_ALARM,
|
||||||
|
PHISHING_REFRESH_ALARM,
|
||||||
|
MIN_ALARM_PERIOD_MINUTES,
|
||||||
|
BALANCE_REFRESH_PERIOD_MINUTES,
|
||||||
|
PHISHING_REFRESH_PERIOD_MINUTES,
|
||||||
|
ensureAlarm,
|
||||||
|
ensureRecurringAlarms,
|
||||||
|
registerAlarmHandlers,
|
||||||
|
};
|
||||||
@@ -21,6 +21,11 @@
|
|||||||
// from the rebuild and changes the bytes, so the final assertion is that
|
// from the rebuild and changes the bytes, so the final assertion is that
|
||||||
// the artifact *is* the approved transaction, not merely that it is not one
|
// the artifact *is* the approved transaction, not merely that it is not one
|
||||||
// of the tampered shapes that were thought of.
|
// of the tampered shapes that were thought of.
|
||||||
|
// - every comparison runs against the decode, but the string handed to
|
||||||
|
// broadcastTransaction() is the artifact. So the artifact is also required
|
||||||
|
// to be the canonical re-encoding of its own decode, which is what makes
|
||||||
|
// the checked transaction and the broadcast bytes the same object rather
|
||||||
|
// than two things that merely decode alike.
|
||||||
//
|
//
|
||||||
// Every consequential field is compared, and a mismatch is a refusal to act,
|
// Every consequential field is compared, and a mismatch is a refusal to act,
|
||||||
// never a warning: what the user approved is what gets broadcast, or nothing
|
// never a warning: what the user approved is what gets broadcast, or nothing
|
||||||
@@ -291,6 +296,23 @@ function assertNothingUnchecked(parsed) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The other half of the closing check, and the one that makes it bind on the
|
||||||
|
// bytes that actually leave: every comparison above runs against the decode,
|
||||||
|
// so on its own the rebuild proves only that the transaction ethers understood
|
||||||
|
// is the approved one. What the background hands to broadcastTransaction() is
|
||||||
|
// the artifact string itself. Requiring the artifact to be exactly the
|
||||||
|
// canonical re-encoding of its own decode closes the gap between the two —
|
||||||
|
// no encoding the decoder normalizes away (a leading zero byte on an RLP
|
||||||
|
// quantity, say) can differ from what was checked. Hex case is not part of the
|
||||||
|
// encoding, so only that is normalized before comparing.
|
||||||
|
function assertCanonicalBytes(parsed, rawSignedTx) {
|
||||||
|
if (parsed.serialized !== String(rawSignedTx).toLowerCase()) {
|
||||||
|
throw refuse(
|
||||||
|
"The signed transaction is not encoded canonically, so the bytes that would be broadcast are not the bytes that were checked.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Assert that a raw signed transaction is the transaction the user approved,
|
// Assert that a raw signed transaction is the transaction the user approved,
|
||||||
// signed by the address the approval was raised for, on the network that is
|
// signed by the address the approval was raised for, on the network that is
|
||||||
// selected. Returns the parsed ethers Transaction on success, throws
|
// selected. Returns the parsed ethers Transaction on success, throws
|
||||||
@@ -411,6 +433,7 @@ function verifySignedTx(rawSignedTx, txParams, expectedFrom, selectedChainId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assertNothingUnchecked(parsed);
|
assertNothingUnchecked(parsed);
|
||||||
|
assertCanonicalBytes(parsed, rawSignedTx);
|
||||||
|
|
||||||
return parsed;
|
return parsed;
|
||||||
}
|
}
|
||||||
@@ -516,6 +539,7 @@ module.exports = {
|
|||||||
verifySignature,
|
verifySignature,
|
||||||
assertNoForbiddenFields,
|
assertNoForbiddenFields,
|
||||||
assertNothingUnchecked,
|
assertNothingUnchecked,
|
||||||
|
assertCanonicalBytes,
|
||||||
sameAddress,
|
sameAddress,
|
||||||
failureIsRetryable,
|
failureIsRetryable,
|
||||||
describeTxFailure,
|
describeTxFailure,
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
// Cached ENS reverse resolution.
|
// Cached ENS reverse resolution.
|
||||||
// Resolves addresses to ENS names via ethers provider.lookupAddress(),
|
// Resolves addresses to ENS names via ethers provider.lookupAddress(),
|
||||||
// caching results in localStorage with a 12-hour TTL.
|
// caching results in localStorage with a 12-hour TTL.
|
||||||
|
//
|
||||||
|
// POPUP ONLY. localStorage does not exist in the Chrome MV3 service worker,
|
||||||
|
// so this module must not be pulled into src/background/. Anything the
|
||||||
|
// background context needs to cache goes in extension storage instead (see
|
||||||
|
// shared/phishingDomains.js).
|
||||||
|
|
||||||
const { getProvider } = require("./balances");
|
const { getProvider } = require("./balances");
|
||||||
const { log } = require("./log");
|
const { log } = require("./log");
|
||||||
|
|||||||
@@ -8,8 +8,14 @@
|
|||||||
// The domain-checker checks the in-memory delta first (fresh/recent scam
|
// The domain-checker checks the in-memory delta first (fresh/recent scam
|
||||||
// sites), then falls back to the vendored list.
|
// sites), then falls back to the vendored list.
|
||||||
//
|
//
|
||||||
// If the delta is under 256 KiB it is persisted to localStorage so it
|
// If the delta and its fetch timestamp fit in 256 KiB they are persisted to
|
||||||
// survives extension/service-worker restarts.
|
// extension storage, so they survive termination of the MV3 service worker.
|
||||||
|
// Extension storage, not localStorage: localStorage does not exist in a
|
||||||
|
// service worker, so the previous persistence never ran on Chrome at all.
|
||||||
|
// The stored timestamps are what keep a restarted worker from re-fetching on
|
||||||
|
// every wake while still noticing an overdue update. Those guards apply to the
|
||||||
|
// startup path only; the 24-hour alarm tick bypasses them, or it would veto
|
||||||
|
// its own refresh — see updatePhishingList().
|
||||||
|
|
||||||
const vendoredConfig = require("./phishingBlocklist.json");
|
const vendoredConfig = require("./phishingBlocklist.json");
|
||||||
|
|
||||||
@@ -17,7 +23,14 @@ const BLOCKLIST_URL =
|
|||||||
"https://raw.githubusercontent.com/MetaMask/eth-phishing-detect/main/src/config.json";
|
"https://raw.githubusercontent.com/MetaMask/eth-phishing-detect/main/src/config.json";
|
||||||
|
|
||||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||||
const REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
||||||
|
// Floor on how often an unscheduled path may hit the network. The worker is
|
||||||
|
// revived every ~30 seconds while the browser is busy, and every revival runs
|
||||||
|
// the startup path; without a persisted record of the last attempt, any state
|
||||||
|
// that leaves lastFetchTime unset — a fetch that failed, or a delta too large
|
||||||
|
// to store — would download the full list on every single wake.
|
||||||
|
const MIN_FETCH_ATTEMPT_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
|
||||||
|
|
||||||
const DELTA_STORAGE_KEY = "phishing-delta";
|
const DELTA_STORAGE_KEY = "phishing-delta";
|
||||||
const MAX_DELTA_BYTES = 256 * 1024; // 256 KiB
|
const MAX_DELTA_BYTES = 256 * 1024; // 256 KiB
|
||||||
|
|
||||||
@@ -29,45 +42,104 @@ const vendoredBlacklist = new Set(
|
|||||||
// Delta set — only entries from live list that are NOT in vendored.
|
// Delta set — only entries from live list that are NOT in vendored.
|
||||||
let deltaBlacklist = new Set();
|
let deltaBlacklist = new Set();
|
||||||
let lastFetchTime = 0;
|
let lastFetchTime = 0;
|
||||||
|
let lastAttemptTime = 0;
|
||||||
let fetchPromise = null;
|
let fetchPromise = null;
|
||||||
let refreshTimer = null;
|
let loadPromise = null;
|
||||||
|
|
||||||
|
// Resolved on use rather than captured at module load, so a test can install
|
||||||
|
// a stub after requiring the module and so the popup — which has no reason to
|
||||||
|
// touch the delta — does not fail to load where the API is absent.
|
||||||
|
function storageApi() {
|
||||||
|
if (typeof browser !== "undefined" && browser.storage) {
|
||||||
|
return browser.storage.local;
|
||||||
|
}
|
||||||
|
if (typeof chrome !== "undefined" && chrome.storage) {
|
||||||
|
return chrome.storage.local;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load delta entries from localStorage on startup.
|
* Sanitise a timestamp read back from storage.
|
||||||
* Called once during module initialization in the background script.
|
*
|
||||||
|
* A value in the future is permanent poison: every guard here measures elapsed
|
||||||
|
* time as `Date.now() - stamp` and tests only the lower bound, so a stamp a
|
||||||
|
* year ahead suppresses updates for a year with no path that ever clears it.
|
||||||
|
* Clock skew and a restored profile backup both produce one. Since these
|
||||||
|
* timestamps only ever gate work, discarding an impossible one is safe: it
|
||||||
|
* costs at most a single extra fetch and restores a sane value immediately.
|
||||||
|
*
|
||||||
|
* @param {unknown} value
|
||||||
|
* @returns {number} the timestamp, or 0 if it is unusable.
|
||||||
*/
|
*/
|
||||||
function loadDeltaFromStorage() {
|
function sanitizeTimestamp(value) {
|
||||||
|
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
|
||||||
|
if (value <= 0 || value > Date.now()) return 0;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the persisted delta and its timestamps from extension storage.
|
||||||
|
* Runs once per worker lifetime; every entry point funnels through
|
||||||
|
* ensureDeltaLoaded() so a wake from termination restores state exactly once.
|
||||||
|
*
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function loadDeltaFromStorage() {
|
||||||
|
const storage = storageApi();
|
||||||
|
if (!storage) return;
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(DELTA_STORAGE_KEY);
|
const result = await storage.get(DELTA_STORAGE_KEY);
|
||||||
if (!raw) return;
|
const data = result && result[DELTA_STORAGE_KEY];
|
||||||
const data = JSON.parse(raw);
|
if (!data) return;
|
||||||
if (data.blacklist && Array.isArray(data.blacklist)) {
|
if (Array.isArray(data.blacklist)) {
|
||||||
deltaBlacklist = new Set(
|
deltaBlacklist = new Set(
|
||||||
data.blacklist.map((d) => d.toLowerCase()),
|
data.blacklist.map((d) => d.toLowerCase()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
lastFetchTime = sanitizeTimestamp(data.lastFetchTime);
|
||||||
|
lastAttemptTime = sanitizeTimestamp(data.lastAttemptTime);
|
||||||
} catch {
|
} catch {
|
||||||
// localStorage unavailable or corrupt — start empty
|
// Storage unavailable or corrupt — start empty and re-fetch.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ensureDeltaLoaded() {
|
||||||
|
if (!loadPromise) loadPromise = loadDeltaFromStorage();
|
||||||
|
return loadPromise;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist delta to localStorage if it fits within MAX_DELTA_BYTES.
|
* Persist the delta and its timestamps if they fit within MAX_DELTA_BYTES.
|
||||||
|
*
|
||||||
|
* The 256 KiB cap covers the delta and its freshness claim: when the delta is
|
||||||
|
* too large to keep, lastFetchTime goes with it, so the next start re-fetches
|
||||||
|
* rather than trusting a freshness claim for a delta it no longer holds.
|
||||||
|
* lastAttemptTime is written either way — it records that the network was
|
||||||
|
* contacted, which stays true whatever became of the response, and it is what
|
||||||
|
* stops a permanently oversized list from downloading on every worker wake.
|
||||||
|
*
|
||||||
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
function saveDeltaToStorage() {
|
async function saveDeltaToStorage() {
|
||||||
|
const storage = storageApi();
|
||||||
|
if (!storage) return;
|
||||||
try {
|
try {
|
||||||
const data = {
|
const data = {
|
||||||
blacklist: Array.from(deltaBlacklist),
|
blacklist: Array.from(deltaBlacklist),
|
||||||
|
lastFetchTime,
|
||||||
|
lastAttemptTime,
|
||||||
};
|
};
|
||||||
const json = JSON.stringify(data);
|
const json = JSON.stringify(data);
|
||||||
if (json.length < MAX_DELTA_BYTES) {
|
if (json.length < MAX_DELTA_BYTES) {
|
||||||
localStorage.setItem(DELTA_STORAGE_KEY, json);
|
await storage.set({ [DELTA_STORAGE_KEY]: data });
|
||||||
|
} else if (lastAttemptTime > 0) {
|
||||||
|
await storage.set({ [DELTA_STORAGE_KEY]: { lastAttemptTime } });
|
||||||
} else {
|
} else {
|
||||||
// Too large — remove stale key if present
|
await storage.remove(DELTA_STORAGE_KEY);
|
||||||
localStorage.removeItem(DELTA_STORAGE_KEY);
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// localStorage unavailable — skip silently
|
// Storage unavailable — skip silently
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +148,7 @@ function saveDeltaToStorage() {
|
|||||||
* Used for both live fetches and testing.
|
* Used for both live fetches and testing.
|
||||||
*
|
*
|
||||||
* @param {{ blacklist?: string[] }} config
|
* @param {{ blacklist?: string[] }} config
|
||||||
|
* @returns {Promise<void>} resolves once the delta has been persisted.
|
||||||
*/
|
*/
|
||||||
function loadConfig(config) {
|
function loadConfig(config) {
|
||||||
const liveBlacklist = (config.blacklist || []).map((d) => d.toLowerCase());
|
const liveBlacklist = (config.blacklist || []).map((d) => d.toLowerCase());
|
||||||
@@ -86,7 +159,7 @@ function loadConfig(config) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
lastFetchTime = Date.now();
|
lastFetchTime = Date.now();
|
||||||
saveDeltaToStorage();
|
return saveDeltaToStorage();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -111,6 +184,11 @@ function hostnameVariants(hostname) {
|
|||||||
* Check if a hostname is on the phishing blocklist.
|
* Check if a hostname is on the phishing blocklist.
|
||||||
* Checks delta first (fresh/recent scam sites), then vendored list.
|
* Checks delta first (fresh/recent scam sites), then vendored list.
|
||||||
*
|
*
|
||||||
|
* Synchronous by design — callers answer an approval prompt with it. On a
|
||||||
|
* worker that has just woken, the persisted delta may still be loading; the
|
||||||
|
* vendored list, which is bundled and always present, carries the check until
|
||||||
|
* it lands.
|
||||||
|
*
|
||||||
* @param {string} hostname - The hostname to check.
|
* @param {string} hostname - The hostname to check.
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
@@ -127,28 +205,59 @@ function isPhishingDomain(hostname) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the latest blocklist and compute delta against vendored data.
|
* Fetch the latest blocklist and compute delta against vendored data.
|
||||||
* De-duplicates concurrent fetches. Results are cached for CACHE_TTL_MS.
|
* De-duplicates concurrent fetches. Results are cached for CACHE_TTL_MS,
|
||||||
|
* counted from the persisted timestamp so the cache outlives the worker.
|
||||||
*
|
*
|
||||||
|
* `force` is what makes the 24-hour alarm actually refresh every 24 hours.
|
||||||
|
* The alarm fires one period after the previous alarm, but lastFetchTime is
|
||||||
|
* stamped when that fetch *completed*, so an unforced tick lands one fetch
|
||||||
|
* latency inside its own TTL, skips, and turns the real cadence into 48 hours.
|
||||||
|
* Shortening the TTL instead would not fix it: the worker wakes every ~30
|
||||||
|
* seconds and the startup path re-checks the TTL each time, so a shortened TTL
|
||||||
|
* simply becomes the real cadence. The TTL is there to stop redundant fetches
|
||||||
|
* on wake, and the scheduled tick is not redundant, so it bypasses it.
|
||||||
|
*
|
||||||
|
* @param {{force?: boolean}} [opts] force: fetch unless one is already in
|
||||||
|
* flight, ignoring both the freshness and the retry guard. For the scheduled
|
||||||
|
* alarm tick only.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async function updatePhishingList() {
|
async function updatePhishingList({ force = false } = {}) {
|
||||||
// Skip if recently fetched
|
// A worker that has just been revived knows nothing until the persisted
|
||||||
if (Date.now() - lastFetchTime < CACHE_TTL_MS && lastFetchTime > 0) {
|
// record is back in memory; without this the freshness check below would
|
||||||
|
// always see 0 and re-fetch on every wake.
|
||||||
|
await ensureDeltaLoaded();
|
||||||
|
|
||||||
|
if (!force) {
|
||||||
|
const now = Date.now();
|
||||||
|
// Skip if recently fetched.
|
||||||
|
if (lastFetchTime > 0 && now - lastFetchTime < CACHE_TTL_MS) return;
|
||||||
|
// Skip if the network was contacted recently and the result was not
|
||||||
|
// usable — a failed fetch or an oversized delta leaves lastFetchTime
|
||||||
|
// unset, and without this every wake would retry.
|
||||||
|
if (
|
||||||
|
lastAttemptTime > 0 &&
|
||||||
|
now - lastAttemptTime < MIN_FETCH_ATTEMPT_INTERVAL_MS
|
||||||
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// De-duplicate concurrent calls
|
// De-duplicate concurrent calls
|
||||||
if (fetchPromise) return fetchPromise;
|
if (fetchPromise) return fetchPromise;
|
||||||
|
|
||||||
fetchPromise = (async () => {
|
fetchPromise = (async () => {
|
||||||
|
lastAttemptTime = Date.now();
|
||||||
try {
|
try {
|
||||||
const resp = await fetch(BLOCKLIST_URL);
|
const resp = await fetch(BLOCKLIST_URL);
|
||||||
if (!resp.ok) throw new Error("HTTP " + resp.status);
|
if (!resp.ok) throw new Error("HTTP " + resp.status);
|
||||||
const config = await resp.json();
|
const config = await resp.json();
|
||||||
loadConfig(config);
|
await loadConfig(config);
|
||||||
} catch {
|
} catch {
|
||||||
// Silently fail — vendored list still provides coverage.
|
// Silently fail — vendored list still provides coverage. Persist
|
||||||
// We'll retry next time.
|
// the attempt so a persistently failing fetch is retried on the
|
||||||
|
// schedule rather than on every wake.
|
||||||
|
await saveDeltaToStorage();
|
||||||
} finally {
|
} finally {
|
||||||
fetchPromise = null;
|
fetchPromise = null;
|
||||||
}
|
}
|
||||||
@@ -158,12 +267,29 @@ async function updatePhishingList() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start periodic refresh of the phishing list.
|
* Restore persisted state and fetch if the list is overdue.
|
||||||
* Should be called once from the background script on startup.
|
*
|
||||||
|
* Called from the background script every time it starts — a fresh install,
|
||||||
|
* a browser start, and every revival of a terminated service worker all land
|
||||||
|
* here. The recurring 24-hour schedule itself is an alarm (see
|
||||||
|
* shared/alarms.js), not a timer, because timers die with the worker.
|
||||||
|
*
|
||||||
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
function startPeriodicRefresh() {
|
async function initPhishingList() {
|
||||||
if (refreshTimer) return;
|
await ensureDeltaLoaded();
|
||||||
refreshTimer = setInterval(updatePhishingList, REFRESH_INTERVAL_MS);
|
return updatePhishingList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 24-hour alarm tick. Separate from initPhishingList() because this is the
|
||||||
|
* scheduled refresh and must not be vetoed by the guards that exist to keep
|
||||||
|
* the unscheduled startup path off the network.
|
||||||
|
*
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function refreshPhishingListOnSchedule() {
|
||||||
|
return updatePhishingList({ force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -190,21 +316,22 @@ function getDeltaSize() {
|
|||||||
function _reset() {
|
function _reset() {
|
||||||
deltaBlacklist = new Set();
|
deltaBlacklist = new Set();
|
||||||
lastFetchTime = 0;
|
lastFetchTime = 0;
|
||||||
|
lastAttemptTime = 0;
|
||||||
fetchPromise = null;
|
fetchPromise = null;
|
||||||
if (refreshTimer) {
|
loadPromise = null;
|
||||||
clearInterval(refreshTimer);
|
|
||||||
refreshTimer = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load persisted delta on module initialization
|
|
||||||
loadDeltaFromStorage();
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
isPhishingDomain,
|
isPhishingDomain,
|
||||||
updatePhishingList,
|
updatePhishingList,
|
||||||
startPeriodicRefresh,
|
refreshPhishingListOnSchedule,
|
||||||
|
initPhishingList,
|
||||||
|
loadDeltaFromStorage,
|
||||||
loadConfig,
|
loadConfig,
|
||||||
|
CACHE_TTL_MS,
|
||||||
|
MIN_FETCH_ATTEMPT_INTERVAL_MS,
|
||||||
|
DELTA_STORAGE_KEY,
|
||||||
|
MAX_DELTA_BYTES,
|
||||||
getBlocklistSize,
|
getBlocklistSize,
|
||||||
getDeltaSize,
|
getDeltaSize,
|
||||||
hostnameVariants,
|
hostnameVariants,
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const DEFAULT_STATE = {
|
|||||||
deniedSites: {},
|
deniedSites: {},
|
||||||
rememberSiteChoice: true,
|
rememberSiteChoice: true,
|
||||||
showZeroBalanceTokens: true,
|
showZeroBalanceTokens: true,
|
||||||
|
hideSpoofedSymbols: true,
|
||||||
hideLowHolderTokens: true,
|
hideLowHolderTokens: true,
|
||||||
hideFraudContracts: true,
|
hideFraudContracts: true,
|
||||||
hideDustTransactions: true,
|
hideDustTransactions: true,
|
||||||
@@ -61,6 +62,7 @@ async function saveState() {
|
|||||||
deniedSites: state.deniedSites,
|
deniedSites: state.deniedSites,
|
||||||
rememberSiteChoice: state.rememberSiteChoice,
|
rememberSiteChoice: state.rememberSiteChoice,
|
||||||
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
||||||
|
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
hideLowHolderTokens: state.hideLowHolderTokens,
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
hideFraudContracts: state.hideFraudContracts,
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
hideDustTransactions: state.hideDustTransactions,
|
||||||
@@ -112,6 +114,12 @@ async function loadState() {
|
|||||||
saved.showZeroBalanceTokens !== undefined
|
saved.showZeroBalanceTokens !== undefined
|
||||||
? saved.showZeroBalanceTokens
|
? saved.showZeroBalanceTokens
|
||||||
: true;
|
: true;
|
||||||
|
// A profile written before this setting existed has no key for it.
|
||||||
|
// It is a safety filter, so absent must load as on, not as undefined.
|
||||||
|
state.hideSpoofedSymbols =
|
||||||
|
saved.hideSpoofedSymbols !== undefined
|
||||||
|
? saved.hideSpoofedSymbols
|
||||||
|
: true;
|
||||||
state.hideLowHolderTokens =
|
state.hideLowHolderTokens =
|
||||||
saved.hideLowHolderTokens !== undefined
|
saved.hideLowHolderTokens !== undefined
|
||||||
? saved.hideLowHolderTokens
|
? saved.hideLowHolderTokens
|
||||||
|
|||||||
@@ -10,6 +10,14 @@ const { formatEther, formatUnits } = require("ethers");
|
|||||||
const { log, debugFetch } = require("./log");
|
const { log, debugFetch } = require("./log");
|
||||||
const { KNOWN_SYMBOLS, TOKEN_BY_ADDRESS } = require("./tokenList");
|
const { KNOWN_SYMBOLS, TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||||
|
|
||||||
|
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
||||||
|
// over the address, not part of its identity. Every address comparison in
|
||||||
|
// this file goes through this helper, so an address arriving in checksummed
|
||||||
|
// or upper-case form can never be read as a different address.
|
||||||
|
function normalizeAddress(addr) {
|
||||||
|
return (addr || "").toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
function formatTxValue(val) {
|
function formatTxValue(val) {
|
||||||
const parts = val.split(".");
|
const parts = val.split(".");
|
||||||
if (parts.length === 1) return val + ".0000";
|
if (parts.length === 1) return val + ".0000";
|
||||||
@@ -30,10 +38,10 @@ function parseTx(tx, addrLower) {
|
|||||||
let exactValue = formatEther(rawWei);
|
let exactValue = formatEther(rawWei);
|
||||||
let rawAmount = rawWei;
|
let rawAmount = rawWei;
|
||||||
let rawUnit = "wei";
|
let rawUnit = "wei";
|
||||||
let direction = from.toLowerCase() === addrLower ? "sent" : "received";
|
let direction = normalizeAddress(from) === addrLower ? "sent" : "received";
|
||||||
let directionLabel = direction === "sent" ? "Sent" : "Received";
|
let directionLabel = direction === "sent" ? "Sent" : "Received";
|
||||||
if (toIsContract && method && method !== "transfer") {
|
if (toIsContract && method && method !== "transfer") {
|
||||||
const token = TOKEN_BY_ADDRESS.get(to.toLowerCase());
|
const token = TOKEN_BY_ADDRESS.get(normalizeAddress(to));
|
||||||
if (token) {
|
if (token) {
|
||||||
symbol = token.symbol;
|
symbol = token.symbol;
|
||||||
}
|
}
|
||||||
@@ -87,7 +95,8 @@ function parseTokenTransfer(tt, addrLower) {
|
|||||||
const to = tt.to?.hash || "";
|
const to = tt.to?.hash || "";
|
||||||
const decimals = parseInt(tt.total?.decimals || "18", 10);
|
const decimals = parseInt(tt.total?.decimals || "18", 10);
|
||||||
const rawVal = tt.total?.value || "0";
|
const rawVal = tt.total?.value || "0";
|
||||||
const direction = from.toLowerCase() === addrLower ? "sent" : "received";
|
const direction =
|
||||||
|
normalizeAddress(from) === addrLower ? "sent" : "received";
|
||||||
const sym = tt.token?.symbol || "?";
|
const sym = tt.token?.symbol || "?";
|
||||||
return {
|
return {
|
||||||
hash: tt.transaction_hash,
|
hash: tt.transaction_hash,
|
||||||
@@ -104,11 +113,9 @@ function parseTokenTransfer(tt, addrLower) {
|
|||||||
direction: direction,
|
direction: direction,
|
||||||
directionLabel: direction === "sent" ? "Sent" : "Received",
|
directionLabel: direction === "sent" ? "Sent" : "Received",
|
||||||
isError: false,
|
isError: false,
|
||||||
contractAddress: (
|
contractAddress: normalizeAddress(
|
||||||
tt.token?.address_hash ||
|
tt.token?.address_hash || tt.token?.address || "",
|
||||||
tt.token?.address ||
|
),
|
||||||
""
|
|
||||||
).toLowerCase(),
|
|
||||||
holders: parseInt(tt.token?.holders_count || "0", 10),
|
holders: parseInt(tt.token?.holders_count || "0", 10),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -194,7 +201,7 @@ function mergeTransactions(txs, tokenTransfers) {
|
|||||||
|
|
||||||
async function fetchRecentTransactions(address, blockscoutUrl, count = 25) {
|
async function fetchRecentTransactions(address, blockscoutUrl, count = 25) {
|
||||||
log.debugf("fetchRecentTransactions", address);
|
log.debugf("fetchRecentTransactions", address);
|
||||||
const addrLower = address.toLowerCase();
|
const addrLower = normalizeAddress(address);
|
||||||
|
|
||||||
const [txResp, ttResp] = await Promise.all([
|
const [txResp, ttResp] = await Promise.all([
|
||||||
debugFetch(blockscoutUrl + "/addresses/" + address + "/transactions"),
|
debugFetch(blockscoutUrl + "/addresses/" + address + "/transactions"),
|
||||||
@@ -243,34 +250,45 @@ function isSpoofedSymbol(tx) {
|
|||||||
if (!KNOWN_SYMBOLS.has(symbol)) return false;
|
if (!KNOWN_SYMBOLS.has(symbol)) return false;
|
||||||
const legit = KNOWN_SYMBOLS.get(symbol);
|
const legit = KNOWN_SYMBOLS.get(symbol);
|
||||||
if (legit === null) return true; // "ETH" as ERC-20 is always fake
|
if (legit === null) return true; // "ETH" as ERC-20 is always fake
|
||||||
return tx.contractAddress !== legit;
|
return normalizeAddress(tx.contractAddress) !== normalizeAddress(legit);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pure filter function. Takes raw transactions and filter settings,
|
// Pure filter function. Takes raw transactions and filter settings,
|
||||||
// returns { transactions, newFraudContracts }.
|
// returns { transactions, newFraudContracts }.
|
||||||
function filterTransactions(txs, filters = {}) {
|
function filterTransactions(txs, filters = {}) {
|
||||||
const fraudSet = new Set(
|
const fraudSet = new Set(
|
||||||
(filters.fraudContracts || []).map((a) => a.toLowerCase()),
|
(filters.fraudContracts || []).map(normalizeAddress),
|
||||||
);
|
);
|
||||||
|
// The dust threshold defaults only when it is unset (nullish): a
|
||||||
|
// threshold of 0 is a real value meaning "hide nothing", since no
|
||||||
|
// transaction has a value below 0 gwei. It is therefore equivalent to
|
||||||
|
// clearing the hide-dust checkbox, and the two controls cannot override
|
||||||
|
// each other in either direction.
|
||||||
|
const dustThresholdGwei = filters.dustThresholdGwei ?? 100000;
|
||||||
const newFraud = [];
|
const newFraud = [];
|
||||||
const filtered = [];
|
const filtered = [];
|
||||||
|
// Fail-safe, unlike the three flags below: this one is off only when the
|
||||||
|
// caller says so explicitly, so a caller that omits the key keeps the
|
||||||
|
// check rather than silently losing it. The setting also governs the
|
||||||
|
// blocklist learning below, which exists only to serve this check —
|
||||||
|
// leaving learning on while the check is off would re-hide the very rows
|
||||||
|
// the user asked to see, through the fraud-contract rule.
|
||||||
|
const hideSpoofed = filters.hideSpoofedSymbols !== false;
|
||||||
|
|
||||||
for (const tx of txs) {
|
for (const tx of txs) {
|
||||||
// Always filter spoofed known symbols and record the fraud contract
|
const contract = normalizeAddress(tx.contractAddress);
|
||||||
if (isSpoofedSymbol(tx)) {
|
|
||||||
if (tx.contractAddress && !fraudSet.has(tx.contractAddress)) {
|
// Filter spoofed known symbols and record the fraud contract
|
||||||
fraudSet.add(tx.contractAddress);
|
if (hideSpoofed && isSpoofedSymbol(tx)) {
|
||||||
newFraud.push(tx.contractAddress);
|
if (contract && !fraudSet.has(contract)) {
|
||||||
|
fraudSet.add(contract);
|
||||||
|
newFraud.push(contract);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter fraud contracts if setting is on
|
// Filter fraud contracts if setting is on
|
||||||
if (
|
if (filters.hideFraudContracts && contract && fraudSet.has(contract)) {
|
||||||
filters.hideFraudContracts &&
|
|
||||||
tx.contractAddress &&
|
|
||||||
fraudSet.has(tx.contractAddress)
|
|
||||||
) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,7 +309,7 @@ function filterTransactions(txs, filters = {}) {
|
|||||||
filters.hideDustTransactions &&
|
filters.hideDustTransactions &&
|
||||||
!tx.isContractCall &&
|
!tx.isContractCall &&
|
||||||
tx.valueGwei !== null &&
|
tx.valueGwei !== null &&
|
||||||
tx.valueGwei < (filters.dustThresholdGwei || 100000)
|
tx.valueGwei < dustThresholdGwei
|
||||||
) {
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
171
src/shared/txValidation.js
Normal file
171
src/shared/txValidation.js
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
// Balance arithmetic for the transaction confirmation screen.
|
||||||
|
//
|
||||||
|
// Pure: no DOM, no network, no state. Everything is exact integer math on
|
||||||
|
// 18-decimal fixed point (wei for ETH), so it can be unit tested directly
|
||||||
|
// instead of through the confirmation view. The caller maps the returned
|
||||||
|
// codes to the reserved message elements on the screen.
|
||||||
|
//
|
||||||
|
// Human decimal strings ("1.25") are scaled to 18 decimals for comparison.
|
||||||
|
// That scale is independent of a token's own decimals: both the amount and
|
||||||
|
// the token balance arrive as human decimal strings, so comparing them at a
|
||||||
|
// common scale is exact.
|
||||||
|
|
||||||
|
const { parseUnits } = require("ethers");
|
||||||
|
|
||||||
|
const SCALE_DECIMALS = 18;
|
||||||
|
|
||||||
|
// Whether the asynchronous fee estimate has arrived yet.
|
||||||
|
const FEE_PENDING = "pending";
|
||||||
|
const FEE_KNOWN = "known";
|
||||||
|
const FEE_UNAVAILABLE = "unavailable";
|
||||||
|
|
||||||
|
const CODES = {
|
||||||
|
// The amount is not a non-negative number we can do exact arithmetic on.
|
||||||
|
AMOUNT_INVALID: "amount-invalid",
|
||||||
|
// ERC-20: the token amount exceeds the token balance.
|
||||||
|
INSUFFICIENT_TOKEN: "insufficient-token",
|
||||||
|
// ETH: the amount alone already exceeds the ETH balance.
|
||||||
|
INSUFFICIENT_ETH: "insufficient-eth",
|
||||||
|
// ETH: the amount fits, the amount plus the network fee does not.
|
||||||
|
INSUFFICIENT_ETH_WITH_FEE: "insufficient-eth-with-fee",
|
||||||
|
// ERC-20: the token balance covers the transfer, the ETH balance does
|
||||||
|
// not cover the network fee it costs.
|
||||||
|
INSUFFICIENT_ETH_FOR_FEE: "insufficient-eth-for-fee",
|
||||||
|
// The fee estimate has not arrived yet.
|
||||||
|
FEE_PENDING: "fee-pending",
|
||||||
|
// The fee estimate failed. Unknown is never treated as zero.
|
||||||
|
FEE_UNAVAILABLE: "fee-unavailable",
|
||||||
|
};
|
||||||
|
|
||||||
|
// The fee that must be reserved for a transaction, in wei: the amount the
|
||||||
|
// node will require, not the amount the transaction is expected to cost.
|
||||||
|
//
|
||||||
|
// A send that pins no fee fields is populated by ethers as a type-2
|
||||||
|
// (EIP-1559) transaction, and a node validates that against
|
||||||
|
// `value + gasLimit * maxFeePerGas`. ethers derives maxFeePerGas as
|
||||||
|
// `baseFeePerGas * 2 + maxPriorityFeePerGas`, so reserving `gasPrice`
|
||||||
|
// (roughly `baseFee + tip`) under-reserves by about `gasLimit * baseFee` and
|
||||||
|
// lets through a transaction the node then rejects with "insufficient funds
|
||||||
|
// for gas * price + value". gasPrice is the fallback only for a network that
|
||||||
|
// offers no type-2 pricing at all.
|
||||||
|
//
|
||||||
|
// Returns null when no usable price is available, which the caller must treat
|
||||||
|
// as a failed estimate rather than as a free transaction.
|
||||||
|
function feeReserveWei(gasLimit, feeData) {
|
||||||
|
if (typeof gasLimit !== "bigint" || gasLimit < 0n) return null;
|
||||||
|
const price = feeData?.maxFeePerGas ?? feeData?.gasPrice;
|
||||||
|
if (typeof price !== "bigint" || price < 0n) return null;
|
||||||
|
return gasLimit * price;
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the transaction is expected to actually cost, in wei — not what must
|
||||||
|
// be reserved for it. A type-2 transaction is charged `baseFee + tip` per gas
|
||||||
|
// and refunded the rest of the cap, and `eth_gasPrice` reports roughly that,
|
||||||
|
// so gasPrice is the estimate and maxFeePerGas is the reserve. On a network
|
||||||
|
// with no type-2 pricing the two are the same number.
|
||||||
|
//
|
||||||
|
// Display only: nothing gates on this. Returns null on the same unusable
|
||||||
|
// inputs as feeReserveWei().
|
||||||
|
function feeEstimateWei(gasLimit, feeData) {
|
||||||
|
if (typeof gasLimit !== "bigint" || gasLimit < 0n) return null;
|
||||||
|
const price = feeData?.gasPrice ?? feeData?.maxFeePerGas;
|
||||||
|
if (typeof price !== "bigint" || price < 0n) return null;
|
||||||
|
return gasLimit * price;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scale a human decimal string to 18-decimal fixed point. Returns null when
|
||||||
|
// the value is not a decimal number or carries more precision than the scale
|
||||||
|
// can hold, which the caller must treat as unusable rather than as zero.
|
||||||
|
function toFixedPoint(value) {
|
||||||
|
if (typeof value !== "string" && typeof value !== "number") return null;
|
||||||
|
const text = String(value).trim();
|
||||||
|
if (text === "") return null;
|
||||||
|
try {
|
||||||
|
return parseUnits(text, SCALE_DECIMALS);
|
||||||
|
} catch (e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate a pending transfer against the balances that must cover it.
|
||||||
|
//
|
||||||
|
// isErc20 — token transfer rather than a native ETH transfer
|
||||||
|
// amount — human decimal string being sent, non-negative. Anything
|
||||||
|
// else, a negative value included, is an unusable amount
|
||||||
|
// rather than an amount that passes every comparison.
|
||||||
|
// ethBalance — human decimal string, the sender's ETH balance
|
||||||
|
// tokenBalance — human decimal string, the sender's token balance
|
||||||
|
// feeStatus — FEE_PENDING, FEE_KNOWN or FEE_UNAVAILABLE. Anything else
|
||||||
|
// is treated as FEE_UNAVAILABLE.
|
||||||
|
// feeWei — the fee reserve in wei from feeReserveWei(), as a
|
||||||
|
// non-negative bigint, when FEE_KNOWN. Any other value makes
|
||||||
|
// the fee unavailable rather than zero.
|
||||||
|
//
|
||||||
|
// Returns { canSend, codes }. Every code blocks sending: canSend is true
|
||||||
|
// only when nothing was found.
|
||||||
|
function validateTransfer({
|
||||||
|
isErc20 = false,
|
||||||
|
amount,
|
||||||
|
ethBalance,
|
||||||
|
tokenBalance,
|
||||||
|
feeStatus = FEE_PENDING,
|
||||||
|
feeWei = null,
|
||||||
|
} = {}) {
|
||||||
|
const codes = [];
|
||||||
|
|
||||||
|
const amountFp = toFixedPoint(amount);
|
||||||
|
const ethFp = toFixedPoint(ethBalance) ?? 0n;
|
||||||
|
|
||||||
|
// A negative amount parses to a valid bigint, so every comparison below
|
||||||
|
// is trivially false and the send clears the screen — then dies at encode
|
||||||
|
// time in parseEther(). Unusable, on the same footing as a malformed fee.
|
||||||
|
if (amountFp === null || amountFp < 0n) {
|
||||||
|
codes.push(CODES.AMOUNT_INVALID);
|
||||||
|
return { canSend: false, codes };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fail closed. Anything that is not a usable fee under a recognised
|
||||||
|
// status — a malformed feeWei, or a status this module does not know —
|
||||||
|
// is an unavailable estimate, never a fee of zero. Every such input errs
|
||||||
|
// in the direction that lets money out, so none of them is trusted.
|
||||||
|
const known =
|
||||||
|
feeStatus === FEE_KNOWN && typeof feeWei === "bigint" && feeWei >= 0n;
|
||||||
|
let status = feeStatus;
|
||||||
|
if (feeStatus === FEE_KNOWN && !known) status = FEE_UNAVAILABLE;
|
||||||
|
if (status !== FEE_KNOWN && status !== FEE_PENDING) {
|
||||||
|
status = FEE_UNAVAILABLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const feeFp = known ? feeWei : null;
|
||||||
|
|
||||||
|
if (isErc20) {
|
||||||
|
const tokenFp = toFixedPoint(tokenBalance) ?? 0n;
|
||||||
|
if (amountFp > tokenFp) codes.push(CODES.INSUFFICIENT_TOKEN);
|
||||||
|
if (feeFp !== null && feeFp > ethFp) {
|
||||||
|
codes.push(CODES.INSUFFICIENT_ETH_FOR_FEE);
|
||||||
|
}
|
||||||
|
} else if (amountFp > ethFp) {
|
||||||
|
codes.push(CODES.INSUFFICIENT_ETH);
|
||||||
|
} else if (feeFp !== null && amountFp + feeFp > ethFp) {
|
||||||
|
codes.push(CODES.INSUFFICIENT_ETH_WITH_FEE);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An unknown fee is never assumed to be zero: sending stays blocked
|
||||||
|
// until the estimate arrives, and stays blocked if it never does.
|
||||||
|
if (status === FEE_PENDING) codes.push(CODES.FEE_PENDING);
|
||||||
|
if (status === FEE_UNAVAILABLE) codes.push(CODES.FEE_UNAVAILABLE);
|
||||||
|
|
||||||
|
return { canSend: codes.length === 0, codes };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
CODES,
|
||||||
|
FEE_PENDING,
|
||||||
|
FEE_KNOWN,
|
||||||
|
FEE_UNAVAILABLE,
|
||||||
|
SCALE_DECIMALS,
|
||||||
|
feeReserveWei,
|
||||||
|
feeEstimateWei,
|
||||||
|
toFixedPoint,
|
||||||
|
validateTransfer,
|
||||||
|
};
|
||||||
@@ -16,8 +16,60 @@ function generateMnemonic() {
|
|||||||
return m.phrase;
|
return m.phrase;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Every extended key (xprv or xpub) entering the app goes through this.
|
||||||
|
//
|
||||||
|
// ethers' HDNodeWallet.fromExtendedKey does NOT verify the base58 checksum
|
||||||
|
// when the decoded payload is the usual 82 bytes, which is exactly the case
|
||||||
|
// the checksum exists to catch: a key with a one-character typo parses into a
|
||||||
|
// *different* wallet instead of being rejected. Re-encoding the parsed node
|
||||||
|
// reproduces a well-formed key byte for byte, checksum included, so comparing
|
||||||
|
// the round trip against the input rejects any altered character. Measured by
|
||||||
|
// the sweep in tests/wallet.test.js over every single-character substitution
|
||||||
|
// of the BIP-32 vector 1 master key: 199 parse without the round-trip
|
||||||
|
// comparison, 0 with it.
|
||||||
|
//
|
||||||
|
// Returns the parsed node, or null if the key is not a well-formed extended
|
||||||
|
// key. Callers turn null into a user-facing error; none of them may fall back
|
||||||
|
// to fromExtendedKey directly.
|
||||||
|
function parseExtendedKey(key) {
|
||||||
|
if (typeof key !== "string") return null;
|
||||||
|
try {
|
||||||
|
const node = HDNodeWallet.fromExtendedKey(key);
|
||||||
|
return node.extendedKey === key ? node : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A master key is at depth 0. Only from there is BIP44_ETH_PATH the absolute
|
||||||
|
// path it names; deriving it under an account-level or child key yields
|
||||||
|
// addresses that correspond to nothing the user holds.
|
||||||
|
const MASTER_DEPTH = 0;
|
||||||
|
|
||||||
|
// Parse an extended private key that the BIP-44 Ethereum account path can be
|
||||||
|
// derived from, or throw. Both callers derive BIP44_ETH_PATH from the result.
|
||||||
|
function masterXprvOrThrow(key) {
|
||||||
|
const node = parseExtendedKey(key);
|
||||||
|
if (!node) {
|
||||||
|
throw new Error("Not a valid extended private key (xprv).");
|
||||||
|
}
|
||||||
|
if (!node.privateKey) {
|
||||||
|
throw new Error("Not an extended private key (xprv).");
|
||||||
|
}
|
||||||
|
if (node.depth !== MASTER_DEPTH) {
|
||||||
|
throw new Error(
|
||||||
|
"Not a master extended private key (xprv): an account-level or " +
|
||||||
|
"child key cannot be imported.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
function deriveAddressFromXpub(xpub, index) {
|
function deriveAddressFromXpub(xpub, index) {
|
||||||
const node = HDNodeWallet.fromExtendedKey(xpub);
|
const node = parseExtendedKey(xpub);
|
||||||
|
if (!node) {
|
||||||
|
throw new Error("Not a valid extended key.");
|
||||||
|
}
|
||||||
return node.deriveChild(index).address;
|
return node.deriveChild(index).address;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,23 +81,28 @@ function hdWalletFromMnemonic(mnemonic) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hdWalletFromXprv(xprv) {
|
function hdWalletFromXprv(xprv) {
|
||||||
const root = HDNodeWallet.fromExtendedKey(xprv);
|
// BIP44_ETH_PATH is absolute ("m/..."), which ethers will only derive from
|
||||||
if (!root.privateKey) {
|
// a depth-0 node. The relative form this used to derive would have been
|
||||||
throw new Error("Not an extended private key (xprv).");
|
// applied *beneath* an account-level key instead of being refused.
|
||||||
}
|
const node = masterXprvOrThrow(xprv).derivePath(BIP44_ETH_PATH);
|
||||||
const node = root.derivePath("44'/60'/0'/0");
|
|
||||||
const xpub = node.neuter().extendedKey;
|
const xpub = node.neuter().extendedKey;
|
||||||
const firstAddress = node.deriveChild(0).address;
|
const firstAddress = node.deriveChild(0).address;
|
||||||
return { xpub, firstAddress };
|
return { xpub, firstAddress };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Well-formed extended private key. Says nothing about depth: the import view
|
||||||
|
// reports a non-master key separately, since "check it for a typo" is the
|
||||||
|
// wrong advice for a key the user copied correctly.
|
||||||
function isValidXprv(key) {
|
function isValidXprv(key) {
|
||||||
try {
|
const node = parseExtendedKey(key);
|
||||||
const node = HDNodeWallet.fromExtendedKey(key);
|
return !!(node && node.privateKey);
|
||||||
return !!node.privateKey;
|
}
|
||||||
} catch {
|
|
||||||
return false;
|
// Whether an extended key is a master key, i.e. the one BIP44_ETH_PATH can be
|
||||||
}
|
// derived from. False for anything parseExtendedKey rejects.
|
||||||
|
function isMasterExtendedKey(key) {
|
||||||
|
const node = parseExtendedKey(key);
|
||||||
|
return !!node && node.depth === MASTER_DEPTH;
|
||||||
}
|
}
|
||||||
|
|
||||||
function addressFromPrivateKey(key) {
|
function addressFromPrivateKey(key) {
|
||||||
@@ -63,8 +120,8 @@ function getSignerForAddress(walletData, addrIndex, decryptedSecret) {
|
|||||||
return node.deriveChild(addrIndex);
|
return node.deriveChild(addrIndex);
|
||||||
}
|
}
|
||||||
if (walletData.type === "xprv") {
|
if (walletData.type === "xprv") {
|
||||||
const root = HDNodeWallet.fromExtendedKey(decryptedSecret);
|
const node =
|
||||||
const node = root.derivePath("44'/60'/0'/0");
|
masterXprvOrThrow(decryptedSecret).derivePath(BIP44_ETH_PATH);
|
||||||
return node.deriveChild(addrIndex);
|
return node.deriveChild(addrIndex);
|
||||||
}
|
}
|
||||||
return new Wallet(decryptedSecret);
|
return new Wallet(decryptedSecret);
|
||||||
@@ -74,13 +131,24 @@ function isValidMnemonic(mnemonic) {
|
|||||||
return Mnemonic.isValidMnemonic(mnemonic);
|
return Mnemonic.isValidMnemonic(mnemonic);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only an HD wallet has a recovery phrase. 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 ever be offered the phrase display.
|
||||||
|
// Written as an allowlist on purpose: a wallet type added later is excluded
|
||||||
|
// until someone decides otherwise.
|
||||||
|
function walletHasRecoveryPhrase(walletData) {
|
||||||
|
return !!walletData && walletData.type === "hd";
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
generateMnemonic,
|
generateMnemonic,
|
||||||
deriveAddressFromXpub,
|
deriveAddressFromXpub,
|
||||||
hdWalletFromMnemonic,
|
hdWalletFromMnemonic,
|
||||||
hdWalletFromXprv,
|
hdWalletFromXprv,
|
||||||
isValidXprv,
|
isValidXprv,
|
||||||
|
isMasterExtendedKey,
|
||||||
addressFromPrivateKey,
|
addressFromPrivateKey,
|
||||||
getSignerForAddress,
|
getSignerForAddress,
|
||||||
isValidMnemonic,
|
isValidMnemonic,
|
||||||
|
walletHasRecoveryPhrase,
|
||||||
};
|
};
|
||||||
|
|||||||
468
tests/alarms.test.js
Normal file
468
tests/alarms.test.js
Normal file
@@ -0,0 +1,468 @@
|
|||||||
|
// Scheduling for the background context.
|
||||||
|
//
|
||||||
|
// The Chrome MV3 service worker is terminated after roughly 30 seconds idle,
|
||||||
|
// so anything scheduled with setInterval/setTimeout dies with it. These tests
|
||||||
|
// pin the recurring jobs to the alarms API and to the re-registration path a
|
||||||
|
// revived worker runs.
|
||||||
|
|
||||||
|
// A controllable clock plus a stubbed balance refresh, so a cadence test can
|
||||||
|
// measure the interval between refreshes that actually happened rather than
|
||||||
|
// asserting the interval someone intended.
|
||||||
|
let mockNow = 0;
|
||||||
|
const mockBalanceRefreshAt = [];
|
||||||
|
|
||||||
|
// jest.resetModules() clears the call record of every jest.fn, and loading the
|
||||||
|
// worker is exactly that call — so anything that must be counted across a load
|
||||||
|
// is counted here rather than read off a mock.
|
||||||
|
let mockSetIntervalCalls = 0;
|
||||||
|
|
||||||
|
// Extension storage reads do not take a constant amount of time, and that is
|
||||||
|
// what makes a guard timed to the alarm period bite: backgroundRefresh()
|
||||||
|
// stamps its freshness marker after awaiting loadState(), so any read that is
|
||||||
|
// quicker than the previous one puts the next tick inside a guard of exactly
|
||||||
|
// one period and the tick is skipped. A simulation with a constant latency
|
||||||
|
// would sit exactly on the boundary and hide the bug.
|
||||||
|
const MOCK_STORAGE_LATENCIES_MS = [7, 3, 11, 2, 9, 4, 13, 1, 6, 5];
|
||||||
|
const MOCK_MAX_STORAGE_LATENCY_MS = Math.max(...MOCK_STORAGE_LATENCIES_MS);
|
||||||
|
let mockStorageJitter = false;
|
||||||
|
let mockStorageOpCount = 0;
|
||||||
|
|
||||||
|
function mockStorageTick() {
|
||||||
|
if (!mockStorageJitter) return;
|
||||||
|
mockNow +=
|
||||||
|
MOCK_STORAGE_LATENCIES_MS[
|
||||||
|
mockStorageOpCount++ % MOCK_STORAGE_LATENCIES_MS.length
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
jest.mock("../src/shared/balances", () => ({
|
||||||
|
refreshBalances: jest.fn(async () => {
|
||||||
|
mockBalanceRefreshAt.push(Date.now());
|
||||||
|
}),
|
||||||
|
getProvider: jest.fn(() => ({})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
function makeAlarmsStub() {
|
||||||
|
const alarms = new Map();
|
||||||
|
const listeners = [];
|
||||||
|
const stub = {
|
||||||
|
created: [],
|
||||||
|
alarms,
|
||||||
|
create: jest.fn((name, info) => {
|
||||||
|
stub.created.push({ name, info });
|
||||||
|
alarms.set(name, { name, ...info });
|
||||||
|
}),
|
||||||
|
get: jest.fn(async (name) => alarms.get(name)),
|
||||||
|
clear: jest.fn(async (name) => alarms.delete(name)),
|
||||||
|
onAlarm: {
|
||||||
|
addListener: jest.fn((fn) => listeners.push(fn)),
|
||||||
|
},
|
||||||
|
fire: (name) => {
|
||||||
|
for (const fn of listeners) fn({ name });
|
||||||
|
},
|
||||||
|
listenerCount: () => listeners.length,
|
||||||
|
};
|
||||||
|
return stub;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("alarms module", () => {
|
||||||
|
let alarmsStub;
|
||||||
|
let alarmsMod;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.resetModules();
|
||||||
|
alarmsStub = makeAlarmsStub();
|
||||||
|
global.chrome = { alarms: alarmsStub };
|
||||||
|
alarmsMod = require("../src/shared/alarms");
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.chrome;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ensureRecurringAlarms schedules both recurring jobs", async () => {
|
||||||
|
const created = await alarmsMod.ensureRecurringAlarms();
|
||||||
|
expect(created).toEqual({ balance: true, phishing: true });
|
||||||
|
|
||||||
|
const names = alarmsStub.created.map((c) => c.name).sort();
|
||||||
|
expect(names).toEqual(
|
||||||
|
[
|
||||||
|
alarmsMod.BALANCE_REFRESH_ALARM,
|
||||||
|
alarmsMod.PHISHING_REFRESH_ALARM,
|
||||||
|
].sort(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the balance refresh keeps its 60-second cadence", async () => {
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
const balance = alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM);
|
||||||
|
expect(balance.periodInMinutes).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the phishing refresh keeps its 24-hour cadence", async () => {
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
const phishing = alarmsStub.alarms.get(
|
||||||
|
alarmsMod.PHISHING_REFRESH_ALARM,
|
||||||
|
);
|
||||||
|
expect(phishing.periodInMinutes).toBe(24 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no period is below the browser-enforced minimum", async () => {
|
||||||
|
// A period under one minute is silently clamped by the browser, so a
|
||||||
|
// request for one would mean the documented cadence is not the real
|
||||||
|
// one. Every period must be a whole minute at or above the minimum.
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
for (const { info } of alarmsStub.created) {
|
||||||
|
expect(info.periodInMinutes).toBeGreaterThanOrEqual(
|
||||||
|
alarmsMod.MIN_ALARM_PERIOD_MINUTES,
|
||||||
|
);
|
||||||
|
expect(Number.isInteger(info.periodInMinutes)).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a revived worker does not reset an existing alarm's schedule", async () => {
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
expect(alarmsStub.create).toHaveBeenCalledTimes(2);
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a missing alarm is re-created on the next start", async () => {
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
await alarmsStub.clear(alarmsMod.BALANCE_REFRESH_ALARM);
|
||||||
|
|
||||||
|
const again = await alarmsMod.ensureRecurringAlarms();
|
||||||
|
expect(again).toEqual({ balance: true, phishing: false });
|
||||||
|
expect(
|
||||||
|
alarmsStub.alarms.get(alarmsMod.BALANCE_REFRESH_ALARM),
|
||||||
|
).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an alarm left over with a stale period is re-created", async () => {
|
||||||
|
// 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, {
|
||||||
|
periodInMinutes: 7 * 24 * 60,
|
||||||
|
});
|
||||||
|
alarmsStub.create.mockClear();
|
||||||
|
|
||||||
|
const created = await alarmsMod.ensureRecurringAlarms();
|
||||||
|
expect(created.phishing).toBe(true);
|
||||||
|
expect(
|
||||||
|
alarmsStub.alarms.get(alarmsMod.PHISHING_REFRESH_ALARM)
|
||||||
|
.periodInMinutes,
|
||||||
|
).toBe(alarmsMod.PHISHING_REFRESH_PERIOD_MINUTES);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reconciling a period settles instead of re-creating forever", async () => {
|
||||||
|
alarmsStub.create(alarmsMod.BALANCE_REFRESH_ALARM, {
|
||||||
|
periodInMinutes: 30,
|
||||||
|
});
|
||||||
|
await alarmsMod.ensureRecurringAlarms();
|
||||||
|
alarmsStub.create.mockClear();
|
||||||
|
|
||||||
|
const again = await alarmsMod.ensureRecurringAlarms();
|
||||||
|
expect(again).toEqual({ balance: false, phishing: false });
|
||||||
|
expect(alarmsStub.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handlers are dispatched by alarm name from one listener", () => {
|
||||||
|
const balance = jest.fn();
|
||||||
|
const phishing = jest.fn();
|
||||||
|
expect(
|
||||||
|
alarmsMod.registerAlarmHandlers({
|
||||||
|
[alarmsMod.BALANCE_REFRESH_ALARM]: balance,
|
||||||
|
[alarmsMod.PHISHING_REFRESH_ALARM]: phishing,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
expect(alarmsStub.listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
alarmsStub.fire(alarmsMod.BALANCE_REFRESH_ALARM);
|
||||||
|
expect(balance).toHaveBeenCalledTimes(1);
|
||||||
|
expect(phishing).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
alarmsStub.fire(alarmsMod.PHISHING_REFRESH_ALARM);
|
||||||
|
expect(phishing).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
alarmsStub.fire("some-other-extension-alarm");
|
||||||
|
expect(balance).toHaveBeenCalledTimes(1);
|
||||||
|
expect(phishing).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Firefox MV2 gets the same treatment via browser.alarms", async () => {
|
||||||
|
// Both targets are built from one bundle. MV2 has a persistent
|
||||||
|
// background page, but it takes the alarm path too, so the schedule
|
||||||
|
// is the same code on both browsers.
|
||||||
|
jest.resetModules();
|
||||||
|
const firefoxAlarms = makeAlarmsStub();
|
||||||
|
global.browser = { alarms: firefoxAlarms };
|
||||||
|
try {
|
||||||
|
const mod = require("../src/shared/alarms");
|
||||||
|
const created = await mod.ensureRecurringAlarms();
|
||||||
|
expect(created).toEqual({ balance: true, phishing: true });
|
||||||
|
expect(firefoxAlarms.created).toHaveLength(2);
|
||||||
|
// The Chrome stub must not have been touched.
|
||||||
|
expect(alarmsStub.create).not.toHaveBeenCalled();
|
||||||
|
} finally {
|
||||||
|
delete global.browser;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a context without the alarms API degrades instead of throwing", async () => {
|
||||||
|
jest.resetModules();
|
||||||
|
delete global.chrome;
|
||||||
|
const mod = require("../src/shared/alarms");
|
||||||
|
await expect(mod.ensureRecurringAlarms()).resolves.toEqual({
|
||||||
|
balance: false,
|
||||||
|
phishing: false,
|
||||||
|
});
|
||||||
|
expect(mod.registerAlarmHandlers({})).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Loads the background worker against stubbed browser APIs. The returned
|
||||||
|
// store is the extension storage the worker sees, so a test can seed wallet
|
||||||
|
// state and read back what the worker persisted.
|
||||||
|
function loadBackground(initialStore = {}) {
|
||||||
|
const storageStore = initialStore;
|
||||||
|
const alarmsStub = makeAlarmsStub();
|
||||||
|
const listeners = { onInstalled: [], onStartup: [] };
|
||||||
|
global.chrome = {
|
||||||
|
alarms: alarmsStub,
|
||||||
|
storage: {
|
||||||
|
local: {
|
||||||
|
get: async (key) => {
|
||||||
|
mockStorageTick();
|
||||||
|
return Object.prototype.hasOwnProperty.call(
|
||||||
|
storageStore,
|
||||||
|
key,
|
||||||
|
)
|
||||||
|
? { [key]: storageStore[key] }
|
||||||
|
: {};
|
||||||
|
},
|
||||||
|
set: async (items) => {
|
||||||
|
mockStorageTick();
|
||||||
|
Object.assign(storageStore, items);
|
||||||
|
},
|
||||||
|
remove: async (key) => {
|
||||||
|
delete storageStore[key];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
runtime: {
|
||||||
|
onMessage: { addListener: jest.fn() },
|
||||||
|
onConnect: { addListener: jest.fn() },
|
||||||
|
onInstalled: {
|
||||||
|
addListener: jest.fn((fn) => listeners.onInstalled.push(fn)),
|
||||||
|
},
|
||||||
|
onStartup: {
|
||||||
|
addListener: jest.fn((fn) => listeners.onStartup.push(fn)),
|
||||||
|
},
|
||||||
|
getURL: (p) => "chrome-extension://test/" + p,
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
windows: {
|
||||||
|
onRemoved: { addListener: jest.fn() },
|
||||||
|
create: jest.fn(),
|
||||||
|
},
|
||||||
|
tabs: { query: jest.fn(), sendMessage: jest.fn() },
|
||||||
|
action: { setPopup: jest.fn() },
|
||||||
|
};
|
||||||
|
global.fetch = jest.fn(async () => ({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({ blacklist: [] }),
|
||||||
|
}));
|
||||||
|
jest.resetModules();
|
||||||
|
require("../src/background/index");
|
||||||
|
return { alarmsStub, listeners, store: storageStore };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush the promise chains the startup path and the alarm handlers run on.
|
||||||
|
async function settle() {
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("background worker scheduling", () => {
|
||||||
|
let alarmsStub;
|
||||||
|
let timers;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockSetIntervalCalls = 0;
|
||||||
|
timers = {
|
||||||
|
setInterval: jest
|
||||||
|
.spyOn(global, "setInterval")
|
||||||
|
.mockImplementation(() => {
|
||||||
|
mockSetIntervalCalls++;
|
||||||
|
return 0;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
timers.setInterval.mockRestore();
|
||||||
|
delete global.chrome;
|
||||||
|
delete global.fetch;
|
||||||
|
jest.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("startup schedules the recurring jobs as alarms, not timers", async () => {
|
||||||
|
alarmsStub = loadBackground().alarmsStub;
|
||||||
|
// 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(),
|
||||||
|
);
|
||||||
|
expect(mockSetIntervalCalls).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an onAlarm listener is installed on startup", async () => {
|
||||||
|
alarmsStub = loadBackground().alarmsStub;
|
||||||
|
await settle();
|
||||||
|
expect(alarmsStub.listenerCount()).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("onInstalled and onStartup both re-establish the schedule", async () => {
|
||||||
|
const loaded = loadBackground();
|
||||||
|
alarmsStub = loaded.alarmsStub;
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(loaded.listeners.onInstalled).toHaveLength(1);
|
||||||
|
expect(loaded.listeners.onStartup).toHaveLength(1);
|
||||||
|
|
||||||
|
// A browser start after the alarms were dropped must put them back.
|
||||||
|
alarmsStub.alarms.clear();
|
||||||
|
alarmsStub.created.length = 0;
|
||||||
|
loaded.listeners.onStartup[0]();
|
||||||
|
await settle();
|
||||||
|
expect(alarmsStub.created).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the install-time listener and the top-level call share one run", async () => {
|
||||||
|
// On a fresh install both fire, close enough that both could observe
|
||||||
|
// an alarm missing and create it — and a second create restarts the
|
||||||
|
// period the first one just set.
|
||||||
|
const loaded = loadBackground();
|
||||||
|
alarmsStub = loaded.alarmsStub;
|
||||||
|
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(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The alarm period alone must set the cadence. A freshness guard timed to the
|
||||||
|
// period vetoes the very tick it gates, because the guard is measured from
|
||||||
|
// when the last run finished and the alarm fires one run-duration before that.
|
||||||
|
// These tests measure the interval between refreshes that actually ran.
|
||||||
|
describe("balance refresh steady-state cadence", () => {
|
||||||
|
const {
|
||||||
|
BALANCE_REFRESH_PERIOD_MINUTES,
|
||||||
|
BALANCE_REFRESH_ALARM,
|
||||||
|
} = require("../src/shared/alarms");
|
||||||
|
const PERIOD_MS = BALANCE_REFRESH_PERIOD_MINUTES * 60 * 1000;
|
||||||
|
|
||||||
|
let clockSpy;
|
||||||
|
let timerSpy;
|
||||||
|
|
||||||
|
function seededStore() {
|
||||||
|
return {
|
||||||
|
autistmask: {
|
||||||
|
hasWallet: true,
|
||||||
|
wallets: [
|
||||||
|
{ address: "0x0000000000000000000000000000000000000001" },
|
||||||
|
],
|
||||||
|
lastBalanceRefresh: 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockNow = Date.UTC(2026, 0, 1, 0, 0, 0);
|
||||||
|
mockBalanceRefreshAt.length = 0;
|
||||||
|
mockSetIntervalCalls = 0;
|
||||||
|
mockStorageOpCount = 0;
|
||||||
|
mockStorageJitter = false;
|
||||||
|
clockSpy = jest.spyOn(Date, "now").mockImplementation(() => mockNow);
|
||||||
|
timerSpy = jest.spyOn(global, "setInterval").mockImplementation(() => {
|
||||||
|
mockSetIntervalCalls++;
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
mockStorageJitter = false;
|
||||||
|
clockSpy.mockRestore();
|
||||||
|
timerSpy.mockRestore();
|
||||||
|
delete global.chrome;
|
||||||
|
delete global.fetch;
|
||||||
|
jest.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ten alarm ticks produce ten refreshes, one per period", async () => {
|
||||||
|
const { alarmsStub } = loadBackground(seededStore());
|
||||||
|
await settle();
|
||||||
|
mockStorageJitter = true;
|
||||||
|
|
||||||
|
const TICKS = 10;
|
||||||
|
let tickAt = mockNow + PERIOD_MS;
|
||||||
|
for (let i = 0; i < TICKS; i++) {
|
||||||
|
mockNow = tickAt;
|
||||||
|
tickAt += PERIOD_MS;
|
||||||
|
alarmsStub.fire(BALANCE_REFRESH_ALARM);
|
||||||
|
await settle();
|
||||||
|
}
|
||||||
|
|
||||||
|
// No tick was a no-op. This is the assertion that fails when the guard
|
||||||
|
// is timed to the alarm period.
|
||||||
|
expect(mockBalanceRefreshAt).toHaveLength(TICKS);
|
||||||
|
|
||||||
|
// And the observed cadence is one period, not two.
|
||||||
|
const intervals = mockBalanceRefreshAt
|
||||||
|
.slice(1)
|
||||||
|
.map((t, i) => t - mockBalanceRefreshAt[i]);
|
||||||
|
for (const interval of intervals) {
|
||||||
|
expect(interval).toBeGreaterThanOrEqual(
|
||||||
|
PERIOD_MS - MOCK_MAX_STORAGE_LATENCY_MS,
|
||||||
|
);
|
||||||
|
expect(interval).toBeLessThanOrEqual(
|
||||||
|
PERIOD_MS + MOCK_MAX_STORAGE_LATENCY_MS,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a refresh an open popup just did still suppresses the tick", async () => {
|
||||||
|
// The guard's actual job, and the reason it is shortened rather than
|
||||||
|
// removed: while the popup is open it refreshes every 10 seconds and
|
||||||
|
// stamps the same field, and the background job has nothing to add.
|
||||||
|
const store = seededStore();
|
||||||
|
const { alarmsStub } = loadBackground(store);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
mockNow += PERIOD_MS;
|
||||||
|
store.autistmask.lastBalanceRefresh = mockNow - 10 * 1000;
|
||||||
|
alarmsStub.fire(BALANCE_REFRESH_ALARM);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(mockBalanceRefreshAt).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
const { Network, Transaction, Wallet } = require("ethers");
|
const {
|
||||||
|
Network,
|
||||||
|
Transaction,
|
||||||
|
Wallet,
|
||||||
|
decodeRlp,
|
||||||
|
encodeRlp,
|
||||||
|
} = require("ethers");
|
||||||
const {
|
const {
|
||||||
verifySignedTx,
|
verifySignedTx,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
assertNoForbiddenFields,
|
assertNoForbiddenFields,
|
||||||
assertNothingUnchecked,
|
assertNothingUnchecked,
|
||||||
|
assertCanonicalBytes,
|
||||||
sameAddress,
|
sameAddress,
|
||||||
failureIsRetryable,
|
failureIsRetryable,
|
||||||
describeTxFailure,
|
describeTxFailure,
|
||||||
@@ -603,6 +610,60 @@ describe("verifySignedTx exhaustiveness", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Every comparison above runs against the decode, but the string that is
|
||||||
|
// handed to broadcastTransaction() is the artifact. An encoding the decoder
|
||||||
|
// normalizes away therefore checks as one transaction and broadcasts as
|
||||||
|
// different bytes, so the artifact must be the canonical encoding of itself.
|
||||||
|
describe("verifySignedTx canonical encoding", () => {
|
||||||
|
// Re-encode a signed type-2 artifact with a leading zero byte on the RLP
|
||||||
|
// value field. It decodes to exactly the approved transaction — same
|
||||||
|
// value, same signer, same everything the field comparisons look at — and
|
||||||
|
// it is not the same string.
|
||||||
|
async function nonCanonical() {
|
||||||
|
const raw = await signedWith({});
|
||||||
|
const items = decodeRlp("0x" + raw.slice(4));
|
||||||
|
// type 2 payload order: chainId, nonce, maxPriorityFeePerGas,
|
||||||
|
// maxFeePerGas, gasLimit, to, value, data, accessList, then the
|
||||||
|
// signature.
|
||||||
|
const padded = items.slice();
|
||||||
|
padded[6] = "0x00" + items[6].slice(2);
|
||||||
|
return "0x02" + encodeRlp(padded).slice(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("the mutation decodes to the approved transaction and is not it", async () => {
|
||||||
|
const raw = await signedWith({});
|
||||||
|
const mutated = await nonCanonical();
|
||||||
|
const parsed = Transaction.from(mutated);
|
||||||
|
expect(mutated).not.toBe(raw);
|
||||||
|
expect(mutated.length).toBeGreaterThan(raw.length);
|
||||||
|
expect(parsed.value).toBe(BigInt(TX_PARAMS.value));
|
||||||
|
expect(parsed.from).toBe(signer.address);
|
||||||
|
expect(parsed.serialized).not.toBe(mutated);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("refuses an artifact that is not its own canonical encoding", async () => {
|
||||||
|
const mutated = await nonCanonical();
|
||||||
|
expect(() =>
|
||||||
|
verifySignedTx(mutated, TX_PARAMS, signer.address, SELECTED),
|
||||||
|
).toThrow(/not encoded canonically/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("assertCanonicalBytes accepts what ethers itself produced", async () => {
|
||||||
|
const raw = await signedWith({});
|
||||||
|
expect(() =>
|
||||||
|
assertCanonicalBytes(Transaction.from(raw), raw),
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hex case is not part of the encoding", async () => {
|
||||||
|
const raw = await signedWith({});
|
||||||
|
const upper = "0x" + raw.slice(2).toUpperCase();
|
||||||
|
expect(() =>
|
||||||
|
verifySignedTx(upper, TX_PARAMS, signer.address, SELECTED),
|
||||||
|
).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// The approval and the artifact spell the same values differently. None of
|
// The approval and the artifact spell the same values differently. None of
|
||||||
// these differences is tampering, so none may refuse the signature.
|
// these differences is tampering, so none may refuse the signature.
|
||||||
describe("verifySignedTx normalization", () => {
|
describe("verifySignedTx normalization", () => {
|
||||||
|
|||||||
471
tests/backgroundApproval.test.js
Normal file
471
tests/backgroundApproval.test.js
Normal file
@@ -0,0 +1,471 @@
|
|||||||
|
// The background's approval message wiring, driven end to end: a dApp
|
||||||
|
// eth_sendTransaction raises a pending approval, and the popup answers it with
|
||||||
|
// AUTISTMASK_TX_RESPONSE / AUTISTMASK_SIGN_RESPONSE.
|
||||||
|
//
|
||||||
|
// What this exists for is the duplicate response. The handler verifies and
|
||||||
|
// broadcasts asynchronously, and the approval deliberately survives a
|
||||||
|
// retryable failure so the user can try again with the transaction they
|
||||||
|
// already saw — which means the entry being present is not by itself proof
|
||||||
|
// that no attempt is running. A second response carrying the same id (a
|
||||||
|
// reloaded approval window re-rendering a live Approve button, a popup that
|
||||||
|
// emits the message twice) must not start a second verify and broadcast: with
|
||||||
|
// the ordinary dApp approval shape the page fixes no nonce, so two artifacts
|
||||||
|
// signed at different nonces both verify, and the approved transfer would go
|
||||||
|
// out twice.
|
||||||
|
|
||||||
|
const { Wallet } = require("ethers");
|
||||||
|
|
||||||
|
const SIGNER_KEY =
|
||||||
|
"0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d";
|
||||||
|
const signer = new Wallet(SIGNER_KEY);
|
||||||
|
const RECIPIENT = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
|
||||||
|
|
||||||
|
const ORIGIN = "https://dapp.example";
|
||||||
|
const HOSTNAME = "dapp.example";
|
||||||
|
const EXT_URL = "chrome-extension://autistmask/";
|
||||||
|
|
||||||
|
// What the dApp asks for: no nonce, no gas, no fees. This is the shape that
|
||||||
|
// makes a duplicate broadcast possible at all.
|
||||||
|
const TX_PARAMS = {
|
||||||
|
from: signer.address,
|
||||||
|
to: RECIPIENT,
|
||||||
|
value: "0x2386f26fc10000",
|
||||||
|
data: "0x",
|
||||||
|
};
|
||||||
|
|
||||||
|
// The fields the popup's populateTransaction() would fill in. The nonce is a
|
||||||
|
// parameter because the duplicate case turns on the two artifacts differing
|
||||||
|
// in exactly the field nothing constrains.
|
||||||
|
function populated(nonce) {
|
||||||
|
return {
|
||||||
|
type: 2,
|
||||||
|
chainId: 1,
|
||||||
|
nonce,
|
||||||
|
gasLimit: 100000n,
|
||||||
|
maxFeePerGas: 2000000000n,
|
||||||
|
maxPriorityFeePerGas: 1000000000n,
|
||||||
|
to: TX_PARAMS.to,
|
||||||
|
value: BigInt(TX_PARAMS.value),
|
||||||
|
data: TX_PARAMS.data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function signedAtNonce(nonce) {
|
||||||
|
return signer.signTransaction(populated(nonce));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A promise whose settlement the test controls, so a broadcast can be held in
|
||||||
|
// flight while the second response arrives.
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
let reject;
|
||||||
|
const promise = new Promise((res, rej) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
});
|
||||||
|
return { promise, resolve, reject };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load the background worker against stubbed browser and network APIs and
|
||||||
|
// return the handles the tests drive it through. Everything that would touch
|
||||||
|
// the network or the browser's own schedulers is mocked; the approval
|
||||||
|
// verification is the real module, because that is what the handler under
|
||||||
|
// test is wired to.
|
||||||
|
function loadBackground(options) {
|
||||||
|
const opts = options || {};
|
||||||
|
jest.resetModules();
|
||||||
|
|
||||||
|
const broadcastTransaction = jest.fn();
|
||||||
|
const loadState = jest.fn(opts.loadState || (async () => {}));
|
||||||
|
|
||||||
|
jest.doMock("../src/shared/state", () => ({
|
||||||
|
state: { rpcUrl: "https://rpc.invalid", wallets: [] },
|
||||||
|
loadState,
|
||||||
|
saveState: jest.fn(async () => {}),
|
||||||
|
currentNetwork: () => ({ chainId: "0x1" }),
|
||||||
|
}));
|
||||||
|
jest.doMock("../src/shared/balances", () => ({
|
||||||
|
getProvider: () => ({ broadcastTransaction }),
|
||||||
|
refreshBalances: jest.fn(async () => {}),
|
||||||
|
}));
|
||||||
|
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(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const persisted = {
|
||||||
|
wallets: [
|
||||||
|
{ name: "Wallet 1", type: "hd", addresses: [signer.address] },
|
||||||
|
],
|
||||||
|
rpcUrl: "https://rpc.invalid",
|
||||||
|
activeAddress: signer.address,
|
||||||
|
allowedSites: { [signer.address]: [HOSTNAME] },
|
||||||
|
deniedSites: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
let messageListener = null;
|
||||||
|
const created = [];
|
||||||
|
|
||||||
|
global.chrome = {
|
||||||
|
storage: {
|
||||||
|
local: {
|
||||||
|
get: jest.fn(async () => ({ autistmask: persisted })),
|
||||||
|
set: jest.fn(async () => {}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
runtime: {
|
||||||
|
getURL: (path) => EXT_URL + path,
|
||||||
|
onMessage: {
|
||||||
|
addListener: (fn) => {
|
||||||
|
messageListener = fn;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
onConnect: { addListener: () => {} },
|
||||||
|
lastError: null,
|
||||||
|
},
|
||||||
|
windows: {
|
||||||
|
getLastFocused: (cb) => cb(null),
|
||||||
|
create: (options2, cb) => {
|
||||||
|
created.push(options2);
|
||||||
|
cb({ id: created.length });
|
||||||
|
},
|
||||||
|
remove: (id, cb) => cb && cb(),
|
||||||
|
onRemoved: { addListener: () => {} },
|
||||||
|
},
|
||||||
|
tabs: {
|
||||||
|
query: (q, cb) => cb([]),
|
||||||
|
sendMessage: () => {},
|
||||||
|
},
|
||||||
|
action: { setPopup: () => {} },
|
||||||
|
};
|
||||||
|
|
||||||
|
require("../src/background/index");
|
||||||
|
|
||||||
|
// Send a message the way the browser would, and hand back whatever the
|
||||||
|
// handler passed to sendResponse.
|
||||||
|
function send(msg, sender) {
|
||||||
|
const sendResponse = jest.fn();
|
||||||
|
const kept = messageListener(msg, sender || {}, sendResponse);
|
||||||
|
return { sendResponse, kept };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raise a pending transaction approval the way a dApp does, and dig the
|
||||||
|
// approval id back out of the popup URL the background opened.
|
||||||
|
function requestTx() {
|
||||||
|
let rpcResult = null;
|
||||||
|
const sendResponse = jest.fn((r) => {
|
||||||
|
rpcResult = r;
|
||||||
|
});
|
||||||
|
messageListener(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_RPC",
|
||||||
|
method: "eth_sendTransaction",
|
||||||
|
params: [TX_PARAMS],
|
||||||
|
},
|
||||||
|
{ origin: ORIGIN },
|
||||||
|
sendResponse,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: () => new URL(created[0].url).searchParams.get("approval"),
|
||||||
|
result: () => rpcResult,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
send,
|
||||||
|
requestTx,
|
||||||
|
broadcastTransaction,
|
||||||
|
loadState,
|
||||||
|
created,
|
||||||
|
fromPopup: { url: EXT_URL + "src/popup/index.html" },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Let the handler's promise chain run to the next suspension point.
|
||||||
|
async function settle() {
|
||||||
|
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.chrome;
|
||||||
|
jest.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("one approval, one broadcast", () => {
|
||||||
|
test("a second AUTISTMASK_TX_RESPONSE for the same id does not broadcast again", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
expect(id).toBeTruthy();
|
||||||
|
|
||||||
|
const inFlight = deferred();
|
||||||
|
bg.broadcastTransaction.mockReturnValue(inFlight.promise);
|
||||||
|
|
||||||
|
// The popup answers. Verification passes and the broadcast is held
|
||||||
|
// open, which is the whole window the second message arrives in.
|
||||||
|
const first = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
// A reloaded approval window signs the same approval again. Nothing
|
||||||
|
// in the approval fixes a nonce, so this artifact verifies just as
|
||||||
|
// well as the first one.
|
||||||
|
const second = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(8),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(second.sendResponse).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
error: expect.stringMatching(/already being sent/),
|
||||||
|
retryable: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
inFlight.resolve({ hash: "0xfeed" });
|
||||||
|
await settle();
|
||||||
|
expect(first.sendResponse).toHaveBeenCalledWith({ txHash: "0xfeed" });
|
||||||
|
expect(pending.result()).toEqual({ result: "0xfeed" });
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the same artifact sent twice broadcasts once", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
const inFlight = deferred();
|
||||||
|
bg.broadcastTransaction.mockReturnValue(inFlight.promise);
|
||||||
|
const raw = await signedAtNonce(7);
|
||||||
|
const msg = {
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: raw,
|
||||||
|
};
|
||||||
|
|
||||||
|
bg.send(msg, { url: bg.fromPopup.url });
|
||||||
|
bg.send(msg, { url: bg.fromPopup.url });
|
||||||
|
await settle();
|
||||||
|
inFlight.resolve({ hash: "0xfeed" });
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a response arriving after the broadcast finished finds nothing to send", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
bg.broadcastTransaction.mockResolvedValue({ hash: "0xfeed" });
|
||||||
|
bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
const late = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(8),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(late.sendResponse).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a second AUTISTMASK_SIGN_RESPONSE for the same id is refused", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
// Hold the transaction approval in flight, then answer it a second
|
||||||
|
// time as if it were a sign approval: the sign handler must apply the
|
||||||
|
// same interlock rather than running its own verification.
|
||||||
|
const inFlight = deferred();
|
||||||
|
bg.broadcastTransaction.mockReturnValue(inFlight.promise);
|
||||||
|
bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
const second = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_SIGN_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
signature: "0x00",
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(second.sendResponse).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
error: expect.stringMatching(/already being signed/),
|
||||||
|
retryable: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
inFlight.resolve({ hash: "0xfeed" });
|
||||||
|
await settle();
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The interlock must not cost the retry the approval exists to allow.
|
||||||
|
describe("the interlock releases a failed attempt", () => {
|
||||||
|
test("a retryable failure before the broadcast leaves the approval usable", async () => {
|
||||||
|
let failNext = true;
|
||||||
|
const bg = loadBackground({
|
||||||
|
loadState: async () => {
|
||||||
|
if (failNext) {
|
||||||
|
failNext = false;
|
||||||
|
throw new Error("storage unavailable");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
const first = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
expect(bg.broadcastTransaction).not.toHaveBeenCalled();
|
||||||
|
expect(first.sendResponse).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ retryable: true }),
|
||||||
|
);
|
||||||
|
|
||||||
|
bg.broadcastTransaction.mockResolvedValue({ hash: "0xfeed" });
|
||||||
|
const retry = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(retry.sendResponse).toHaveBeenCalledWith({ txHash: "0xfeed" });
|
||||||
|
expect(pending.result()).toEqual({ result: "0xfeed" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a mismatched artifact spends the approval outright", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
// Signed for a different recipient than the one that was approved.
|
||||||
|
const wrong = await signer.signTransaction({
|
||||||
|
...populated(7),
|
||||||
|
to: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
|
||||||
|
});
|
||||||
|
const first = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: wrong,
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
expect(first.sendResponse).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ retryable: false, stage: "verify" }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const retry = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: bg.fromPopup.url },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).not.toHaveBeenCalled();
|
||||||
|
expect(retry.sendResponse).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("popup-only messages", () => {
|
||||||
|
test("a page sender cannot answer an approval", async () => {
|
||||||
|
const bg = loadBackground();
|
||||||
|
const pending = bg.requestTx();
|
||||||
|
await settle();
|
||||||
|
const id = pending.id();
|
||||||
|
|
||||||
|
const spoof = bg.send(
|
||||||
|
{
|
||||||
|
type: "AUTISTMASK_TX_RESPONSE",
|
||||||
|
id,
|
||||||
|
approved: true,
|
||||||
|
rawSignedTx: await signedAtNonce(7),
|
||||||
|
},
|
||||||
|
{ url: ORIGIN + "/index.html" },
|
||||||
|
);
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
expect(bg.broadcastTransaction).not.toHaveBeenCalled();
|
||||||
|
expect(spoof.sendResponse).toHaveBeenCalledWith({
|
||||||
|
error: "Unauthorized sender",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -255,6 +255,11 @@ async function openPopup(ctx, popupUrl) {
|
|||||||
|
|
||||||
// Full wallet creation through the real UI: BIP-39 generation, libsodium
|
// Full wallet creation through the real UI: BIP-39 generation, libsodium
|
||||||
// vault encryption and extension storage persistence, for real.
|
// vault encryption and extension storage persistence, for real.
|
||||||
|
//
|
||||||
|
// Returns the recovery phrase it generated. Tests that assert on a secret
|
||||||
|
// need the real value — checking for "some 12 words" would pass against the
|
||||||
|
// wrong wallet's phrase, and checking for nothing at all would pass against
|
||||||
|
// a screen that shows the phrase it was supposed to hide.
|
||||||
async function createWallet(page) {
|
async function createWallet(page) {
|
||||||
await page.click("#btn-welcome-add");
|
await page.click("#btn-welcome-add");
|
||||||
await visible(page, "#view-add-wallet");
|
await visible(page, "#view-add-wallet");
|
||||||
@@ -263,10 +268,12 @@ async function createWallet(page) {
|
|||||||
const el = document.getElementById("wallet-mnemonic");
|
const el = document.getElementById("wallet-mnemonic");
|
||||||
return el && el.value.trim().split(/\s+/).length >= 12;
|
return el && el.value.trim().split(/\s+/).length >= 12;
|
||||||
});
|
});
|
||||||
|
const phrase = (await page.inputValue("#wallet-mnemonic")).trim();
|
||||||
await page.fill("#add-wallet-password", PASSWORD);
|
await page.fill("#add-wallet-password", PASSWORD);
|
||||||
await page.fill("#add-wallet-password-confirm", PASSWORD);
|
await page.fill("#add-wallet-password-confirm", PASSWORD);
|
||||||
await page.click("#btn-add-wallet-confirm");
|
await page.click("#btn-add-wallet-confirm");
|
||||||
await visible(page, "#view-main", 60000);
|
await visible(page, "#view-main", 60000);
|
||||||
|
return phrase;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reach the address detail screen from wherever the popup restored to.
|
// Reach the address detail screen from wherever the popup restored to.
|
||||||
@@ -281,6 +288,7 @@ async function openAddressDetail(page) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
PASSWORD,
|
||||||
createWallet,
|
createWallet,
|
||||||
launch,
|
launch,
|
||||||
openAddressDetail,
|
openAddressDetail,
|
||||||
|
|||||||
264
tests/e2e/run.js
264
tests/e2e/run.js
@@ -10,6 +10,7 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
PASSWORD,
|
||||||
createWallet,
|
createWallet,
|
||||||
launch,
|
launch,
|
||||||
openAddressDetail,
|
openAddressDetail,
|
||||||
@@ -34,6 +35,10 @@ function assert(cond, message) {
|
|||||||
if (!cond) throw new Error(message);
|
if (!cond) throw new Error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
function withTimeout(promise, name) {
|
function withTimeout(promise, name) {
|
||||||
let timer;
|
let timer;
|
||||||
const timeout = new Promise((_, reject) => {
|
const timeout = new Promise((_, reject) => {
|
||||||
@@ -56,7 +61,11 @@ test("popup loads and reaches the welcome view", async (env) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test("wallet creation through the UI reaches the main view", async (env) => {
|
test("wallet creation through the UI reaches the main view", async (env) => {
|
||||||
await createWallet(env.page);
|
env.phrase = await createWallet(env.page);
|
||||||
|
assert(
|
||||||
|
env.phrase.split(/\s+/).length >= 12,
|
||||||
|
"wallet creation did not yield a recovery phrase",
|
||||||
|
);
|
||||||
const addrCount = await env.page
|
const addrCount = await env.page
|
||||||
.locator("#wallet-list .btn-addr-info")
|
.locator("#wallet-list .btn-addr-info")
|
||||||
.count();
|
.count();
|
||||||
@@ -117,6 +126,256 @@ test("transaction detail renders an ERC-20 transfer (#151)", async (env) => {
|
|||||||
assert(dots > 0, "token contract row rendered without its colour dot");
|
assert(dots > 0, "token contract row rendered without its colour dot");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// -------------------------------------------- recovery phrase (#161)
|
||||||
|
|
||||||
|
// The gear toggles, so pressing it while Settings is already up leaves it.
|
||||||
|
async function openSettings(page) {
|
||||||
|
if (!(await page.isVisible("#view-settings"))) {
|
||||||
|
await page.click("#btn-settings");
|
||||||
|
}
|
||||||
|
await visible(page, "#view-settings");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Everything the recovery phrase screen is holding, read straight out of
|
||||||
|
// the DOM whether or not that screen is the one on top. Reading it while it
|
||||||
|
// is hidden is the point: "cleared on leave" means the node is empty, not
|
||||||
|
// merely off-screen.
|
||||||
|
async function phraseScreenState(page) {
|
||||||
|
return page.evaluate(() => ({
|
||||||
|
value: document.getElementById("show-phrase-value").textContent,
|
||||||
|
error: document.getElementById("show-phrase-flash").textContent,
|
||||||
|
html: document.getElementById("view-show-phrase").innerHTML,
|
||||||
|
resultHidden: document
|
||||||
|
.getElementById("show-phrase-result")
|
||||||
|
.classList.contains("hidden"),
|
||||||
|
viewHidden: document
|
||||||
|
.getElementById("view-show-phrase")
|
||||||
|
.classList.contains("hidden"),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openPhraseScreen(page) {
|
||||||
|
await openSettings(page);
|
||||||
|
await page.click("#settings-wallet-list .btn-show-phrase");
|
||||||
|
await visible(page, "#view-show-phrase");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revealPhrase(page) {
|
||||||
|
await page.fill("#show-phrase-password", PASSWORD);
|
||||||
|
await page.click("#btn-show-phrase-reveal");
|
||||||
|
await visible(page, "#show-phrase-result", 60000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertWiped(st, phrase, where) {
|
||||||
|
assert(st.value === "", "phrase still in the DOM " + where);
|
||||||
|
assert(st.resultHidden, "result section still shown " + where);
|
||||||
|
assert(
|
||||||
|
!st.html.includes(phrase),
|
||||||
|
"the recovery phrase is still somewhere in the screen markup " + where,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("only an HD wallet is offered the recovery phrase action (#161)", async (env) => {
|
||||||
|
await openSettings(env.page);
|
||||||
|
const offered = await env.page
|
||||||
|
.locator("#settings-wallet-list .btn-show-phrase")
|
||||||
|
.count();
|
||||||
|
const wallets = await env.page
|
||||||
|
.locator("#settings-wallet-list .btn-delete-wallet")
|
||||||
|
.count();
|
||||||
|
assert(wallets === 1, "expected exactly one wallet row, got " + wallets);
|
||||||
|
assert(
|
||||||
|
offered === 1,
|
||||||
|
"the HD wallet was not offered the recovery phrase action",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The other half of the gate, against the real UI: a wallet holding a bare
|
||||||
|
// private key has no phrase to show, so no row of it may offer the action.
|
||||||
|
// The key is generated here rather than committed — the repo holds no
|
||||||
|
// private keys, test ones included.
|
||||||
|
test("a key wallet is not offered the recovery phrase action (#161)", async (env) => {
|
||||||
|
const { Wallet } = require("ethers");
|
||||||
|
|
||||||
|
await openSettings(env.page);
|
||||||
|
await env.page.click("#btn-main-add-wallet");
|
||||||
|
await visible(env.page, "#view-add-wallet");
|
||||||
|
await env.page.click("#tab-privkey");
|
||||||
|
await env.page.fill(
|
||||||
|
"#import-private-key",
|
||||||
|
Wallet.createRandom().privateKey,
|
||||||
|
);
|
||||||
|
await env.page.fill("#add-wallet-password", PASSWORD);
|
||||||
|
await env.page.fill("#add-wallet-password-confirm", PASSWORD);
|
||||||
|
await env.page.click("#btn-add-wallet-confirm");
|
||||||
|
await visible(env.page, "#view-main", 60000);
|
||||||
|
|
||||||
|
await openSettings(env.page);
|
||||||
|
const wallets = await env.page
|
||||||
|
.locator("#settings-wallet-list .btn-delete-wallet")
|
||||||
|
.count();
|
||||||
|
const offered = await env.page
|
||||||
|
.locator("#settings-wallet-list .btn-show-phrase")
|
||||||
|
.count();
|
||||||
|
assert(wallets === 2, "expected two wallet rows, got " + wallets);
|
||||||
|
assert(
|
||||||
|
offered === 1,
|
||||||
|
"the key wallet was offered the recovery phrase action",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the recovery phrase screen holds nothing before the password (#161)", async (env) => {
|
||||||
|
await openPhraseScreen(env.page);
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assertWiped(st, env.phrase, "before any password was entered");
|
||||||
|
const passwordShown = await env.page.isVisible(
|
||||||
|
"#show-phrase-password-section",
|
||||||
|
);
|
||||||
|
assert(passwordShown, "the password prompt is not shown");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a wrong password reveals nothing (#161)", async (env) => {
|
||||||
|
await env.page.fill("#show-phrase-password", "not-the-password");
|
||||||
|
await env.page.click("#btn-show-phrase-reveal");
|
||||||
|
await env.page.waitForFunction(
|
||||||
|
() =>
|
||||||
|
document.getElementById("show-phrase-flash").textContent.length > 0,
|
||||||
|
null,
|
||||||
|
{ timeout: 60000 },
|
||||||
|
);
|
||||||
|
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assertWiped(st, env.phrase, "after a wrong password");
|
||||||
|
assert(
|
||||||
|
/^[A-Z].*\.$/.test(st.error.trim()),
|
||||||
|
"the wrong-password error is not a full sentence: " +
|
||||||
|
JSON.stringify(st.error),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the correct password reveals the full phrase, and nothing logs it (#161)", async (env) => {
|
||||||
|
const console_ = [];
|
||||||
|
const listener = (msg) => console_.push(msg.text());
|
||||||
|
env.page.on("console", listener);
|
||||||
|
try {
|
||||||
|
await revealPhrase(env.page);
|
||||||
|
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assert(
|
||||||
|
st.value === env.phrase,
|
||||||
|
"the displayed phrase is not the wallet's phrase, verbatim",
|
||||||
|
);
|
||||||
|
const promptShown = await env.page.isVisible(
|
||||||
|
"#show-phrase-password-section",
|
||||||
|
);
|
||||||
|
assert(!promptShown, "the password prompt is still shown after unlock");
|
||||||
|
|
||||||
|
// Full Identifiers Policy: shown whole, and copyable.
|
||||||
|
const title = await env.page.getAttribute(
|
||||||
|
"#show-phrase-value",
|
||||||
|
"title",
|
||||||
|
);
|
||||||
|
assert(title === "Click to copy", "the phrase is not click-to-copy");
|
||||||
|
|
||||||
|
const leaked = console_.filter((line) => line.includes(env.phrase));
|
||||||
|
assert(
|
||||||
|
leaked.length === 0,
|
||||||
|
"the recovery phrase reached the console: " +
|
||||||
|
JSON.stringify(leaked),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
env.page.off("console", listener);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('"Back" wipes the revealed phrase (#161)', async (env) => {
|
||||||
|
await env.page.click("#btn-show-phrase-back");
|
||||||
|
await visible(env.page, "#view-settings");
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assert(st.viewHidden, "the recovery phrase screen is still on top");
|
||||||
|
assertWiped(st, env.phrase, "after Back");
|
||||||
|
});
|
||||||
|
|
||||||
|
// The settings gear leaves the screen without touching its Back button. A
|
||||||
|
// clear wired only to Back would pass the test above and leak here.
|
||||||
|
test("leaving by the settings gear wipes it too (#161)", async (env) => {
|
||||||
|
await openPhraseScreen(env.page);
|
||||||
|
await revealPhrase(env.page);
|
||||||
|
await env.page.click("#btn-settings");
|
||||||
|
await visible(env.page, "#view-settings");
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assertWiped(st, env.phrase, "after leaving via the settings gear");
|
||||||
|
});
|
||||||
|
|
||||||
|
// The same leave, but taken while the decrypt is still running. Both
|
||||||
|
// clicks are dispatched inside one page task on purpose: "Reveal" runs its
|
||||||
|
// handler up to the await, the gear then runs the leave — and the wipe with
|
||||||
|
// it — to completion, and the decrypt's continuation resumes afterwards.
|
||||||
|
// Without a liveness check that continuation writes the phrase into the
|
||||||
|
// hidden screen after the wipe, and nothing is left to wipe it again.
|
||||||
|
//
|
||||||
|
// A human cannot produce this interleaving by hand once libsodium's wasm is
|
||||||
|
// warm, because crypto_pwhash is synchronous and the only suspension point
|
||||||
|
// is a microtask; the window a user can actually hit is a still-pending
|
||||||
|
// sodium.ready on the first vault use of a page load. Forcing it here is
|
||||||
|
// the only way to test the guard deterministically.
|
||||||
|
test("leaving while the decrypt is in flight reveals nothing (#161)", async (env) => {
|
||||||
|
await openPhraseScreen(env.page);
|
||||||
|
await env.page.fill("#show-phrase-password", PASSWORD);
|
||||||
|
await env.page.evaluate(() => {
|
||||||
|
document.getElementById("btn-show-phrase-reveal").click();
|
||||||
|
document.getElementById("btn-settings").click();
|
||||||
|
});
|
||||||
|
await visible(env.page, "#view-settings");
|
||||||
|
|
||||||
|
// The Reveal button is disabled for exactly the duration of the
|
||||||
|
// decrypt and re-enabled in the same continuation that would have
|
||||||
|
// written the phrase, so waiting for it to come back is a precise
|
||||||
|
// "the decrypt has settled and its handler has finished" signal
|
||||||
|
// rather than a guess at a duration.
|
||||||
|
await env.page.waitForFunction(
|
||||||
|
() => !document.getElementById("btn-show-phrase-reveal").disabled,
|
||||||
|
null,
|
||||||
|
{ timeout: 60000 },
|
||||||
|
);
|
||||||
|
await sleep(2000);
|
||||||
|
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
// Printed on every run, pass or fail: "the phrase is not there" is
|
||||||
|
// worth more as a measurement than as a silent assertion, and the
|
||||||
|
// same line read from a build without the guard is what this test
|
||||||
|
// exists to prevent.
|
||||||
|
console.log(
|
||||||
|
"# probe: len=" +
|
||||||
|
st.value.length +
|
||||||
|
" equalsPhrase=" +
|
||||||
|
(st.value === env.phrase) +
|
||||||
|
" resultHidden=" +
|
||||||
|
st.resultHidden +
|
||||||
|
" viewHidden=" +
|
||||||
|
st.viewHidden,
|
||||||
|
);
|
||||||
|
assert(st.viewHidden, "the recovery phrase screen is still on top");
|
||||||
|
assertWiped(st, env.phrase, "after leaving mid-decrypt");
|
||||||
|
});
|
||||||
|
|
||||||
|
// Closing and reopening the page rather than reloading it: that is what
|
||||||
|
// the toolbar popup actually does, and the persisted currentView is
|
||||||
|
// "show-phrase" at the moment it happens, which is precisely the state
|
||||||
|
// RESTORABLE_VIEWS has to refuse.
|
||||||
|
test("reopening the popup never lands on the phrase screen (#161)", async (env) => {
|
||||||
|
await openPhraseScreen(env.page);
|
||||||
|
await revealPhrase(env.page);
|
||||||
|
|
||||||
|
await env.page.close();
|
||||||
|
env.page = await openPopup(env.ctx, env.popupUrl);
|
||||||
|
await visible(env.page, "#view-main");
|
||||||
|
|
||||||
|
const st = await phraseScreenState(env.page);
|
||||||
|
assert(st.viewHidden, "the popup reopened onto the recovery phrase screen");
|
||||||
|
assertWiped(st, env.phrase, "after reopening the popup");
|
||||||
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------- runner
|
// ---------------------------------------------------------------- runner
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
@@ -154,6 +413,9 @@ async function main() {
|
|||||||
popupUrl: session.popupUrl,
|
popupUrl: session.popupUrl,
|
||||||
routeOpts,
|
routeOpts,
|
||||||
page: null,
|
page: null,
|
||||||
|
// The recovery phrase of the wallet created in test 2, so later
|
||||||
|
// tests can assert on the real secret rather than its shape.
|
||||||
|
phrase: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Attribution of collected errors is total. session.errors has no
|
// Attribution of collected errors is total. session.errors has no
|
||||||
|
|||||||
@@ -1,17 +1,24 @@
|
|||||||
// Provide a localStorage mock for Node.js test environment.
|
// Extension storage stub for the Node test environment. The module resolves
|
||||||
// Must be set before requiring the module since it calls loadDeltaFromStorage()
|
// the storage API on use, so this only has to exist before the first call.
|
||||||
// at module load time.
|
// Values round-trip through JSON the way structured cloning would, so a test
|
||||||
const localStorageStore = {};
|
// cannot pass by holding a live reference to the module's own array.
|
||||||
global.localStorage = {
|
const storageStore = {};
|
||||||
getItem: (key) =>
|
global.chrome = {
|
||||||
Object.prototype.hasOwnProperty.call(localStorageStore, key)
|
storage: {
|
||||||
? localStorageStore[key]
|
local: {
|
||||||
: null,
|
get: async (key) =>
|
||||||
setItem: (key, value) => {
|
Object.prototype.hasOwnProperty.call(storageStore, key)
|
||||||
localStorageStore[key] = String(value);
|
? { [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];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
removeItem: (key) => {
|
|
||||||
delete localStorageStore[key];
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -21,19 +28,32 @@ const {
|
|||||||
getBlocklistSize,
|
getBlocklistSize,
|
||||||
getDeltaSize,
|
getDeltaSize,
|
||||||
hostnameVariants,
|
hostnameVariants,
|
||||||
|
DELTA_STORAGE_KEY,
|
||||||
_reset,
|
_reset,
|
||||||
_getVendoredBlacklistSize,
|
_getVendoredBlacklistSize,
|
||||||
_getDeltaBlacklist,
|
_getDeltaBlacklist,
|
||||||
} = require("../src/shared/phishingDomains");
|
} = require("../src/shared/phishingDomains");
|
||||||
|
|
||||||
|
function clearStorage() {
|
||||||
|
for (const key of Object.keys(storageStore)) {
|
||||||
|
delete storageStore[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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");
|
||||||
|
}
|
||||||
|
|
||||||
// Reset delta state before each test to avoid cross-test contamination.
|
// Reset delta state before each test to avoid cross-test contamination.
|
||||||
// Note: vendored sets are immutable and always present.
|
// Note: vendored sets are immutable and always present.
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
_reset();
|
_reset();
|
||||||
// Clear localStorage mock between tests
|
clearStorage();
|
||||||
for (const key of Object.keys(localStorageStore)) {
|
|
||||||
delete localStorageStore[key];
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("phishingDomains", () => {
|
describe("phishingDomains", () => {
|
||||||
@@ -169,15 +189,34 @@ describe("phishingDomains", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("localStorage persistence", () => {
|
describe("extension storage persistence", () => {
|
||||||
test("saveDeltaToStorage persists delta under 256KiB", () => {
|
test("delta is persisted to extension storage, not localStorage", async () => {
|
||||||
loadConfig({
|
await loadConfig({
|
||||||
blacklist: ["persisted-scam-xyz.com"],
|
blacklist: ["persisted-scam-xyz.com"],
|
||||||
});
|
});
|
||||||
const stored = localStorage.getItem("phishing-delta");
|
const stored = storageStore[DELTA_STORAGE_KEY];
|
||||||
expect(stored).not.toBeNull();
|
expect(stored).toBeDefined();
|
||||||
const data = JSON.parse(stored);
|
expect(stored.blacklist).toContain("persisted-scam-xyz.com");
|
||||||
expect(data.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`);
|
||||||
|
}
|
||||||
|
await loadConfig({ blacklist: huge });
|
||||||
|
expect(storageStore[DELTA_STORAGE_KEY]).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("delta is cleared on _reset", () => {
|
test("delta is cleared on _reset", () => {
|
||||||
@@ -203,3 +242,332 @@ describe("phishingDomains", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("phishing list across a service worker restart", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
clearStorage();
|
||||||
|
jest.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
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("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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
clockSpy.mockRestore();
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
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("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;
|
||||||
|
});
|
||||||
|
|
||||||
|
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("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 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("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("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();
|
||||||
|
|
||||||
|
await mod.refreshPhishingListOnSchedule();
|
||||||
|
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
111
tests/settingsUtcTimestamps.test.js
Normal file
111
tests/settingsUtcTimestamps.test.js
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
// Tests for the UTC Timestamps setting.
|
||||||
|
//
|
||||||
|
// The checkbox was moved out of the Token Spam Protection well and into the
|
||||||
|
// Display well next to the theme selector. It is wired by id through the $()
|
||||||
|
// helper, so the move cannot break the handler — but nothing in the suite said
|
||||||
|
// so. These tests pin both halves down: the markup lives in Display and
|
||||||
|
// nowhere else, and the value still round-trips through storage.
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const POPUP_HTML = fs.readFileSync(
|
||||||
|
path.join(__dirname, "..", "src", "popup", "index.html"),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
// The body of one `<div class="bg-well ...">` well, selected by its heading.
|
||||||
|
function wellWithHeading(html, heading) {
|
||||||
|
const headingIndex = html.indexOf(
|
||||||
|
'<h3 class="font-bold mb-1">' + heading + "</h3>",
|
||||||
|
);
|
||||||
|
expect(headingIndex).toBeGreaterThan(-1);
|
||||||
|
const start = html.lastIndexOf('<div class="bg-well', headingIndex);
|
||||||
|
const end = html.indexOf('<div class="bg-well', headingIndex);
|
||||||
|
return html.slice(start, end === -1 ? html.length : end);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("the UTC Timestamps checkbox placement", () => {
|
||||||
|
test("the checkbox appears exactly once in the popup markup", () => {
|
||||||
|
const matches = POPUP_HTML.match(/id="settings-utc-timestamps"/g);
|
||||||
|
expect(matches).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("it renders in the Display well, alongside the theme selector", () => {
|
||||||
|
const display = wellWithHeading(POPUP_HTML, "Display");
|
||||||
|
|
||||||
|
expect(display).toContain('id="settings-utc-timestamps"');
|
||||||
|
expect(display).toContain('id="settings-theme"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test("it does not render in the Token Spam Protection well", () => {
|
||||||
|
const spam = wellWithHeading(POPUP_HTML, "Token Spam Protection");
|
||||||
|
|
||||||
|
expect(spam).not.toContain('id="settings-utc-timestamps"');
|
||||||
|
// The filters that do belong there are untouched.
|
||||||
|
expect(spam).toContain('id="settings-hide-low-holders"');
|
||||||
|
expect(spam).toContain('id="settings-hide-fraud-contracts"');
|
||||||
|
expect(spam).toContain('id="settings-hide-dust"');
|
||||||
|
expect(spam).toContain('id="settings-dust-threshold"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the UTC Timestamps setting round-trips through storage", () => {
|
||||||
|
let store;
|
||||||
|
|
||||||
|
function loadStateModule() {
|
||||||
|
store = {};
|
||||||
|
global.chrome = {
|
||||||
|
storage: {
|
||||||
|
local: {
|
||||||
|
get: async (key) =>
|
||||||
|
key in store ? { [key]: store[key] } : {},
|
||||||
|
set: async (obj) => Object.assign(store, obj),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
jest.resetModules();
|
||||||
|
return require("../src/shared/state");
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete global.chrome;
|
||||||
|
});
|
||||||
|
|
||||||
|
test("defaults to off with nothing persisted", async () => {
|
||||||
|
const { state, loadState } = loadStateModule();
|
||||||
|
|
||||||
|
await loadState();
|
||||||
|
|
||||||
|
expect(state.utcTimestamps).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an enabled checkbox is persisted and read back", async () => {
|
||||||
|
const first = loadStateModule();
|
||||||
|
|
||||||
|
// What the change handler in views/settings.js does.
|
||||||
|
first.state.utcTimestamps = true;
|
||||||
|
await first.saveState();
|
||||||
|
expect(store.autistmask.utcTimestamps).toBe(true);
|
||||||
|
|
||||||
|
// A fresh popup load sees it.
|
||||||
|
jest.resetModules();
|
||||||
|
const second = require("../src/shared/state");
|
||||||
|
expect(second.state.utcTimestamps).toBe(false);
|
||||||
|
await second.loadState();
|
||||||
|
expect(second.state.utcTimestamps).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("turning it back off is persisted too", async () => {
|
||||||
|
const { state, saveState, loadState } = loadStateModule();
|
||||||
|
|
||||||
|
state.utcTimestamps = true;
|
||||||
|
await saveState();
|
||||||
|
state.utcTimestamps = false;
|
||||||
|
await saveState();
|
||||||
|
|
||||||
|
state.utcTimestamps = true;
|
||||||
|
await loadState();
|
||||||
|
expect(state.utcTimestamps).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
94
tests/showPhrase.test.js
Normal file
94
tests/showPhrase.test.js
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
// 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/popup/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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -102,3 +102,60 @@ describe("loadState hasWallet reconciliation", () => {
|
|||||||
expect(mod.state.activeAddress).toBe(ADDRESS);
|
expect(mod.state.activeAddress).toBe(ADDRESS);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The known-symbol spoof filter is a safety filter, so an existing profile
|
||||||
|
// stored before the setting existed must load with it on rather than with
|
||||||
|
// undefined, which would read as off.
|
||||||
|
describe("hideSpoofedSymbols persistence", () => {
|
||||||
|
test("defaults to on with empty storage", async () => {
|
||||||
|
const { mod } = loadModuleWith(null);
|
||||||
|
await mod.loadState();
|
||||||
|
expect(mod.state.hideSpoofedSymbols).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a profile stored without the key loads with it on", async () => {
|
||||||
|
const { mod } = loadModuleWith({ wallets: oneWallet() });
|
||||||
|
await mod.loadState();
|
||||||
|
expect(mod.state.hideSpoofedSymbols).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an explicit false survives the load", async () => {
|
||||||
|
const { mod } = loadModuleWith({
|
||||||
|
wallets: oneWallet(),
|
||||||
|
hideSpoofedSymbols: false,
|
||||||
|
});
|
||||||
|
await mod.loadState();
|
||||||
|
expect(mod.state.hideSpoofedSymbols).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("saveState persists the flag", async () => {
|
||||||
|
const { mod, set } = loadModuleWith(null);
|
||||||
|
mod.state.hideSpoofedSymbols = false;
|
||||||
|
await mod.saveState();
|
||||||
|
expect(set).toHaveBeenCalledWith({
|
||||||
|
autistmask: expect.objectContaining({ hideSpoofedSymbols: false }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the flag round-trips off through save and load", async () => {
|
||||||
|
const first = loadModuleWith(null);
|
||||||
|
first.mod.state.hideSpoofedSymbols = false;
|
||||||
|
await first.mod.saveState();
|
||||||
|
const persisted = first.set.mock.calls[0][0].autistmask;
|
||||||
|
|
||||||
|
const second = loadModuleWith(persisted);
|
||||||
|
await second.mod.loadState();
|
||||||
|
expect(second.mod.state.hideSpoofedSymbols).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the flag round-trips back on through save and load", async () => {
|
||||||
|
const first = loadModuleWith(null);
|
||||||
|
first.mod.state.hideSpoofedSymbols = true;
|
||||||
|
await first.mod.saveState();
|
||||||
|
const persisted = first.set.mock.calls[0][0].autistmask;
|
||||||
|
|
||||||
|
const second = loadModuleWith(persisted);
|
||||||
|
await second.mod.loadState();
|
||||||
|
expect(second.mod.state.hideSpoofedSymbols).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ const ORDINARY_PEER = "0x5aa0f9f1e0a1d0e0e5c1e7ce3b7dbbe9c19f0a11";
|
|||||||
|
|
||||||
// The documented default settings (README.md:810-814, state.js:24-27).
|
// The documented default settings (README.md:810-814, state.js:24-27).
|
||||||
const DEFAULT_FILTERS = {
|
const DEFAULT_FILTERS = {
|
||||||
|
hideSpoofedSymbols: true,
|
||||||
hideLowHolderTokens: true,
|
hideLowHolderTokens: true,
|
||||||
hideFraudContracts: true,
|
hideFraudContracts: true,
|
||||||
hideDustTransactions: true,
|
hideDustTransactions: true,
|
||||||
@@ -329,44 +330,150 @@ describe("known-symbol spoof verification", () => {
|
|||||||
expect(result.newFraudContracts).toEqual([]);
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Documents current behaviour, not desired behaviour: the spoof check
|
// Regression guard (#179): EIP-55 mixed case is a checksum over the
|
||||||
// compares tx.contractAddress against a lowercased known address with
|
// address, not part of its identity, so the contract comparison must be
|
||||||
// ===, so a caller passing a checksummed address for a genuine token has
|
// case-insensitive in both directions — a genuine token in any casing is
|
||||||
// it treated as a spoof. In the app this cannot happen because
|
// genuine, and a spoof cannot escape detection by changing its casing.
|
||||||
// parseTokenTransfer lowercases, but the exported function is not
|
test("a genuine contract in all-lowercase form is not a spoof", () => {
|
||||||
// defensive about it the way the blocklist check is.
|
const tx = tokenTx({ contractAddress: USDC_CONTRACT });
|
||||||
test("current behaviour: a checksummed genuine contract is treated as a spoof", () => {
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
const genuineButChecksummed = tokenTx({
|
|
||||||
contractAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
|
||||||
});
|
|
||||||
const result = filterTransactions([genuineButChecksummed], filters());
|
|
||||||
expect(result.transactions).toEqual([]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Documents current behaviour: README.md:810-814 says all four filters
|
test("a genuine contract in EIP-55 checksummed form is not a spoof", () => {
|
||||||
// "default to on but can be individually disabled". There is no setting
|
const tx = tokenTx({
|
||||||
// for known-symbol verification, and filterTransactions applies it
|
contractAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
|
||||||
// unconditionally, so it cannot be turned off.
|
});
|
||||||
test("current behaviour: spoof filtering cannot be disabled by any setting", () => {
|
const result = filterTransactions([tx], filters());
|
||||||
const allFiltersOff = {
|
expect(result.transactions).toEqual([tx]);
|
||||||
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a genuine contract in all-uppercase form is not a spoof", () => {
|
||||||
|
const tx = tokenTx({
|
||||||
|
contractAddress: "0X" + USDC_CONTRACT.slice(2).toUpperCase(),
|
||||||
|
});
|
||||||
|
const result = filterTransactions([tx], filters());
|
||||||
|
expect(result.transactions).toEqual([tx]);
|
||||||
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a genuinely different contract claiming USDC is still a spoof in any casing", () => {
|
||||||
|
const tx = tokenTx({
|
||||||
|
contractAddress: "0xD05339F9EA5AB9D9F03B9D57F671D2ABD1F55C82",
|
||||||
|
});
|
||||||
|
const result = filterTransactions([tx], filters());
|
||||||
|
expect(result.transactions).toEqual([]);
|
||||||
|
// The recorded fraud contract is normalised, so the persisted
|
||||||
|
// blocklist matches later transfers whatever casing they arrive in.
|
||||||
|
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Turning the other three filters off must not turn this one off: each
|
||||||
|
// filter is independent, and this is the one the README calls out as the
|
||||||
|
// defense against the fake "ETH" attack.
|
||||||
|
test("the check still runs when the other three filters are off", () => {
|
||||||
|
const result = filterTransactions(
|
||||||
|
[fakeEthTokenTransfer()],
|
||||||
|
filters({
|
||||||
hideLowHolderTokens: false,
|
hideLowHolderTokens: false,
|
||||||
hideFraudContracts: false,
|
hideFraudContracts: false,
|
||||||
hideDustTransactions: false,
|
hideDustTransactions: false,
|
||||||
dustThresholdGwei: 1,
|
dustThresholdGwei: 1,
|
||||||
fraudContracts: [],
|
}),
|
||||||
};
|
|
||||||
const result = filterTransactions(
|
|
||||||
[fakeEthTokenTransfer()],
|
|
||||||
allFiltersOff,
|
|
||||||
);
|
);
|
||||||
expect(result.transactions).toEqual([]);
|
expect(result.transactions).toEqual([]);
|
||||||
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
expect(result.newFraudContracts).toEqual([FAKE_ETH_CONTRACT]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("current behaviour: spoof filtering also applies with no filters argument", () => {
|
test("spoof filtering also applies with no filters argument", () => {
|
||||||
const result = filterTransactions([fakeEthTokenTransfer()]);
|
const result = filterTransactions([fakeEthTokenTransfer()]);
|
||||||
expect(result.transactions).toEqual([]);
|
expect(result.transactions).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Fail-safe: unlike the other three flags, an absent hideSpoofedSymbols
|
||||||
|
// leaves the check ON. A caller that forgets the key keeps the wallet's
|
||||||
|
// headline protection; only a user who deliberately switched the setting
|
||||||
|
// off sends an explicit false.
|
||||||
|
test("an absent hideSpoofedSymbols leaves the check on", () => {
|
||||||
|
const result = filterTransactions([fakeEthTokenTransfer()], {
|
||||||
|
fraudContracts: [],
|
||||||
|
});
|
||||||
|
expect(result.transactions).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a truthy-but-not-true hideSpoofedSymbols leaves the check on", () => {
|
||||||
|
const result = filterTransactions(
|
||||||
|
[fakeEthTokenTransfer()],
|
||||||
|
filters({ hideSpoofedSymbols: undefined }),
|
||||||
|
);
|
||||||
|
expect(result.transactions).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("disabling known-symbol spoof verification", () => {
|
||||||
|
test("the spoofed transfer is shown when hideSpoofedSymbols is false", () => {
|
||||||
|
const attack = fakeEthTokenTransfer();
|
||||||
|
const result = filterTransactions(
|
||||||
|
[attack],
|
||||||
|
filters({
|
||||||
|
hideSpoofedSymbols: false,
|
||||||
|
// The blocklist rule would otherwise hide the same row via a
|
||||||
|
// contract this pass had already learned.
|
||||||
|
hideFraudContracts: false,
|
||||||
|
hideLowHolderTokens: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(result.transactions).toEqual([attack]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The blocklist is populated only by this check, so switching the check
|
||||||
|
// off stops the learning too. Leaving learning on would make the setting
|
||||||
|
// a no-op: the contract it recorded would immediately hide the same row
|
||||||
|
// through the fraud-contract rule, which is on by default.
|
||||||
|
test("no fraud contract is learned when hideSpoofedSymbols is false", () => {
|
||||||
|
const result = filterTransactions(
|
||||||
|
[fakeEthTokenTransfer()],
|
||||||
|
filters({ hideSpoofedSymbols: false }),
|
||||||
|
);
|
||||||
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the setting off does not stop the other three rules", () => {
|
||||||
|
const dust = nativeDustTransfer();
|
||||||
|
const lowHolder = tokenTx({
|
||||||
|
symbol: NOVEL_SPAM_SYMBOL,
|
||||||
|
contractAddress: NOVEL_SPAM_CONTRACT,
|
||||||
|
holders: 0,
|
||||||
|
});
|
||||||
|
const result = filterTransactions(
|
||||||
|
[dust, lowHolder],
|
||||||
|
filters({ hideSpoofedSymbols: false }),
|
||||||
|
);
|
||||||
|
expect(result.transactions).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// An already-persisted fraud contract keeps being filtered: the blocklist
|
||||||
|
// rule is a separate setting and is unaffected by this one.
|
||||||
|
test("an already-blocklisted contract is still hidden with the check off", () => {
|
||||||
|
const result = filterTransactions(
|
||||||
|
[fakeEthTokenTransfer()],
|
||||||
|
filters({
|
||||||
|
hideSpoofedSymbols: false,
|
||||||
|
fraudContracts: [FAKE_ETH_CONTRACT],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(result.transactions).toEqual([]);
|
||||||
|
expect(result.newFraudContracts).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a genuine transfer is unaffected by the setting either way", () => {
|
||||||
|
const tx = tokenTx();
|
||||||
|
expect(
|
||||||
|
filterTransactions([tx], filters({ hideSpoofedSymbols: false }))
|
||||||
|
.transactions,
|
||||||
|
).toEqual([tx]);
|
||||||
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
||||||
@@ -412,6 +519,21 @@ describe("low-holder token filtering (the 1,000-holder rule)", () => {
|
|||||||
expect(tx.holders).toBeNull();
|
expect(tx.holders).toBeNull();
|
||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Regression guard (#179): an unknown holder count on a real token — the
|
||||||
|
// explorer rate-limited the call, or a self-hosted instance omits the
|
||||||
|
// field — must not be read as zero holders. Reading it that way hides a
|
||||||
|
// legitimate transfer from the user's history, the same over-filtering
|
||||||
|
// harm as the zero-threshold bug. This pins the `tx.holders !== null`
|
||||||
|
// guard, which no fixture previously reached.
|
||||||
|
test("a token whose holder count is unknown is not filtered", () => {
|
||||||
|
const tx = tokenTx({
|
||||||
|
symbol: NOVEL_SPAM_SYMBOL,
|
||||||
|
contractAddress: NOVEL_SPAM_CONTRACT,
|
||||||
|
holders: null,
|
||||||
|
});
|
||||||
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("fraud contract blocklist", () => {
|
describe("fraud contract blocklist", () => {
|
||||||
@@ -575,21 +697,56 @@ describe("dust threshold filtering", () => {
|
|||||||
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
expect(filterTransactions([tx], filters()).transactions).toEqual([tx]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Documents current behaviour: the threshold is read as
|
// Regression guard (#179): 0 is a real threshold meaning "hide nothing",
|
||||||
// `filters.dustThresholdGwei || 100000`, so a user who sets the threshold
|
// not an absent one. It used to be swallowed by `|| 100000`, so the one
|
||||||
// to 0 (the natural way to ask for no dust filtering while leaving the
|
// value a user would pick to see everything was the one that did not
|
||||||
// toggle on) silently gets the 100,000 gwei default instead.
|
// work.
|
||||||
test("current behaviour: a threshold of 0 falls back to the 100,000 gwei default", () => {
|
test("a threshold of 0 hides nothing, leaving the toggle on", () => {
|
||||||
const result = filterTransactions(
|
const dust = dustOf(50);
|
||||||
[dustOf(50)],
|
const zero = dustOf(0);
|
||||||
|
const opts = filters({ dustThresholdGwei: 0 });
|
||||||
|
expect(filterTransactions([dust], opts).transactions).toEqual([dust]);
|
||||||
|
expect(filterTransactions([zero], opts).transactions).toEqual([zero]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a threshold of 0 agrees with clearing the hide-dust checkbox", () => {
|
||||||
|
const tx = nativeDustTransfer();
|
||||||
|
const thresholdZero = filterTransactions(
|
||||||
|
[tx],
|
||||||
filters({ dustThresholdGwei: 0 }),
|
filters({ dustThresholdGwei: 0 }),
|
||||||
);
|
);
|
||||||
expect(result.transactions).toEqual([]);
|
const toggleOff = filterTransactions(
|
||||||
|
[tx],
|
||||||
|
filters({ hideDustTransactions: false }),
|
||||||
|
);
|
||||||
|
expect(thresholdZero.transactions).toEqual([tx]);
|
||||||
|
expect(toggleOff.transactions).toEqual([tx]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("0, unset and a set threshold are three distinct behaviours", () => {
|
||||||
|
const tx = dustOf(50);
|
||||||
|
expect(
|
||||||
|
filterTransactions([tx], filters({ dustThresholdGwei: 0 }))
|
||||||
|
.transactions,
|
||||||
|
).toEqual([tx]);
|
||||||
|
expect(
|
||||||
|
filterTransactions([tx], filters({ dustThresholdGwei: undefined }))
|
||||||
|
.transactions,
|
||||||
|
).toEqual([]);
|
||||||
|
expect(
|
||||||
|
filterTransactions([tx], filters({ dustThresholdGwei: 40 }))
|
||||||
|
.transactions,
|
||||||
|
).toEqual([tx]);
|
||||||
|
expect(
|
||||||
|
filterTransactions([tx], filters({ dustThresholdGwei: 60 }))
|
||||||
|
.transactions,
|
||||||
|
).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("filter defaults promised by the README and Settings", () => {
|
describe("filter defaults promised by the README and Settings", () => {
|
||||||
test("all three toggles default to on and the threshold to 100,000 gwei", () => {
|
test("all four toggles default to on and the threshold to 100,000 gwei", () => {
|
||||||
|
expect(state.hideSpoofedSymbols).toBe(true);
|
||||||
expect(state.hideLowHolderTokens).toBe(true);
|
expect(state.hideLowHolderTokens).toBe(true);
|
||||||
expect(state.hideFraudContracts).toBe(true);
|
expect(state.hideFraudContracts).toBe(true);
|
||||||
expect(state.hideDustTransactions).toBe(true);
|
expect(state.hideDustTransactions).toBe(true);
|
||||||
@@ -600,10 +757,10 @@ describe("filter defaults promised by the README and Settings", () => {
|
|||||||
expect(state.fraudContracts).toEqual([]);
|
expect(state.fraudContracts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Documents current behaviour: filterTransactions itself defaults every
|
// Documents current behaviour: filterTransactions defaults the other three
|
||||||
// optional filter to off. The "default to on" promise is satisfied by
|
// optional filters to off. Their "default to on" promise is satisfied by
|
||||||
// the state defaults above, which every caller passes in; the pure
|
// the state defaults above, which every caller passes in. Spoof
|
||||||
// function makes no assumption of its own.
|
// verification is the exception and stays on unless explicitly disabled.
|
||||||
test("current behaviour: with no filters argument only spoof filtering runs", () => {
|
test("current behaviour: with no filters argument only spoof filtering runs", () => {
|
||||||
const dust = nativeDustTransfer();
|
const dust = nativeDustTransfer();
|
||||||
const lowHolder = tokenTx({
|
const lowHolder = tokenTx({
|
||||||
|
|||||||
357
tests/txValidation.test.js
Normal file
357
tests/txValidation.test.js
Normal file
@@ -0,0 +1,357 @@
|
|||||||
|
const { parseEther } = require("ethers");
|
||||||
|
const {
|
||||||
|
CODES,
|
||||||
|
FEE_PENDING,
|
||||||
|
FEE_KNOWN,
|
||||||
|
FEE_UNAVAILABLE,
|
||||||
|
feeReserveWei,
|
||||||
|
feeEstimateWei,
|
||||||
|
toFixedPoint,
|
||||||
|
validateTransfer,
|
||||||
|
} = require("../src/shared/txValidation");
|
||||||
|
|
||||||
|
// A plausible mainnet fee: 21000 gas at 20 gwei.
|
||||||
|
const FEE = 21000n * 20000000000n; // 0.00042 ETH
|
||||||
|
|
||||||
|
const GWEI = 1000000000n;
|
||||||
|
const GAS_LIMIT = 21000n;
|
||||||
|
|
||||||
|
describe("toFixedPoint", () => {
|
||||||
|
test("scales human decimals to 18 places", () => {
|
||||||
|
expect(toFixedPoint("1.5")).toBe(parseEther("1.5"));
|
||||||
|
expect(toFixedPoint("0")).toBe(0n);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects values it cannot represent exactly", () => {
|
||||||
|
expect(toFixedPoint("not a number")).toBe(null);
|
||||||
|
expect(toFixedPoint("")).toBe(null);
|
||||||
|
expect(toFixedPoint(null)).toBe(null);
|
||||||
|
// More precision than 18 decimals can hold.
|
||||||
|
expect(toFixedPoint("0.0000000000000000001")).toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("validateTransfer, native ETH", () => {
|
||||||
|
const eth = (over) => ({
|
||||||
|
isErc20: false,
|
||||||
|
amount: "0.5",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_KNOWN,
|
||||||
|
feeWei: FEE,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a send comfortably within balance", () => {
|
||||||
|
const r = validateTransfer(eth());
|
||||||
|
expect(r).toEqual({ canSend: true, codes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks a send whose amount plus fee exceeds the balance", () => {
|
||||||
|
// The whole balance: passes an amount-only check, fails once the fee
|
||||||
|
// is counted. This is the bug this module exists to prevent.
|
||||||
|
const r = validateTransfer(eth({ amount: "1.0", ethBalance: "1.0" }));
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks a send left short by less than one fee", () => {
|
||||||
|
const balance = "1.0";
|
||||||
|
// One wei less headroom than the fee needs.
|
||||||
|
const amount = "0.99958000000000001"; // 1.0 - 0.00042 + 1e-17
|
||||||
|
const r = validateTransfer(eth({ amount, ethBalance: balance }));
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a send that leaves exactly the fee behind", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
eth({ amount: "0.99958", ethBalance: "1.0" }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: true, codes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports plain insufficient balance when the amount alone is too big", () => {
|
||||||
|
const r = validateTransfer(eth({ amount: "2.0", ethBalance: "1.0" }));
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks while the fee estimate is still pending", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
eth({ feeStatus: FEE_PENDING, feeWei: null }),
|
||||||
|
);
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.FEE_PENDING]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks when the fee estimate failed, without assuming zero", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
eth({
|
||||||
|
amount: "1.0",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_UNAVAILABLE,
|
||||||
|
feeWei: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.FEE_UNAVAILABLE]);
|
||||||
|
// A zero fee would have let this exact transfer through.
|
||||||
|
expect(
|
||||||
|
validateTransfer(
|
||||||
|
eth({ amount: "1.0", ethBalance: "1.0", feeWei: 0n }),
|
||||||
|
).canSend,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("still reports an over-balance amount before the estimate lands", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
eth({
|
||||||
|
amount: "2.0",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_PENDING,
|
||||||
|
feeWei: null,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH, CODES.FEE_PENDING]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects an amount it cannot do exact arithmetic on", () => {
|
||||||
|
const r = validateTransfer(eth({ amount: "abc" }));
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.AMOUNT_INVALID]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a negative amount", () => {
|
||||||
|
// A negative amount parses to a perfectly good bigint, so neither
|
||||||
|
// balance comparison can fire: both are trivially false against it.
|
||||||
|
// Left unblocked it clears the screen and then dies at encode time.
|
||||||
|
const r = validateTransfer(
|
||||||
|
eth({ amount: "-1", ethBalance: "1.0", feeWei: 861000000000000n }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
||||||
|
expect(
|
||||||
|
validateTransfer(eth({ amount: "-0.000000000000000001" })),
|
||||||
|
).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("treats a missing balance as zero, not as unlimited", () => {
|
||||||
|
const r = validateTransfer(eth({ ethBalance: undefined }));
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("validateTransfer, ERC-20", () => {
|
||||||
|
const erc20 = (over) => ({
|
||||||
|
isErc20: true,
|
||||||
|
amount: "100.0",
|
||||||
|
tokenBalance: "250.0",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_KNOWN,
|
||||||
|
feeWei: FEE,
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a transfer with tokens to spend and ETH for the fee", () => {
|
||||||
|
expect(validateTransfer(erc20())).toEqual({ canSend: true, codes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("checks the token amount against the token balance", () => {
|
||||||
|
const r = validateTransfer(erc20({ amount: "250.000001" }));
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_TOKEN]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not charge the fee against the token balance", () => {
|
||||||
|
// The full token balance is sendable: the fee is paid in ETH.
|
||||||
|
expect(validateTransfer(erc20({ amount: "250.0" })).canSend).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks when the ETH balance does not cover the fee", () => {
|
||||||
|
const r = validateTransfer(erc20({ ethBalance: "0.0001" }));
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_FOR_FEE]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows a fee exactly equal to the ETH balance", () => {
|
||||||
|
const r = validateTransfer(erc20({ ethBalance: "0.00042" }));
|
||||||
|
expect(r).toEqual({ canSend: true, codes: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reports both shortfalls when tokens and ETH are both short", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
erc20({ amount: "300.0", ethBalance: "0.0" }),
|
||||||
|
);
|
||||||
|
expect(r.codes).toEqual([
|
||||||
|
CODES.INSUFFICIENT_TOKEN,
|
||||||
|
CODES.INSUFFICIENT_ETH_FOR_FEE,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks while the fee estimate is pending or failed", () => {
|
||||||
|
expect(
|
||||||
|
validateTransfer(erc20({ feeStatus: FEE_PENDING, feeWei: null }))
|
||||||
|
.codes,
|
||||||
|
).toEqual([CODES.FEE_PENDING]);
|
||||||
|
expect(
|
||||||
|
validateTransfer(
|
||||||
|
erc20({ feeStatus: FEE_UNAVAILABLE, feeWei: null }),
|
||||||
|
).codes,
|
||||||
|
).toEqual([CODES.FEE_UNAVAILABLE]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a negative token amount", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
erc20({ amount: "-0.5", feeWei: 861000000000000n }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.AMOUNT_INVALID] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("treats a missing token balance as zero", () => {
|
||||||
|
const r = validateTransfer(erc20({ tokenBalance: undefined }));
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_TOKEN]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The reserve a node requires, not the fee the transaction is expected to
|
||||||
|
// actually cost. An unpinned send goes out as type-2, and the node checks it
|
||||||
|
// against maxFeePerGas; reserving gasPrice lets a transaction the node will
|
||||||
|
// reject pass the gate.
|
||||||
|
describe("feeReserveWei", () => {
|
||||||
|
// baseFee 20 gwei, tip 1 gwei: eth_gasPrice reports ~21 gwei, while
|
||||||
|
// ethers populates maxFeePerGas as baseFee * 2 + tip = 41 gwei.
|
||||||
|
const type2 = {
|
||||||
|
gasPrice: 21n * GWEI,
|
||||||
|
maxFeePerGas: 41n * GWEI,
|
||||||
|
maxPriorityFeePerGas: 1n * GWEI,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("reserves gasLimit * maxFeePerGas, not gasLimit * gasPrice", () => {
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(GAS_LIMIT * 41n * GWEI);
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(861000000000000n);
|
||||||
|
// The number the node would not have accepted.
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, type2)).not.toBe(441000000000000n);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("gates out a send the type-2 reserve cannot fund", () => {
|
||||||
|
// Exactly fundable against a gasPrice reserve (0.999559 + 0.000441 is
|
||||||
|
// the whole balance to the wei), and short against the reserve the
|
||||||
|
// node will actually require.
|
||||||
|
const send = {
|
||||||
|
isErc20: false,
|
||||||
|
amount: "0.999559",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_KNOWN,
|
||||||
|
};
|
||||||
|
expect(
|
||||||
|
validateTransfer({
|
||||||
|
...send,
|
||||||
|
feeWei: GAS_LIMIT * type2.gasPrice,
|
||||||
|
}).canSend,
|
||||||
|
).toBe(true);
|
||||||
|
const r = validateTransfer({
|
||||||
|
...send,
|
||||||
|
feeWei: feeReserveWei(GAS_LIMIT, type2),
|
||||||
|
});
|
||||||
|
expect(r.canSend).toBe(false);
|
||||||
|
expect(r.codes).toEqual([CODES.INSUFFICIENT_ETH_WITH_FEE]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back to gasPrice on a network with no type-2 pricing", () => {
|
||||||
|
const legacy = { gasPrice: 21n * GWEI, maxFeePerGas: null };
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, legacy)).toBe(GAS_LIMIT * 21n * GWEI);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns null when no usable price or gas limit is available", () => {
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, { gasPrice: null })).toBe(null);
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, {})).toBe(null);
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, null)).toBe(null);
|
||||||
|
expect(feeReserveWei(21000, type2)).toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The display counterpart of the reserve: what the transaction is expected to
|
||||||
|
// cost. Shown alongside the reserve so the screen neither contradicts the gate
|
||||||
|
// nor quotes the user roughly double what they will pay.
|
||||||
|
describe("feeEstimateWei", () => {
|
||||||
|
const type2 = {
|
||||||
|
gasPrice: 21n * GWEI,
|
||||||
|
maxFeePerGas: 41n * GWEI,
|
||||||
|
maxPriorityFeePerGas: 1n * GWEI,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("estimates gasLimit * gasPrice, below the reserve", () => {
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, type2)).toBe(441000000000000n);
|
||||||
|
expect(feeReserveWei(GAS_LIMIT, type2)).toBe(861000000000000n);
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, type2)).toBeLessThan(
|
||||||
|
feeReserveWei(GAS_LIMIT, type2),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("equals the reserve when the network has no type-2 pricing", () => {
|
||||||
|
const legacy = { gasPrice: 21n * GWEI, maxFeePerGas: null };
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, legacy)).toBe(
|
||||||
|
feeReserveWei(GAS_LIMIT, legacy),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back to maxFeePerGas when there is no gasPrice", () => {
|
||||||
|
const noLegacy = { gasPrice: null, maxFeePerGas: 41n * GWEI };
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, noLegacy)).toBe(
|
||||||
|
feeReserveWei(GAS_LIMIT, noLegacy),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns null on the same unusable inputs as the reserve", () => {
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, {})).toBe(null);
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, null)).toBe(null);
|
||||||
|
expect(feeEstimateWei(GAS_LIMIT, { gasPrice: -1n })).toBe(null);
|
||||||
|
expect(feeEstimateWei(21000, type2)).toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Everything that is not a usable fee blocks exactly as FEE_UNAVAILABLE does.
|
||||||
|
// Each of these previously returned { canSend: true, codes: [] } — counting no
|
||||||
|
// fee at all, on a full-balance send, in the direction that lets money out.
|
||||||
|
describe("validateTransfer, unusable fee input fails closed", () => {
|
||||||
|
const fullBalanceSend = (over) => ({
|
||||||
|
isErc20: false,
|
||||||
|
amount: "1.0",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks a null fee claiming to be known", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: null }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks a known fee that is a number rather than a bigint", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: 420000000000000 }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks an unrecognised fee status", () => {
|
||||||
|
const r = validateTransfer(fullBalanceSend({ feeStatus: "bogus" }));
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks a negative fee", () => {
|
||||||
|
const r = validateTransfer(
|
||||||
|
fullBalanceSend({ feeStatus: FEE_KNOWN, feeWei: -1n }),
|
||||||
|
);
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("blocks an ERC-20 transfer on an unusable fee too", () => {
|
||||||
|
const r = validateTransfer({
|
||||||
|
isErc20: true,
|
||||||
|
amount: "100.0",
|
||||||
|
tokenBalance: "250.0",
|
||||||
|
ethBalance: "1.0",
|
||||||
|
feeStatus: FEE_KNOWN,
|
||||||
|
feeWei: null,
|
||||||
|
});
|
||||||
|
expect(r).toEqual({ canSend: false, codes: [CODES.FEE_UNAVAILABLE] });
|
||||||
|
});
|
||||||
|
});
|
||||||
346
tests/vault.test.js
Normal file
346
tests/vault.test.js
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
// Tests for src/shared/vault.js: the Argon2id + XSalsa20-Poly1305 encryption
|
||||||
|
// that protects recovery phrases and private keys at rest.
|
||||||
|
//
|
||||||
|
// The properties that matter here are the ones whose failure is silent. A
|
||||||
|
// vault that decrypts under the wrong password, that hands back plaintext from
|
||||||
|
// a ciphertext an attacker edited, that reuses a nonce, or that leaves the
|
||||||
|
// recovery phrase readable somewhere in the stored blob all look exactly like
|
||||||
|
// a working vault from the UI. So each test below asserts a negative: the
|
||||||
|
// thing that must not happen.
|
||||||
|
//
|
||||||
|
// Cost: every encrypt and decrypt runs one Argon2id pwhash at the production
|
||||||
|
// interactive parameters, which the module hardcodes. The parameters are not
|
||||||
|
// weakened or overridden anywhere in this file — they are pinned by the "key
|
||||||
|
// derivation cost" tests, since they are the vault's only defence against an
|
||||||
|
// offline attack on a stolen blob. The suite is kept inside script/test's
|
||||||
|
// 30-second budget by sharing one encrypted fixture across the tamper cases
|
||||||
|
// instead of re-encrypting per test.
|
||||||
|
|
||||||
|
const sodium = require("libsodium-wrappers-sumo");
|
||||||
|
const {
|
||||||
|
encryptWithPassword,
|
||||||
|
decryptWithPassword,
|
||||||
|
} = require("../src/shared/vault");
|
||||||
|
|
||||||
|
// A publicly known development phrase. Never fund it.
|
||||||
|
const SECRET = "test test test test test test test test test test test junk";
|
||||||
|
const PASSWORD = "correct horse battery staple";
|
||||||
|
const WRONG_PASSWORD = "correct horse battery stapl";
|
||||||
|
|
||||||
|
const SALT_BYTES = 16;
|
||||||
|
const NONCE_BYTES = 24;
|
||||||
|
const POLY1305_TAG_BYTES = 16;
|
||||||
|
|
||||||
|
const BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
||||||
|
|
||||||
|
function b64decode(s) {
|
||||||
|
return sodium.from_base64(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A shallow copy with one field replaced, so the shared fixture is never
|
||||||
|
// mutated by a tamper test.
|
||||||
|
function withField(blob, field, value) {
|
||||||
|
return { ...blob, [field]: value };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flip the low bit of one byte of a base64-encoded field.
|
||||||
|
function flipByte(b64, index) {
|
||||||
|
const bytes = b64decode(b64);
|
||||||
|
bytes[index] ^= 0x01;
|
||||||
|
return sodium.to_base64(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
let vault;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await sodium.ready;
|
||||||
|
vault = await encryptWithPassword(SECRET, PASSWORD);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("stored blob shape", () => {
|
||||||
|
test("is exactly the documented { salt, nonce, ciphertext }", () => {
|
||||||
|
expect(Object.keys(vault).sort()).toEqual([
|
||||||
|
"ciphertext",
|
||||||
|
"nonce",
|
||||||
|
"salt",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("every field is a base64 string", () => {
|
||||||
|
for (const field of ["salt", "nonce", "ciphertext"]) {
|
||||||
|
expect(typeof vault[field]).toBe("string");
|
||||||
|
expect(vault[field]).toMatch(BASE64);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("salt and nonce are full length", () => {
|
||||||
|
expect(b64decode(vault.salt)).toHaveLength(SALT_BYTES);
|
||||||
|
expect(b64decode(vault.nonce)).toHaveLength(NONCE_BYTES);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ciphertext carries a Poly1305 authentication tag", () => {
|
||||||
|
expect(b64decode(vault.ciphertext)).toHaveLength(
|
||||||
|
SECRET.length + POLY1305_TAG_BYTES,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the blob survives JSON storage unchanged", async () => {
|
||||||
|
const stored = JSON.parse(JSON.stringify(vault));
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(stored, PASSWORD)).resolves.toBe(
|
||||||
|
SECRET,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("no plaintext leakage", () => {
|
||||||
|
test("the secret does not appear in the serialized vault", () => {
|
||||||
|
const serialized = JSON.stringify(vault);
|
||||||
|
|
||||||
|
expect(serialized).not.toContain(SECRET);
|
||||||
|
for (const word of new Set(SECRET.split(" "))) {
|
||||||
|
expect(serialized).not.toContain(word);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the ciphertext bytes do not contain the secret bytes", () => {
|
||||||
|
const bytes = Buffer.from(b64decode(vault.ciphertext));
|
||||||
|
|
||||||
|
expect(bytes.includes(Buffer.from(SECRET, "utf8"))).toBe(false);
|
||||||
|
// Not even the first word, which would betray an unencrypted prefix.
|
||||||
|
expect(bytes.includes(Buffer.from("test test", "utf8"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the password does not appear in the serialized vault", () => {
|
||||||
|
expect(JSON.stringify(vault)).not.toContain(PASSWORD);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("round trip", () => {
|
||||||
|
test("decrypts back to the original secret", async () => {
|
||||||
|
await expect(decryptWithPassword(vault, PASSWORD)).resolves.toBe(
|
||||||
|
SECRET,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("survives a non-ASCII plaintext byte for byte", async () => {
|
||||||
|
const unicode = "recovery phrase é中文\u{1f600}";
|
||||||
|
|
||||||
|
const blob = await encryptWithPassword(unicode, PASSWORD);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(blob, PASSWORD)).resolves.toBe(
|
||||||
|
unicode,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an empty password still round-trips and is not a bypass", async () => {
|
||||||
|
const blob = await encryptWithPassword(SECRET, "");
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(blob, "")).resolves.toBe(SECRET);
|
||||||
|
// An empty password must not act as a skeleton key on other vaults,
|
||||||
|
// nor may a real password open an empty-password vault.
|
||||||
|
await expect(decryptWithPassword(vault, "")).rejects.toThrow();
|
||||||
|
await expect(decryptWithPassword(blob, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("fresh salt and nonce", () => {
|
||||||
|
test("two encryptions of the same plaintext differ in all three fields", async () => {
|
||||||
|
const second = await encryptWithPassword(SECRET, PASSWORD);
|
||||||
|
|
||||||
|
expect(second.salt).not.toBe(vault.salt);
|
||||||
|
expect(second.nonce).not.toBe(vault.nonce);
|
||||||
|
expect(second.ciphertext).not.toBe(vault.ciphertext);
|
||||||
|
await expect(decryptWithPassword(second, PASSWORD)).resolves.toBe(
|
||||||
|
SECRET,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("key derivation cost", () => {
|
||||||
|
// Argon2id's opslimit and memlimit are the whole of the vault's resistance
|
||||||
|
// to an offline attack on a stolen blob, and lowering them breaks nothing
|
||||||
|
// any other test here can see — the suite merely runs faster. So pin them
|
||||||
|
// directly, both to libsodium's INTERACTIVE constants and to the absolute
|
||||||
|
// values those constants must keep meaning.
|
||||||
|
const INTERACTIVE_OPSLIMIT = 2;
|
||||||
|
const INTERACTIVE_MEMLIMIT = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
test("the interactive constants still mean 2 passes over 64 MiB", () => {
|
||||||
|
expect(sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE).toBe(
|
||||||
|
INTERACTIVE_OPSLIMIT,
|
||||||
|
);
|
||||||
|
expect(sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE).toBe(
|
||||||
|
INTERACTIVE_MEMLIMIT,
|
||||||
|
);
|
||||||
|
// The floor these must never quietly be swapped for: _MIN is one pass
|
||||||
|
// over 8 KiB, an 8192x reduction in memory cost.
|
||||||
|
expect(sodium.crypto_pwhash_OPSLIMIT_MIN).toBeLessThan(
|
||||||
|
INTERACTIVE_OPSLIMIT,
|
||||||
|
);
|
||||||
|
expect(sodium.crypto_pwhash_MEMLIMIT_MIN).toBeLessThan(
|
||||||
|
INTERACTIVE_MEMLIMIT,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a key derived at the interactive parameters opens the vault", () => {
|
||||||
|
// Independent of any spy, and of the module's own code path: derive
|
||||||
|
// the key here from the vault's published salt at the interactive cost
|
||||||
|
// and open its ciphertext directly. A vault whose key came from any
|
||||||
|
// other opslimit, memlimit or Argon2id variant yields a different key
|
||||||
|
// and cannot be opened this way.
|
||||||
|
const key = sodium.crypto_pwhash(
|
||||||
|
sodium.crypto_secretbox_KEYBYTES,
|
||||||
|
PASSWORD,
|
||||||
|
b64decode(vault.salt),
|
||||||
|
INTERACTIVE_OPSLIMIT,
|
||||||
|
INTERACTIVE_MEMLIMIT,
|
||||||
|
sodium.crypto_pwhash_ALG_ARGON2ID13,
|
||||||
|
);
|
||||||
|
const opened = sodium.crypto_secretbox_open_easy(
|
||||||
|
b64decode(vault.ciphertext),
|
||||||
|
b64decode(vault.nonce),
|
||||||
|
key,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sodium.to_string(opened)).toBe(SECRET);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
[
|
||||||
|
"encrypt",
|
||||||
|
async () => {
|
||||||
|
await encryptWithPassword(SECRET, PASSWORD);
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"decrypt",
|
||||||
|
async () => {
|
||||||
|
await decryptWithPassword(vault, PASSWORD);
|
||||||
|
},
|
||||||
|
],
|
||||||
|
])("%s derives exactly one key at the interactive cost", async (_, run) => {
|
||||||
|
const spy = jest.spyOn(sodium, "crypto_pwhash");
|
||||||
|
try {
|
||||||
|
await run();
|
||||||
|
|
||||||
|
expect(spy).toHaveBeenCalledTimes(1);
|
||||||
|
const [keyBytes, , salt, opslimit, memlimit, alg] =
|
||||||
|
spy.mock.calls[0];
|
||||||
|
expect(keyBytes).toBe(sodium.crypto_secretbox_KEYBYTES);
|
||||||
|
expect(salt).toHaveLength(SALT_BYTES);
|
||||||
|
expect(opslimit).toBe(sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE);
|
||||||
|
expect(memlimit).toBe(sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE);
|
||||||
|
expect(alg).toBe(sodium.crypto_pwhash_ALG_ARGON2ID13);
|
||||||
|
} finally {
|
||||||
|
spy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("wrong password", () => {
|
||||||
|
test("is rejected, and rejects cleanly", async () => {
|
||||||
|
// rejects.toThrow asserts a rejected promise, not a synchronous throw
|
||||||
|
// and not an unhandled rejection: the caller can catch this.
|
||||||
|
await expect(
|
||||||
|
decryptWithPassword(vault, WRONG_PASSWORD),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns no plaintext, not even partially", async () => {
|
||||||
|
const result = await decryptWithPassword(vault, WRONG_PASSWORD).catch(
|
||||||
|
(err) => err,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBeInstanceOf(Error);
|
||||||
|
expect(String(result)).not.toContain("test");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the empty password is rejected on a password-protected vault", async () => {
|
||||||
|
await expect(decryptWithPassword(vault, "")).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("tampering", () => {
|
||||||
|
test("a flipped ciphertext bit is rejected by the auth tag", async () => {
|
||||||
|
const tampered = withField(
|
||||||
|
vault,
|
||||||
|
"ciphertext",
|
||||||
|
flipByte(vault.ciphertext, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a flipped bit in the authentication tag itself is rejected", async () => {
|
||||||
|
const tagStart = b64decode(vault.ciphertext).length - 1;
|
||||||
|
const tampered = withField(
|
||||||
|
vault,
|
||||||
|
"ciphertext",
|
||||||
|
flipByte(vault.ciphertext, tagStart),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a flipped nonce bit is rejected", async () => {
|
||||||
|
const tampered = withField(vault, "nonce", flipByte(vault.nonce, 0));
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a flipped salt bit is rejected", async () => {
|
||||||
|
const tampered = withField(vault, "salt", flipByte(vault.salt, 0));
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a truncated ciphertext is rejected", async () => {
|
||||||
|
const bytes = b64decode(vault.ciphertext);
|
||||||
|
const tampered = withField(
|
||||||
|
vault,
|
||||||
|
"ciphertext",
|
||||||
|
sodium.to_base64(bytes.slice(0, bytes.length - 4)),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a ciphertext shorter than the auth tag is rejected", async () => {
|
||||||
|
const tampered = withField(
|
||||||
|
vault,
|
||||||
|
"ciphertext",
|
||||||
|
sodium.to_base64(b64decode(vault.ciphertext).slice(0, 4)),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a truncated nonce is rejected", async () => {
|
||||||
|
const tampered = withField(
|
||||||
|
vault,
|
||||||
|
"nonce",
|
||||||
|
sodium.to_base64(b64decode(vault.nonce).slice(0, NONCE_BYTES - 1)),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(tampered, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a ciphertext from another vault is rejected", async () => {
|
||||||
|
const other = await encryptWithPassword("a different secret", PASSWORD);
|
||||||
|
const spliced = withField(vault, "ciphertext", other.ciphertext);
|
||||||
|
|
||||||
|
await expect(decryptWithPassword(spliced, PASSWORD)).rejects.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a missing field is rejected rather than decrypted", async () => {
|
||||||
|
for (const field of ["salt", "nonce", "ciphertext"]) {
|
||||||
|
const broken = { ...vault };
|
||||||
|
delete broken[field];
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
decryptWithPassword(broken, PASSWORD),
|
||||||
|
).rejects.toThrow();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
// Tests for the DEBUG build flag as it gates mnemonic generation.
|
// Tests for src/shared/wallet.js: the DEBUG build flag as it gates mnemonic
|
||||||
|
// generation (first two describes), and HD key derivation against published
|
||||||
|
// known-answer vectors (rest of the file).
|
||||||
//
|
//
|
||||||
// The modules read the __BUILD_DEBUG__ global that esbuild replaces at bundle
|
// The modules read the __BUILD_DEBUG__ global that esbuild replaces at bundle
|
||||||
// time. Under jest the global is absent, which is exactly the release-build
|
// time. Under jest the global is absent, which is exactly the release-build
|
||||||
@@ -92,3 +94,449 @@ describe("generateMnemonic in a debug build", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Key derivation.
|
||||||
|
//
|
||||||
|
// Every address below is a published constant, not something this codebase
|
||||||
|
// produced. Asserting against what the implementation happens to return today
|
||||||
|
// would pass just as happily with the wrong coin type, the wrong path depth or
|
||||||
|
// a non-empty seed passphrase, all of which silently send funds to addresses
|
||||||
|
// no other wallet can recover.
|
||||||
|
//
|
||||||
|
// Vector sources:
|
||||||
|
//
|
||||||
|
// VECTOR_PHRASE / VECTOR_ADDRESSES / VECTOR_PRIVATE_KEYS — the standard
|
||||||
|
// development recovery phrase and the first three accounts it yields at
|
||||||
|
// m/44'/60'/0'/0/n with an empty seed passphrase, as published in the
|
||||||
|
// Hardhat and Ganache documentation. Publicly known; never fund it.
|
||||||
|
//
|
||||||
|
// ZERO_ENTROPY_PHRASE / ZERO_ENTROPY_ADDRESS — the BIP-39 all-zero-entropy
|
||||||
|
// phrase (Trezor's official BIP-39 vector set, first entry) and its
|
||||||
|
// m/44'/60'/0'/0/0 Ethereum address with an empty seed passphrase. A second,
|
||||||
|
// independently published phrase so the pin is not one vector deep.
|
||||||
|
//
|
||||||
|
// BIP32_VECTOR_1_XPRV — the master key of BIP-32 test vector 1
|
||||||
|
// (seed 000102030405060708090a0b0c0d0e0f).
|
||||||
|
//
|
||||||
|
// The two Hardhat facts cross-check each other: VECTOR_PRIVATE_KEYS[n] is the
|
||||||
|
// published key for VECTOR_ADDRESSES[n], so addressFromPrivateKey and the HD
|
||||||
|
// path must meet at the same address from two different directions.
|
||||||
|
|
||||||
|
const { HDNodeWallet, Mnemonic, verifyMessage } = require("ethers");
|
||||||
|
const wallet = require("../src/shared/wallet");
|
||||||
|
const { BIP44_ETH_PATH } = require("../src/shared/constants");
|
||||||
|
|
||||||
|
const VECTOR_PHRASE =
|
||||||
|
"test test test test test test test test test test test junk";
|
||||||
|
|
||||||
|
const VECTOR_ADDRESSES = [
|
||||||
|
"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
|
||||||
|
"0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
|
||||||
|
"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
|
||||||
|
];
|
||||||
|
|
||||||
|
const VECTOR_PRIVATE_KEYS = [
|
||||||
|
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
|
||||||
|
"0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d",
|
||||||
|
"0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a",
|
||||||
|
];
|
||||||
|
|
||||||
|
const ZERO_ENTROPY_PHRASE =
|
||||||
|
"abandon abandon abandon abandon abandon abandon " +
|
||||||
|
"abandon abandon abandon abandon abandon about";
|
||||||
|
const ZERO_ENTROPY_ADDRESS = "0x9858EfFD232B4033E47d90003D41EC34EcaEda94";
|
||||||
|
|
||||||
|
const BIP32_VECTOR_1_XPRV =
|
||||||
|
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqji" +
|
||||||
|
"ChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi";
|
||||||
|
|
||||||
|
// The master (depth-0) extended private key for a phrase, which is what the
|
||||||
|
// import-an-xprv flow is handed. Built with ethers rather than with the module
|
||||||
|
// under test, so hdWalletFromXprv is not being checked against itself.
|
||||||
|
function masterXprv(phrase, passphrase = "") {
|
||||||
|
return HDNodeWallet.fromSeed(
|
||||||
|
Mnemonic.fromPhrase(phrase, passphrase).computeSeed(),
|
||||||
|
).extendedKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The account-level (depth-3) extended private key m/44'/60'/0' for a phrase.
|
||||||
|
// A normal thing for a user to hold, and not something the import flow can
|
||||||
|
// derive the BIP-44 account path from.
|
||||||
|
function accountXprv(phrase) {
|
||||||
|
return HDNodeWallet.fromSeed(
|
||||||
|
Mnemonic.fromPhrase(phrase, "").computeSeed(),
|
||||||
|
).derivePath("m/44'/60'/0'").extendedKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every single-character substitution of `key`, using base58 characters that
|
||||||
|
// are not the original. Base58 has no visually ambiguous characters, so each
|
||||||
|
// of these is a plausible typo rather than a contrived string.
|
||||||
|
const TYPO_CHARS = ["a", "b", "2", "Z"];
|
||||||
|
|
||||||
|
function singleCharacterTypos(key) {
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i < key.length; i++) {
|
||||||
|
for (const c of TYPO_CHARS) {
|
||||||
|
if (c === key[i]) continue;
|
||||||
|
out.push(key.slice(0, i) + c + key.slice(i + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("hdWalletFromMnemonic", () => {
|
||||||
|
test("first address matches the published vector for m/44'/60'/0'/0/0", () => {
|
||||||
|
expect(wallet.hdWalletFromMnemonic(VECTOR_PHRASE).firstAddress).toBe(
|
||||||
|
VECTOR_ADDRESSES[0],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("second published phrase derives its published address", () => {
|
||||||
|
expect(
|
||||||
|
wallet.hdWalletFromMnemonic(ZERO_ENTROPY_PHRASE).firstAddress,
|
||||||
|
).toBe(ZERO_ENTROPY_ADDRESS);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns the account-level xpub, which is watch-only", () => {
|
||||||
|
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
|
||||||
|
expect(xpub.startsWith("xpub")).toBe(true);
|
||||||
|
// A neutered ethers node exposes no private key at all, so accept
|
||||||
|
// either absent or null rather than pinning which.
|
||||||
|
expect(
|
||||||
|
HDNodeWallet.fromExtendedKey(xpub).privateKey ?? null,
|
||||||
|
).toBeNull();
|
||||||
|
expect(wallet.isValidXprv(xpub)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the account path is the documented BIP-44 Ethereum path", () => {
|
||||||
|
expect(BIP44_ETH_PATH).toBe("m/44'/60'/0'/0");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects an invalid recovery phrase rather than deriving from it", () => {
|
||||||
|
expect(() => wallet.hdWalletFromMnemonic("not a phrase")).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("deriveAddressFromXpub", () => {
|
||||||
|
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
|
||||||
|
test.each([0, 1, 2])(
|
||||||
|
"child %i matches the published vector address",
|
||||||
|
(index) => {
|
||||||
|
expect(wallet.deriveAddressFromXpub(xpub, index)).toBe(
|
||||||
|
VECTOR_ADDRESSES[index],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("agrees with hdWalletFromMnemonic at index 0", () => {
|
||||||
|
expect(wallet.deriveAddressFromXpub(xpub, 0)).toBe(
|
||||||
|
wallet.hdWalletFromMnemonic(VECTOR_PHRASE).firstAddress,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects garbage instead of returning an address", () => {
|
||||||
|
expect(() =>
|
||||||
|
wallet.deriveAddressFromXpub("xpub-nonsense", 0),
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("hdWalletFromMnemonic seed passphrase handling", () => {
|
||||||
|
// The vectors above are only reproducible with an empty BIP-39 seed
|
||||||
|
// passphrase. This pins that the empty string reaching
|
||||||
|
// HDNodeWallet.fromPhrase is load-bearing: with any passphrase applied the
|
||||||
|
// published address is unreachable, and a wallet derived that way could
|
||||||
|
// not be restored anywhere else from the phrase alone.
|
||||||
|
test("a non-empty seed passphrase would yield a different address", () => {
|
||||||
|
const withPassphrase = HDNodeWallet.fromPhrase(
|
||||||
|
VECTOR_PHRASE,
|
||||||
|
"TREZOR",
|
||||||
|
BIP44_ETH_PATH,
|
||||||
|
).deriveChild(0).address;
|
||||||
|
|
||||||
|
expect(withPassphrase).not.toBe(VECTOR_ADDRESSES[0]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("hdWalletFromXprv", () => {
|
||||||
|
// hdWalletFromMnemonic derives the absolute path "m/44'/60'/0'/0" while
|
||||||
|
// hdWalletFromXprv derives the relative path "44'/60'/0'/0". For a
|
||||||
|
// depth-0 master key the two are the same derivation; these tests pin that
|
||||||
|
// equivalence to a published address rather than assuming it.
|
||||||
|
test("master xprv for the vector phrase yields the vector address", () => {
|
||||||
|
expect(
|
||||||
|
wallet.hdWalletFromXprv(masterXprv(VECTOR_PHRASE)).firstAddress,
|
||||||
|
).toBe(VECTOR_ADDRESSES[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("agrees with hdWalletFromMnemonic on xpub and address", () => {
|
||||||
|
const fromPhrase = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
const fromXprv = wallet.hdWalletFromXprv(masterXprv(VECTOR_PHRASE));
|
||||||
|
|
||||||
|
expect(fromXprv).toEqual(fromPhrase);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("derived xpub generates the same child addresses", () => {
|
||||||
|
const { xpub } = wallet.hdWalletFromXprv(masterXprv(VECTOR_PHRASE));
|
||||||
|
|
||||||
|
expect(
|
||||||
|
[0, 1, 2].map((i) => wallet.deriveAddressFromXpub(xpub, i)),
|
||||||
|
).toEqual(VECTOR_ADDRESSES);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("accepts the BIP-32 test vector 1 master key", () => {
|
||||||
|
const { xpub, firstAddress } =
|
||||||
|
wallet.hdWalletFromXprv(BIP32_VECTOR_1_XPRV);
|
||||||
|
|
||||||
|
expect(xpub.startsWith("xpub")).toBe(true);
|
||||||
|
expect(firstAddress).toMatch(/^0x[0-9a-fA-F]{40}$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects a watch-only xpub", () => {
|
||||||
|
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
|
||||||
|
expect(() => wallet.hdWalletFromXprv(xpub)).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects garbage", () => {
|
||||||
|
expect(() => wallet.hdWalletFromXprv("nonsense")).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isValidXprv", () => {
|
||||||
|
test.each([
|
||||||
|
["BIP-32 test vector 1 master key", BIP32_VECTOR_1_XPRV, true],
|
||||||
|
["the empty string", "", false],
|
||||||
|
["garbage", "not-a-key", false],
|
||||||
|
["a bare private key", VECTOR_PRIVATE_KEYS[0], false],
|
||||||
|
["a truncated xprv", BIP32_VECTOR_1_XPRV.slice(0, -6), false],
|
||||||
|
["an xprv with an extra character", BIP32_VECTOR_1_XPRV + "a", false],
|
||||||
|
])("%s -> %s", (_name, key, expected) => {
|
||||||
|
expect(wallet.isValidXprv(key)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a watch-only xpub is not an xprv", () => {
|
||||||
|
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
|
||||||
|
expect(wallet.isValidXprv(xpub)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects an extended key with a one-character typo", () => {
|
||||||
|
const index = BIP32_VECTOR_1_XPRV.length - 8;
|
||||||
|
const typo =
|
||||||
|
BIP32_VECTOR_1_XPRV.slice(0, index) +
|
||||||
|
(BIP32_VECTOR_1_XPRV[index] === "a" ? "b" : "a") +
|
||||||
|
BIP32_VECTOR_1_XPRV.slice(index + 1);
|
||||||
|
|
||||||
|
expect(wallet.isValidXprv(typo)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The base58 checksum exists to make a mistyped key impossible to use, and
|
||||||
|
// ethers does not enforce it: HDNodeWallet.fromExtendedKey skips checksum
|
||||||
|
// verification whenever the decoded payload is the usual 82 bytes, which
|
||||||
|
// is precisely the case it is there to catch. A typo anywhere in the key
|
||||||
|
// must be refused, not silently turned into someone else's wallet.
|
||||||
|
test("no single-character typo anywhere in the key is accepted", () => {
|
||||||
|
const accepted = singleCharacterTypos(BIP32_VECTOR_1_XPRV).filter(
|
||||||
|
(typo) => wallet.isValidXprv(typo),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(accepted).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a typo never yields a wallet, let alone a different one", () => {
|
||||||
|
const correct = wallet.hdWalletFromXprv(BIP32_VECTOR_1_XPRV);
|
||||||
|
const derived = [];
|
||||||
|
for (const typo of singleCharacterTypos(BIP32_VECTOR_1_XPRV)) {
|
||||||
|
try {
|
||||||
|
derived.push(wallet.hdWalletFromXprv(typo).firstAddress);
|
||||||
|
} catch {
|
||||||
|
// Rejected, which is the required behaviour.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(derived).toEqual([]);
|
||||||
|
expect(correct.firstAddress).toBe(
|
||||||
|
"0x022b971dFF0C43305e691DEd7a14367AF19D6407",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("extended key depth", () => {
|
||||||
|
// hdWalletFromXprv derives the BIP-44 Ethereum account path from the key
|
||||||
|
// it is given. That is only the path it names when the key is the master
|
||||||
|
// key. Under an account-level key the same derivation lands at
|
||||||
|
// m/44'/60'/0'/44'/60'/0'/0, whose addresses correspond to nothing the
|
||||||
|
// user holds, so a non-master key is refused rather than derived from.
|
||||||
|
test("a master key is a master key", () => {
|
||||||
|
expect(wallet.isMasterExtendedKey(masterXprv(VECTOR_PHRASE))).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
expect(wallet.isMasterExtendedKey(BIP32_VECTOR_1_XPRV)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an account-level key is not a master key", () => {
|
||||||
|
expect(wallet.isMasterExtendedKey(accountXprv(VECTOR_PHRASE))).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a derived xpub is not a master key", () => {
|
||||||
|
expect(
|
||||||
|
wallet.isMasterExtendedKey(
|
||||||
|
wallet.hdWalletFromMnemonic(VECTOR_PHRASE).xpub,
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a mistyped key is not a master key either", () => {
|
||||||
|
expect(wallet.isMasterExtendedKey(BIP32_VECTOR_1_XPRV + "a")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hdWalletFromXprv rejects an account-level key", () => {
|
||||||
|
expect(() =>
|
||||||
|
wallet.hdWalletFromXprv(accountXprv(VECTOR_PHRASE)),
|
||||||
|
).toThrow(/master/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getSignerForAddress rejects an account-level key", () => {
|
||||||
|
expect(() =>
|
||||||
|
wallet.getSignerForAddress(
|
||||||
|
{ type: "xprv" },
|
||||||
|
0,
|
||||||
|
accountXprv(VECTOR_PHRASE),
|
||||||
|
),
|
||||||
|
).toThrow(/master/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the account-level key is well-formed, so only depth rejects it", () => {
|
||||||
|
expect(wallet.isValidXprv(accountXprv(VECTOR_PHRASE))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a master key still imports and derives the published addresses", () => {
|
||||||
|
const { xpub, firstAddress } = wallet.hdWalletFromXprv(
|
||||||
|
masterXprv(VECTOR_PHRASE),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(firstAddress).toBe(VECTOR_ADDRESSES[0]);
|
||||||
|
expect(
|
||||||
|
[0, 1, 2].map((i) => wallet.deriveAddressFromXpub(xpub, i)),
|
||||||
|
).toEqual(VECTOR_ADDRESSES);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("deriveAddressFromXpub checksum enforcement", () => {
|
||||||
|
// The xpub path shares the hole: fromExtendedKey accepts a mistyped xpub
|
||||||
|
// just as readily, and deriveAddressFromXpub would hand back addresses
|
||||||
|
// from a different tree.
|
||||||
|
const { xpub } = wallet.hdWalletFromMnemonic(VECTOR_PHRASE);
|
||||||
|
|
||||||
|
test("the correct xpub still derives the published addresses", () => {
|
||||||
|
expect(wallet.deriveAddressFromXpub(xpub, 0)).toBe(VECTOR_ADDRESSES[0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("no single-character typo anywhere in an xpub is accepted", () => {
|
||||||
|
const derived = [];
|
||||||
|
for (const typo of singleCharacterTypos(xpub)) {
|
||||||
|
try {
|
||||||
|
derived.push(wallet.deriveAddressFromXpub(typo, 0));
|
||||||
|
} catch {
|
||||||
|
// Rejected, which is the required behaviour.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(derived).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isValidMnemonic", () => {
|
||||||
|
test.each([
|
||||||
|
["the vector phrase", VECTOR_PHRASE, true],
|
||||||
|
["the BIP-39 zero-entropy phrase", ZERO_ENTROPY_PHRASE, true],
|
||||||
|
[
|
||||||
|
"a 12-word phrase with a bad checksum",
|
||||||
|
"abandon abandon abandon abandon abandon abandon " +
|
||||||
|
"abandon abandon abandon abandon abandon abandon",
|
||||||
|
false,
|
||||||
|
],
|
||||||
|
["an 11-word phrase", "abandon ".repeat(10) + "about", false],
|
||||||
|
["a word outside the wordlist", VECTOR_PHRASE + " zzzzzz", false],
|
||||||
|
["the empty string", "", false],
|
||||||
|
["garbage", "correct horse battery staple", false],
|
||||||
|
])("%s -> %s", (_name, phrase, expected) => {
|
||||||
|
expect(wallet.isValidMnemonic(phrase)).toBe(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("addressFromPrivateKey", () => {
|
||||||
|
test.each([0, 1, 2])(
|
||||||
|
"published key %i yields its published address",
|
||||||
|
(index) => {
|
||||||
|
expect(
|
||||||
|
wallet.addressFromPrivateKey(VECTOR_PRIVATE_KEYS[index]),
|
||||||
|
).toBe(VECTOR_ADDRESSES[index]);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("rejects a key of the wrong length", () => {
|
||||||
|
expect(() => wallet.addressFromPrivateKey("0xdeadbeef")).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects the empty string", () => {
|
||||||
|
expect(() => wallet.addressFromPrivateKey("")).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getSignerForAddress", () => {
|
||||||
|
test.each([0, 1, 2])("hd wallet, address index %i", (index) => {
|
||||||
|
const signer = wallet.getSignerForAddress(
|
||||||
|
{ type: "hd" },
|
||||||
|
index,
|
||||||
|
VECTOR_PHRASE,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(signer.address).toBe(VECTOR_ADDRESSES[index]);
|
||||||
|
expect(signer.privateKey).toBe(VECTOR_PRIVATE_KEYS[index]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([0, 1, 2])("xprv wallet, address index %i", (index) => {
|
||||||
|
const signer = wallet.getSignerForAddress(
|
||||||
|
{ type: "xprv" },
|
||||||
|
index,
|
||||||
|
masterXprv(VECTOR_PHRASE),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(signer.address).toBe(VECTOR_ADDRESSES[index]);
|
||||||
|
expect(signer.privateKey).toBe(VECTOR_PRIVATE_KEYS[index]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("single private key ignores the address index", () => {
|
||||||
|
for (const index of [0, 1, 2]) {
|
||||||
|
const signer = wallet.getSignerForAddress(
|
||||||
|
{ type: "privkey" },
|
||||||
|
index,
|
||||||
|
VECTOR_PRIVATE_KEYS[1],
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(signer.address).toBe(VECTOR_ADDRESSES[1]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the returned signer signs recoverably as the expected address", async () => {
|
||||||
|
const signer = wallet.getSignerForAddress(
|
||||||
|
{ type: "hd" },
|
||||||
|
1,
|
||||||
|
VECTOR_PHRASE,
|
||||||
|
);
|
||||||
|
const message = "AutistMask derivation test";
|
||||||
|
|
||||||
|
const signature = await signer.signMessage(message);
|
||||||
|
|
||||||
|
expect(verifyMessage(message, signature)).toBe(VECTOR_ADDRESSES[1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user