Compare commits
7 Commits
issue-312-
...
958e92d753
| Author | SHA1 | Date | |
|---|---|---|---|
| 958e92d753 | |||
| 769f6a5289 | |||
| 669c443bf9 | |||
| 12b0c4d1c6 | |||
| c36d8b6ddf | |||
| cef6aaab11 | |||
| 20e911059a |
@@ -4,3 +4,4 @@
|
|||||||
node_modules
|
node_modules
|
||||||
.DS_Store
|
.DS_Store
|
||||||
dist
|
dist
|
||||||
|
release
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -23,6 +23,9 @@ node_modules/
|
|||||||
# Build output
|
# Build output
|
||||||
dist/
|
dist/
|
||||||
|
|
||||||
|
# Release artifacts (make package). Derived from dist/, never committed.
|
||||||
|
release/
|
||||||
|
|
||||||
# Yarn
|
# Yarn
|
||||||
.yarn-integrity
|
.yarn-integrity
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
yarn.lock
|
yarn.lock
|
||||||
dist/
|
dist/
|
||||||
|
release/
|
||||||
.claude/
|
.claude/
|
||||||
|
|||||||
25
Makefile
25
Makefile
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: bootstrap setup install test test-e2e test-e2e-firefox lint fmt fmt-check check check-censored docker hooks build build-debug vendor-blocklist clean dev
|
.PHONY: bootstrap setup install test test-e2e test-e2e-firefox lint fmt fmt-check check check-censored docker hooks build build-debug package vendor-blocklist clean dev
|
||||||
|
|
||||||
# Standard targets are thin shims; the implementations live in script/
|
# Standard targets are thin shims; the implementations live in script/
|
||||||
# per the scripts-to-rule-them-all pattern (see the Entrypoints section
|
# per the scripts-to-rule-them-all pattern (see the Entrypoints section
|
||||||
@@ -41,6 +41,9 @@ check:
|
|||||||
check-censored:
|
check-censored:
|
||||||
@script/check-censored
|
@script/check-censored
|
||||||
|
|
||||||
|
package:
|
||||||
|
@script/package
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
@script/docker
|
@script/docker
|
||||||
|
|
||||||
@@ -60,19 +63,31 @@ hooks:
|
|||||||
# scrubbed from the build itself: with AUTISTMASK_DEBUG=1 exported, this target
|
# scrubbed from the build itself: with AUTISTMASK_DEBUG=1 exported, this target
|
||||||
# compiles a debug bundle and then fails on it, loudly, rather than quietly
|
# compiles a debug bundle and then fails on it, loudly, rather than quietly
|
||||||
# handing back something other than the release build that was asked for.
|
# handing back something other than the release build that was asked for.
|
||||||
|
#
|
||||||
|
# Every step of this target is wrapped in script/discard-dist-on-failure, so a
|
||||||
|
# release build that fails removes dist/ instead of leaving a complete, loadable
|
||||||
|
# debug bundle there for whoever runs the build, sees it fail, and loads
|
||||||
|
# dist/chrome/ anyway. A step that succeeds removes nothing, and build-debug is
|
||||||
|
# deliberately not wrapped.
|
||||||
build:
|
build:
|
||||||
@echo "Building extension..."
|
@echo "Building extension..."
|
||||||
@set -eu; \
|
@set -eu; \
|
||||||
receipt="$$(mktemp "$${TMPDIR:-/tmp}/autistmask-build-receipt.XXXXXX")"; \
|
receipt="$$(mktemp "$${TMPDIR:-/tmp}/autistmask-build-receipt.XXXXXX")"; \
|
||||||
trap 'rm -f "$$receipt"' EXIT INT TERM; \
|
trap 'rm -f "$$receipt"' EXIT INT TERM; \
|
||||||
AUTISTMASK_BUILD_RECEIPT="$$receipt" yarn run build 2>&1; \
|
script/discard-dist-on-failure \
|
||||||
env -u AUTISTMASK_DEBUG script/verify-build --expect release \
|
env AUTISTMASK_BUILD_RECEIPT="$$receipt" yarn run build 2>&1; \
|
||||||
|
script/discard-dist-on-failure \
|
||||||
|
env -u AUTISTMASK_DEBUG script/verify-build --expect release \
|
||||||
--receipt "$$receipt"
|
--receipt "$$receipt"
|
||||||
@script/check-censored --require-dist
|
@script/discard-dist-on-failure script/check-censored --require-dist
|
||||||
|
|
||||||
# Development-only build: enables the red DEBUG / INSECURE banner and makes
|
# Development-only build: enables the red DEBUG / INSECURE banner and makes
|
||||||
# the hardcoded test recovery phrase the output of wallet creation. Never
|
# the hardcoded test recovery phrase the output of wallet creation. Never
|
||||||
# distribute the artifacts this produces.
|
# distribute the artifacts this produces.
|
||||||
|
#
|
||||||
|
# No discard-dist-on-failure here, on purpose: a debug build that fails is not
|
||||||
|
# producing an artifact anyone could mistake for a release one, and its dist/ is
|
||||||
|
# the evidence of what went wrong.
|
||||||
build-debug:
|
build-debug:
|
||||||
@echo "Building extension (DEBUG)..."
|
@echo "Building extension (DEBUG)..."
|
||||||
@set -eu; \
|
@set -eu; \
|
||||||
@@ -90,7 +105,7 @@ vendor-blocklist:
|
|||||||
@script/vendor-blocklist
|
@script/vendor-blocklist
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
@rm -rf dist/
|
@rm -rf dist/ release/
|
||||||
|
|
||||||
dev:
|
dev:
|
||||||
@echo "Building in watch mode..."
|
@echo "Building in watch mode..."
|
||||||
|
|||||||
267
README.md
267
README.md
@@ -44,7 +44,107 @@ Load the extension:
|
|||||||
- **Chrome**: Navigate to `chrome://extensions/`, enable "Developer mode", click
|
- **Chrome**: Navigate to `chrome://extensions/`, enable "Developer mode", click
|
||||||
"Load unpacked", and select the `dist/chrome/` directory.
|
"Load unpacked", and select the `dist/chrome/` directory.
|
||||||
- **Firefox**: Navigate to `about:debugging#/runtime/this-firefox`, click "Load
|
- **Firefox**: Navigate to `about:debugging#/runtime/this-firefox`, click "Load
|
||||||
Temporary Add-on", and select `dist/firefox/manifest.json`.
|
Temporary Add-on", and select `dist/firefox/manifest.json`. Read
|
||||||
|
[Installing on Firefox](#installing-on-firefox) before relying on this: a
|
||||||
|
temporary add-on does not survive closing the browser.
|
||||||
|
|
||||||
|
### Release Artifacts
|
||||||
|
|
||||||
|
`make package` runs `make build` and then writes one self-contained, versioned
|
||||||
|
archive per browser into `release/`, plus a `SHA256SUMS` for them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make package
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
release/autistmask-chrome-<version>.zip
|
||||||
|
release/autistmask-firefox-<version>.xpi
|
||||||
|
release/SHA256SUMS
|
||||||
|
```
|
||||||
|
|
||||||
|
Nothing is published by this. Tagging, CRX packing and any upload are
|
||||||
|
outward-facing acts and are the owner's alone.
|
||||||
|
|
||||||
|
The archives are deterministic — entries sorted, timestamps fixed, compression
|
||||||
|
level fixed — so two builds of one commit produce byte-identical files and the
|
||||||
|
recorded digest is a property of the input rather than of the clock.
|
||||||
|
|
||||||
|
**Self-containment is checked, not assumed.** `build.js` writes the compiled
|
||||||
|
Tailwind output to `dist/styles.css` at the `dist/` ROOT, outside both browser
|
||||||
|
directories, and copies it into each of them as `src/popup/styles.css`; a naive
|
||||||
|
`zip -r dist/chrome` is therefore correct only by accident. So the packager
|
||||||
|
resolves every path referenced by the manifest and by every HTML document in the
|
||||||
|
archive, requires each to be inside the archive, and fails on any reference that
|
||||||
|
climbs out of the extension root. Files left at the `dist/` root are printed as
|
||||||
|
deliberately not shipped rather than dropped by a glob. The archive is then read
|
||||||
|
back off disk and compared member by member against the directory it was built
|
||||||
|
from: an archive nobody opened is a claim, not an artifact.
|
||||||
|
|
||||||
|
There is one version, and the build enforces it. `package.json`,
|
||||||
|
`manifest/chrome.json` and `manifest/firefox.json` each declare one and none is
|
||||||
|
derived from another — the manifests are copied to `dist/` verbatim, which is
|
||||||
|
what `tests/manifest.test.js` asserts — so `script/lib/version.js` requires all
|
||||||
|
three to agree and **fails the build when they do not**, naming each file and
|
||||||
|
what it said. `tests/version.test.js` covers that rule in `make check`.
|
||||||
|
|
||||||
|
### Installing on Chrome
|
||||||
|
|
||||||
|
`manifest/chrome.json` carries a fixed `key`: the public half of an RSA keypair,
|
||||||
|
base64-encoded DER. It exists for one reason. An unpacked Chrome extension with
|
||||||
|
no `key` gets an extension id derived from the **absolute path it was loaded
|
||||||
|
from**, and `chrome.storage.local` — which is where the wallet lives — is
|
||||||
|
partitioned by that id. Move the checkout, re-clone it, or load a second copy
|
||||||
|
from anywhere else, and the extension comes up on a fresh, empty storage
|
||||||
|
partition: the wallet is simply gone, with no error and nothing in the UI to say
|
||||||
|
so. With the `key` in place the id is derived from the key instead, and follows
|
||||||
|
the extension wherever it is loaded from. That id is
|
||||||
|
`gipbhkogfopeahplcjhipkgpcimdpkip`, pinned in `tests/extensionId.test.js` and
|
||||||
|
observed against a real Chrome in `tests/e2e/storagePartition.js`.
|
||||||
|
|
||||||
|
**Changing `key` changes the extension id, and orphans every wallet stored under
|
||||||
|
the old one.** It is a migration, not an edit.
|
||||||
|
|
||||||
|
The **private** half is a credential. It is not in this repository, no target
|
||||||
|
generates one into the working tree, `*.pem` and `*.key` are gitignored, and
|
||||||
|
`tests/extensionId.test.js` fails if such a file is ever committed. It is not
|
||||||
|
needed to build, load or test anything here — it signs a CRX, and this repo does
|
||||||
|
not pack one. A packer would take it from outside the repo, e.g.
|
||||||
|
`chrome --pack-extension=dist/chrome --pack-extension-key=<path to the .pem>`.
|
||||||
|
|
||||||
|
### Installing on Firefox
|
||||||
|
|
||||||
|
**The XPI this repo produces is UNSIGNED, and release Firefox and Firefox ESR
|
||||||
|
will refuse to install it.** Those builds enforce add-on signing with no working
|
||||||
|
override — `xpinstall.signatures.required` does nothing on them — so a permanent
|
||||||
|
install needs Firefox Developer Edition, Nightly, or an Unbranded build, with
|
||||||
|
`xpinstall.signatures.required` set to `false` in `about:config`.
|
||||||
|
|
||||||
|
Signing means submitting to AMO (self-distribution is enough, and does not
|
||||||
|
require listing), which needs credentials this repository does not have and is
|
||||||
|
the owner's decision.
|
||||||
|
|
||||||
|
The other route is `about:debugging#/runtime/this-firefox` -> "Load Temporary
|
||||||
|
Add-on", which works on every Firefox including release. **A temporary add-on is
|
||||||
|
unloaded when Firefox exits**, so daily use means re-adding it by hand on every
|
||||||
|
browser start.
|
||||||
|
|
||||||
|
**The wallet survives the restart.** `manifest/firefox.json` declares a fixed
|
||||||
|
`browser_specific_settings.gecko.id`, and Firefox keys the extension's storage
|
||||||
|
area on that id rather than on the install, so adding the temporary add-on again
|
||||||
|
in the same profile finds the vault where it left it. That is asserted, not
|
||||||
|
assumed: `tests/e2e/firefox/reinstall.js` installs the packaged XPI in a real
|
||||||
|
Firefox, creates a wallet through the UI, quits the browser, starts it again on
|
||||||
|
the same profile, adds the add-on again, and decrypts the vault with the
|
||||||
|
original password back to the original recovery phrase. The `moz-extension://`
|
||||||
|
origin the popup is served from is _not_ stable across installs and does not
|
||||||
|
need to be — nothing durable is keyed on it.
|
||||||
|
|
||||||
|
**Removing the add-on does not.** An explicit uninstall — about:addons "Remove"
|
||||||
|
— destroys the extension's storage, and the vault with it. That is ordinary,
|
||||||
|
correct browser behaviour and it is observed in the same suite, but for a wallet
|
||||||
|
it is worth saying out loud: **on Firefox, Remove is irreversible, and the
|
||||||
|
recovery phrase is the only way back.**
|
||||||
|
|
||||||
### Debug Builds
|
### Debug Builds
|
||||||
|
|
||||||
@@ -63,8 +163,12 @@ that runs `make build`, that target compiles a debug bundle and then **fails**,
|
|||||||
because it tells `script/verify-build` in so many words that it was supposed to
|
because it tells `script/verify-build` in so many words that it was supposed to
|
||||||
produce a release build. It used to be that the verifier read the same variable
|
produce a release build. It used to be that the verifier read the same variable
|
||||||
out of its own environment, agreed with itself, and reported a debug artifact as
|
out of its own environment, agreed with itself, and reported a debug artifact as
|
||||||
verified. The build prints which mode it used. See the
|
verified. The build prints which mode it used. A release build that fails also
|
||||||
[DEBUG Mode Policy](#debug-mode-policy) for what the flag changes. **Never
|
**removes `dist/`**, and says so: the bundle it had already written is loadable,
|
||||||
|
and a loud failure is no protection against someone loading `dist/chrome/`
|
||||||
|
anyway. `make build-debug` keeps its `dist/` on failure — that output is not
|
||||||
|
mistakable for a release build, and it is the evidence of what went wrong. See
|
||||||
|
the [DEBUG Mode Policy](#debug-mode-policy) for what the flag changes. **Never
|
||||||
distribute a debug build** — every wallet it creates gets the same publicly
|
distribute a debug build** — every wallet it creates gets the same publicly
|
||||||
known test recovery phrase.
|
known test recovery phrase.
|
||||||
|
|
||||||
@@ -81,17 +185,21 @@ lives.
|
|||||||
one of the bundles containing `src/shared/constants.js` — into a build receipt,
|
one of the bundles containing `src/shared/constants.js` — into a build receipt,
|
||||||
and `script/verify-build` checks `dist/` against that receipt: every recorded
|
and `script/verify-build` checks `dist/` against that receipt: every recorded
|
||||||
file present with exactly the recorded bytes, every audited bundle carrying the
|
file present with exactly the recorded bytes, every audited bundle carrying the
|
||||||
requested `DEBUG` marker, and nothing under `dist/` that the build did not
|
requested `DEBUG` marker, and no regular file or symlink under `dist/` that the
|
||||||
write. The `Makefile` creates the receipt path with `mktemp` per invocation,
|
build did not write. The `Makefile` creates the receipt path with `mktemp` per
|
||||||
outside the repo, and deletes it afterwards.
|
invocation, outside the repo, and deletes it afterwards.
|
||||||
|
|
||||||
That is what ties the check to a build rather than to a directory. What it
|
That is what ties the check to a build rather than to a directory. What it
|
||||||
establishes is narrow and worth stating exactly: `dist/` is byte for byte the
|
establishes is narrow and worth stating exactly: `dist/` is byte for byte the
|
||||||
output of the `build.js` run that just finished, with nothing added, removed or
|
output of the `build.js` run that just finished, with no regular file or symlink
|
||||||
altered in between. It establishes nothing about whether the source tree or
|
added, removed or altered in between. Regular files and symlinks are the whole
|
||||||
`build.js` were honest, and it offers nothing to someone handed a `dist/` from
|
of what the tree walk covers; fifos, sockets, device nodes and empty directories
|
||||||
elsewhere — without the receipt from its own build there is no input to the
|
under `dist/` are not checked, because a build emits none of them, none can
|
||||||
check. Verifiable provenance for a third party is signing, which this is not.
|
carry a shippable payload, and `grep` on a fifo would hang rather than fail. It
|
||||||
|
establishes nothing about whether the source tree or `build.js` were honest, and
|
||||||
|
it offers nothing to someone handed a `dist/` from elsewhere — without the
|
||||||
|
receipt from its own build there is no input to the check. Verifiable provenance
|
||||||
|
for a third party is signing, which this is not.
|
||||||
|
|
||||||
There is deliberately no target that re-verifies an existing `dist/` on its own.
|
There is deliberately no target that re-verifies an existing `dist/` on its own.
|
||||||
The list of files to check has to come from the build that produced them; read
|
The list of files to check has to come from the build that produced them; read
|
||||||
@@ -138,31 +246,45 @@ provide:
|
|||||||
fails anywhere else. Part of `make check`, which inspects `dist/` when there
|
fails anywhere else. Part of `make check`, which inspects `dist/` when there
|
||||||
is one and says loudly when there is not; `make build` re-runs it with
|
is one and says loudly when there is not; `make build` re-runs it with
|
||||||
`--require-dist`, so a build artifact is always covered
|
`--require-dist`, so a build artifact is always covered
|
||||||
|
- `script/package` — produce the release artifacts: `make build` first, so the
|
||||||
|
archives can only ever be made from a `dist/` that has been verified against
|
||||||
|
that build's own receipt as a RELEASE build, then one self-contained,
|
||||||
|
versioned archive per browser into `release/` (see
|
||||||
|
[Release Artifacts](#release-artifacts)). It packages and does not publish
|
||||||
- `script/vendor-blocklist` — refresh `src/shared/phishingBlocklist.json` from
|
- `script/vendor-blocklist` — refresh `src/shared/phishingBlocklist.json` from
|
||||||
its upstream, pinned to a commit and to the sha256 of the bytes that commit
|
its upstream, pinned to a commit and to the sha256 of the bytes that commit
|
||||||
serves. Run deliberately, never as part of a build: the output is committed
|
serves. Run deliberately, never as part of a build: the output is committed
|
||||||
and there is no runtime fetch, so the shipped list is as fresh as the last
|
and there is no runtime fetch, so the shipped list is as fresh as the last
|
||||||
vendoring run that was released
|
vendoring run that was released
|
||||||
- `script/verify-build --expect release|debug --receipt PATH` — assert that
|
- `script/verify-build --expect release|debug --receipt PATH` — assert that the
|
||||||
`dist/` is exactly what the build that just ran emitted, and that the compiled
|
regular files and symlinks under `dist/` are exactly what the build that just
|
||||||
`DEBUG` state of the bundles in it is the one that was asked for. Both
|
ran emitted (other file types are out of scope), and that the compiled `DEBUG`
|
||||||
arguments are required and neither has a default: the expected mode is stated
|
state of the bundles in it is the one that was asked for. Both arguments are
|
||||||
by the caller rather than read from `AUTISTMASK_DEBUG`, and the file list
|
required and neither has a default: the expected mode is stated by the caller
|
||||||
comes from the build's receipt rather than from `dist/` (see
|
rather than read from `AUTISTMASK_DEBUG`, and the file list comes from the
|
||||||
|
build's receipt rather than from `dist/` (see
|
||||||
[Build Receipts](#build-receipts)). Run automatically at the end of
|
[Build Receipts](#build-receipts)). Run automatically at the end of
|
||||||
`make build` and `make build-debug`; fails loudly rather than passing whenever
|
`make build` and `make build-debug`; fails loudly rather than passing whenever
|
||||||
it cannot determine something. Not part of `make check`, which does not depend
|
it cannot determine something. Not part of `make check`, which does not depend
|
||||||
on build artifacts existing.
|
on build artifacts existing.
|
||||||
|
- `script/discard-dist-on-failure COMMAND [ARG...]` — run one step of the
|
||||||
|
**release** build and, if it fails, remove `dist/` before returning that
|
||||||
|
step's exit status, saying on stderr that it did and why. Every step of
|
||||||
|
`make build` runs through it; `make build-debug` runs none of them through it.
|
||||||
|
A step that succeeds removes nothing, and a removal that cannot be completed
|
||||||
|
is reported as loudly as one that was
|
||||||
- `script/test-verify-build` — exercise every failure mode of
|
- `script/test-verify-build` — exercise every failure mode of
|
||||||
`script/verify-build` against a fixture tree in a temp dir, asserting the exit
|
`script/verify-build` against a fixture tree in a temp dir, asserting the exit
|
||||||
status and the message of each, and read the `make build` and
|
status and the message of each, assert the state of `dist/` on disk after a
|
||||||
|
failing and a succeeding release build step, and read the `make build` and
|
||||||
`make build-debug` recipes back out of `make -n` to check that they pass the
|
`make build-debug` recipes back out of `make -n` to check that they pass the
|
||||||
mode as an argument on a scrubbed environment. Part of `make check`; it reads
|
mode as an argument on a scrubbed environment and wrap only the release path.
|
||||||
no build artifacts and writes nothing under `dist/`. The cases that depend on
|
Part of `make check`; it reads no build artifacts and writes nothing under
|
||||||
file permissions cannot mean anything for a process that is not subject to
|
`dist/`. The cases that depend on file permissions cannot mean anything for a
|
||||||
them, so the harness proves its runner against a mode-000 file before counting
|
process that is not subject to them, so the harness proves its runner against
|
||||||
them, dropping to an unprivileged user when run as root; if it cannot, it
|
a mode-000 file before counting them, dropping to an unprivileged user when
|
||||||
skips those cases and says so in a banner rather than passing them.
|
run as root; if it cannot, it skips those cases and says so in a banner rather
|
||||||
|
than passing them.
|
||||||
- `script/docker` — build the Docker image tagged via `script/projectname`
|
- `script/docker` — build the Docker image tagged via `script/projectname`
|
||||||
- `script/cibuild` — CI entrypoint: plain `docker build .`
|
- `script/cibuild` — CI entrypoint: plain `docker build .`
|
||||||
- `script/precommit` — run by the git pre-commit hook; runs `script/check`
|
- `script/precommit` — run by the git pre-commit hook; runs `script/check`
|
||||||
@@ -176,10 +298,12 @@ The Makefile shims to those. It also carries a few targets that have no
|
|||||||
silently rewritten. Use `make setup` for a fresh clone.
|
silently rewritten. Use `make setup` for a fresh clone.
|
||||||
- `make hooks` — shims to `script/install-precommit`
|
- `make hooks` — shims to `script/install-precommit`
|
||||||
- `make build` — build the extension into `dist/chrome/` and `dist/firefox/`,
|
- `make build` — build the extension into `dist/chrome/` and `dist/firefox/`,
|
||||||
then verify the result against the build's receipt as a release build
|
then verify the result against the build's receipt as a release build. A
|
||||||
|
failure at any step removes `dist/`
|
||||||
- `make build-debug` — the same build with `AUTISTMASK_DEBUG=1`, verified as a
|
- `make build-debug` — the same build with `AUTISTMASK_DEBUG=1`, verified as a
|
||||||
debug build (see [Debug Builds](#debug-builds))
|
debug build, and keeping its `dist/` on failure (see
|
||||||
- `make clean` — remove `dist/`
|
[Debug Builds](#debug-builds))
|
||||||
|
- `make clean` — remove `dist/` and `release/`
|
||||||
- `make dev` — build in watch mode
|
- `make dev` — build in watch mode
|
||||||
|
|
||||||
## End-to-End Tests
|
## End-to-End Tests
|
||||||
@@ -315,6 +439,23 @@ class before a browser is involved, so this suite is no longer the only thing
|
|||||||
standing between it and a release — but a static rule only sees identifiers, and
|
standing between it and a release — but a static rule only sees identifiers, and
|
||||||
the runtime errors this suite catches are broader than one rule.
|
the runtime errors this suite catches are broader than one rule.
|
||||||
|
|
||||||
|
`make test-e2e` then runs a second program in the same image,
|
||||||
|
`tests/e2e/storagePartition.js`, which answers where `chrome.storage.local`
|
||||||
|
lives. It loads the built extension from one temporary directory in a fresh
|
||||||
|
profile, writes a sentinel key the extension itself never touches, closes the
|
||||||
|
browser, and loads a **copy at a different path into the same profile** — then
|
||||||
|
does it again with `key` stripped out of the manifest, and reports what each
|
||||||
|
pair actually did rather than what it expected. It needs its own browser
|
||||||
|
sessions, four of them, because the whole subject is what happens ACROSS loads.
|
||||||
|
|
||||||
|
The observed behaviour, on the pinned Chromium: **with `key`, both paths get the
|
||||||
|
same extension id and the second load reads the first load's storage. Without
|
||||||
|
`key`, the two paths get different ids and the second load sees an empty
|
||||||
|
partition** — the wallet, silently gone. Loading both keyed copies at once in
|
||||||
|
one profile yields a single extension id, not two: Chrome does not load a second
|
||||||
|
copy of an id it already has. The assertions are annotated as observations, so a
|
||||||
|
Chrome that ever changes this fails the run instead of passing it.
|
||||||
|
|
||||||
### Firefox (`make test-e2e-firefox`)
|
### Firefox (`make test-e2e-firefox`)
|
||||||
|
|
||||||
`make test-e2e-firefox` builds `dist/firefox/` and drives the **real popup in a
|
`make test-e2e-firefox` builds `dist/firefox/` and drives the **real popup in a
|
||||||
@@ -332,6 +473,33 @@ runner rather than believed from the extension, and the stub node has to answer
|
|||||||
`eth_sendRawTransaction` with the hash `ethers` computes for the artifact it
|
`eth_sendRawTransaction` with the hash `ethers` computes for the artifact it
|
||||||
sent, or `provider.broadcastTransaction()` refuses the answer.
|
sent, or `provider.broadcastTransaction()` refuses the answer.
|
||||||
|
|
||||||
|
`make test-e2e-firefox` then runs a second program in the same image,
|
||||||
|
`tests/e2e/firefox/reinstall.js`, and it installs the **packaged XPI** rather
|
||||||
|
than the unpacked directory — the only place a real Firefox is asked to load the
|
||||||
|
artifact that would actually be handed to someone. It runs two browsers over one
|
||||||
|
profile, because it asks two questions that have different answers:
|
||||||
|
|
||||||
|
- **Restart.** Install, create a wallet through the UI, record the vault, quit
|
||||||
|
the browser, start it again on the same profile, add the add-on again. The
|
||||||
|
extension must not come up as a fresh install; the vault, xpub and first
|
||||||
|
address must be unchanged; and the vault must still **decrypt** with the
|
||||||
|
original password to the original recovery phrase, through the real Show
|
||||||
|
Recovery Phrase screen. "The ciphertext is still in storage" and "the wallet
|
||||||
|
still works" are different claims and only the second one is worth anything.
|
||||||
|
This is what a user does every day, because a temporary add-on is unloaded
|
||||||
|
when Firefox exits.
|
||||||
|
- **Removal.** Then, in the same browser, an explicit uninstall and a fresh
|
||||||
|
install. Observed: **Firefox destroys the extension's storage on uninstall**,
|
||||||
|
so the vault is gone. Recorded as an assertion, so a Firefox that ever changes
|
||||||
|
it fails the run, and stated in
|
||||||
|
[Installing on Firefox](#installing-on-firefox) because for a wallet it means
|
||||||
|
Remove is irreversible except from the recovery phrase.
|
||||||
|
|
||||||
|
It also pins down something worth knowing about the harness: the
|
||||||
|
`moz-extension://` uuid the popup is served from is not stable across installs,
|
||||||
|
and navigating to a stale one does not fail — it hangs. The program reads the
|
||||||
|
live uuid out of `extensions.webextensions.uuids` after every install.
|
||||||
|
|
||||||
Both suites build their own image, each with the repo and a fresh extension
|
Both suites build their own image, each with the repo and a fresh extension
|
||||||
build baked in; what differs is the base. The Chrome image layers those on top
|
build baked in; what differs is the base. The Chrome image layers those on top
|
||||||
of a published Playwright image, whereas this one is assembled from a `node`
|
of a published Playwright image, whereas this one is assembled from a `node`
|
||||||
@@ -689,6 +857,51 @@ Both are click-copyable. Truncating to 4 decimals in summary views is acceptable
|
|||||||
for scannability, but the detail view must never discard precision — it is the
|
for scannability, but the detail view must never discard precision — it is the
|
||||||
one place the user can always use to verify exact details.
|
one place the user can always use to verify exact details.
|
||||||
|
|
||||||
|
**Specific Exception — nonzero floor on the approval screens:** A nonzero amount
|
||||||
|
must never render as zero. Truncating to 4 decimals does exactly that to an
|
||||||
|
amount below 0.0001 — 1 base unit of an 18-decimal token, 500 base units of an
|
||||||
|
8-decimal one — and on the dApp approval screen and the wait/success/error
|
||||||
|
screens that carry its amount forward, a real transfer or allowance then reads
|
||||||
|
as "nothing is being moved". A swap's `Min. received` is the sharper case: a
|
||||||
|
slippage floor shown as `0.0000` states that the swap may return nothing.
|
||||||
|
|
||||||
|
On those screens, when the truncated string would contain no digit from 1 to 9
|
||||||
|
and the value does, the amount is extended to its first significant digit
|
||||||
|
instead: `0.000000000000000001 DAI`, not `0.0000 DAI`. The test is on the whole
|
||||||
|
truncated string, integer part included, so `1.00005` still shows as `1.0000` —
|
||||||
|
the exception only fires where the entire displayed figure would read as zero. A
|
||||||
|
genuine zero still renders `0.0000`, and truncation stays truncation: `0.99999`
|
||||||
|
shows as `0.9999`, never rounded up.
|
||||||
|
|
||||||
|
The rule and its exception live in `src/shared/amountDisplay.js` as
|
||||||
|
`truncateAmount()` and `truncateAmountNeverZero()`. Everything the approval and
|
||||||
|
confirmation screens display goes through the floored one — the ERC-20 amount,
|
||||||
|
the ETH value and max fee (`src/popup/views/approval.js`), and the swap's
|
||||||
|
`Amount` and `Min. received` lines (`src/shared/uniswap.js`). The history and
|
||||||
|
balance lists (`src/shared/transactions.js`) use the unfloored one: the
|
||||||
|
transaction detail view is the authoritative record and already shows exact
|
||||||
|
precision. The 4-decimal rule is unchanged everywhere else, including for
|
||||||
|
amounts at or above the floor on the approval screens.
|
||||||
|
|
||||||
|
The floor applies only where the token's scale is known. Where it is not, the
|
||||||
|
approval screen states base units instead of a quantity — see Unknown token
|
||||||
|
scale below — and no truncation happens at all.
|
||||||
|
|
||||||
|
**Specific Exception — unknown token scale:** Calldata carries base units and no
|
||||||
|
scale, so every amount on the dApp approval screen needs the token's `decimals`.
|
||||||
|
It is resolved from the bundled token list, then from the tokens the user
|
||||||
|
tracks, then from what the block explorer reported for the contract
|
||||||
|
(`resolveTokenDecimals()` in `src/shared/approvalAmount.js`). Where none of them
|
||||||
|
answers, the amount is not formatted: the line reads
|
||||||
|
`5000000000 base units (decimals unknown)`. A guessed scale is not an
|
||||||
|
approximation but a different number — 1,000 units of a 6-decimal token
|
||||||
|
formatted at 18 decimals reads `0.000000001` — on the screen whose only job is
|
||||||
|
to state what is being authorized. Both amount paths of that screen take this
|
||||||
|
rule: the ERC-20 `transfer`/`approve` line (`src/popup/views/approval.js`) and
|
||||||
|
the swap's `Amount` and `Min. received` lines (`src/shared/uniswap.js`). An
|
||||||
|
unbounded allowance or permit needs no scale to describe and is still shown as
|
||||||
|
`Unlimited`.
|
||||||
|
|
||||||
#### Partial USD totals
|
#### Partial USD totals
|
||||||
|
|
||||||
Prices are fetched for the top 25 tokens only, so an address can hold assets the
|
Prices are fetched for the top 25 tokens only, so an address can hold assets the
|
||||||
|
|||||||
116
TODO.md
116
TODO.md
@@ -26,7 +26,8 @@ milestone is in flight on `next`; its `next` -> `main` PR is
|
|||||||
[#190](https://git.eeqj.de/sneak/AutistMask/pulls/190). `make check` verified
|
[#190](https://git.eeqj.de/sneak/AutistMask/pulls/190). `make check` verified
|
||||||
green on `next` at `e9fa8be` on 2026-08-10, and `make build` produces
|
green on `next` at `e9fa8be` on 2026-08-10, and `make build` produces
|
||||||
`dist/chrome/` and `dist/firefox/`, verified against the build's own receipt to
|
`dist/chrome/` and `dist/firefox/`, verified against the build's own receipt to
|
||||||
be exactly what that build emitted with `DEBUG` compiled off.
|
hold exactly the regular files and symlinks that build emitted, with `DEBUG`
|
||||||
|
compiled off.
|
||||||
|
|
||||||
The backlog lives on the
|
The backlog lives on the
|
||||||
[Gitea tracker](https://git.eeqj.de/sneak/AutistMask/issues), which is
|
[Gitea tracker](https://git.eeqj.de/sneak/AutistMask/issues), which is
|
||||||
@@ -44,6 +45,119 @@ but the review is broader than any of them.
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-08-23: The swap approval screen no longer guesses 18 decimals for a token
|
||||||
|
outside the bundled list
|
||||||
|
([#340](https://git.eeqj.de/sneak/AutistMask/issues/340)). `tokenInfo()` in
|
||||||
|
`src/shared/uniswap.js` returned `decimals: 18` for any such token — the same
|
||||||
|
assumption [#306](https://git.eeqj.de/sneak/AutistMask/issues/306) removed
|
||||||
|
from the ERC-20 amount line — so a 1,000-unit swap of a 6-decimal token was
|
||||||
|
stated as `0.000000001`, and every newly listed token reached it. The swap's
|
||||||
|
`Amount` and `Min. received` lines now resolve the scale through
|
||||||
|
`resolveTokenDecimals()`, the same bundled-list-then-tracked-then-explorer
|
||||||
|
order the ERC-20 line uses, and where nothing knows it they render
|
||||||
|
`unknownDecimalsAmount()` — base units with the scale stated — instead of a
|
||||||
|
number. No new data source and no network call: the scale comes only from what
|
||||||
|
the wallet already holds. An unbounded permit is still shown as `Unlimited`.
|
||||||
|
`README.md` records the rule as a Display Consistency exception.
|
||||||
|
- 2026-08-23: A failed release build no longer leaves a loadable debug bundle in
|
||||||
|
`dist/` ([#333](https://git.eeqj.de/sneak/AutistMask/issues/333)). With
|
||||||
|
`AUTISTMASK_DEBUG=1` exported, `make build` compiled a debug bundle and failed
|
||||||
|
on it in `script/verify-build` — but the bundle stayed on disk, loadable, with
|
||||||
|
every wallet it creates using the publicly committed test recovery phrase.
|
||||||
|
Every step of `make build` now runs through `script/discard-dist-on-failure`,
|
||||||
|
which removes `dist/` when a step fails and says on stderr that it did and
|
||||||
|
why; a removal it cannot complete is reported just as loudly.
|
||||||
|
`make build-debug` is deliberately not wrapped: its output is not mistakable
|
||||||
|
for a release build and is the evidence of the failure.
|
||||||
|
`script/test-verify-build` asserts the state of `dist/` on disk after a
|
||||||
|
failing and a succeeding step, not just the exit status, and reads `make -n`
|
||||||
|
to check the wrapper is on the release path and only there.
|
||||||
|
- 2026-08-23: `README.md` and `script/verify-build`'s own comments now state the
|
||||||
|
emitted-tree guarantee at the width the code actually enforces
|
||||||
|
([#331](https://git.eeqj.de/sneak/AutistMask/issues/331)). The tree walk is
|
||||||
|
`-type f -o -type l`, so the guarantee covers regular files and symlinks under
|
||||||
|
`dist/`; fifos, sockets, device nodes and empty directories are not checked,
|
||||||
|
because a build emits none of them, none can carry a shippable payload, and
|
||||||
|
`grep` on a fifo would hang rather than fail. The exclusion is deliberate and
|
||||||
|
unchanged — the README said "nothing under `dist/` that the build did not
|
||||||
|
write", which was broader than that. Documentation only; no executable line
|
||||||
|
changed.
|
||||||
|
- 2026-08-23: An amount below the 4-decimal display floor no longer reads as
|
||||||
|
zero on the approval screens
|
||||||
|
([#322](https://git.eeqj.de/sneak/AutistMask/issues/322)). With the token's
|
||||||
|
true scale resolved, the 4-decimal truncation still printed a small amount as
|
||||||
|
`0.0000` — 1 base unit of an 18-decimal token, 500 of an 8-decimal one — so a
|
||||||
|
real transfer, allowance or swap was stated as nothing on the one screen whose
|
||||||
|
job is to say what is being authorized, and a swap's `Min. received` claimed
|
||||||
|
the user might receive nothing. Three copies of that truncation existed; they
|
||||||
|
now share `src/shared/amountDisplay.js`. Everything the approval and
|
||||||
|
confirmation screens render (`src/popup/views/approval.js`,
|
||||||
|
`src/shared/uniswap.js`) extends to the first significant digit when the
|
||||||
|
truncated figure would otherwise read as zero, keeping the amount in token
|
||||||
|
units rather than switching to base units mid-line. The history and balance
|
||||||
|
lists (`src/shared/transactions.js`) keep the unfloored rule, which is out of
|
||||||
|
scope by the issue's definition of done. `README.md`'s Display Consistency
|
||||||
|
section records the exception.
|
||||||
|
- 2026-08-23: The extension can be installed once and kept
|
||||||
|
([#310](https://git.eeqj.de/sneak/AutistMask/issues/310)). There was no
|
||||||
|
packaging target anywhere, no artifact, and `manifest/chrome.json` carried no
|
||||||
|
`key` — so an unpacked Chrome load derived its extension id, and therefore its
|
||||||
|
`chrome.storage.local` partition, from the absolute checkout path: moving or
|
||||||
|
re-cloning the checkout presented an empty wallet with no error. The manifest
|
||||||
|
now carries a fixed `key` (public half only; the private half is a credential
|
||||||
|
and is not in this repo, and no target generates one into the tree), pinning
|
||||||
|
the id to `gipbhkogfopeahplcjhipkgpcimdpkip`. `make package` produces
|
||||||
|
`release/autistmask-chrome-<version>.zip` and
|
||||||
|
`release/autistmask-firefox-<version>.xpi` plus `SHA256SUMS`,
|
||||||
|
deterministically and via `make build` so the archives can only be made from a
|
||||||
|
`dist/` already verified against that build's receipt as a release build;
|
||||||
|
every path the manifests and the popup HTML reference is resolved and required
|
||||||
|
to be inside the archive, and the archive is read back off disk and compared
|
||||||
|
member by member — `dist/styles.css` sits at the `dist/` root outside both
|
||||||
|
browser directories and is reported as deliberately not shipped rather than
|
||||||
|
dropped by a glob. One version: `script/lib/version.js` fails the build when
|
||||||
|
`package.json` and the two manifests disagree, instead of reading from one of
|
||||||
|
them. `BUILD_COMMIT` now carries `-dirty` when the working tree does not match
|
||||||
|
`HEAD` (and `-unknown` when git cannot say), while the full hash behind the
|
||||||
|
About screen's commit link stays clean so the link still resolves. Two real
|
||||||
|
browser observations back it: `tests/e2e/storagePartition.js` loads the
|
||||||
|
extension from two different paths in one Chrome profile with and without
|
||||||
|
`key` and records what each does, and `tests/e2e/firefox/reinstall.js`
|
||||||
|
installs the packaged XPI in a real Firefox, creates a wallet, restarts the
|
||||||
|
browser on the same profile, adds the add-on again and decrypts the vault back
|
||||||
|
to the original recovery phrase — and then observes that an explicit uninstall
|
||||||
|
DESTROYS that storage, which is correct browser behaviour but means Remove is
|
||||||
|
irreversible for a wallet, now stated in README.md. Deliberately not done: AMO
|
||||||
|
signing, CRX packing, tagging and any upload — the Firefox artifact is
|
||||||
|
UNSIGNED and README.md now states that release Firefox and ESR refuse it, that
|
||||||
|
Developer Edition or an Unbranded build is required, and that a temporary
|
||||||
|
add-on does not survive a browser restart.
|
||||||
|
- 2026-08-20: A second extension page can no longer silently delete a wallet
|
||||||
|
([#304](https://git.eeqj.de/sneak/AutistMask/issues/304)). `saveState()` wrote
|
||||||
|
the entire state blob, and every extension page — the toolbar popup, a dApp
|
||||||
|
approval window, `backgroundRefresh()` — holds its own in-memory `state`,
|
||||||
|
loaded once, with `showView()` saving on every navigation; a second page that
|
||||||
|
saved after a first had written something new overwrote it, no attacker or
|
||||||
|
unusual input required. `saveState()` is now a read-modify-write: it re-reads
|
||||||
|
storage, diffs the persisted fields against a deep-cloned `baseline` snapshot
|
||||||
|
taken at the last `loadState()`/`saveState()` on that page, and writes only
|
||||||
|
the fields that actually changed — everything else is carried forward from
|
||||||
|
storage in its loaded-and-normalized shape (`normalizePersisted()`, shared
|
||||||
|
with `loadState()`), so a legacy or malformed record a load has always
|
||||||
|
self-healed in memory keeps getting written back even on a save that touched
|
||||||
|
something else entirely. `showView()` fires `saveState()` on every navigation
|
||||||
|
without awaiting it, so two saves from the same page can be in flight at once;
|
||||||
|
a FIFO queue serializes them rather than letting a slow one finish after a
|
||||||
|
later one and re-derive a stale answer. Deliberately not done: the live
|
||||||
|
`state` of a field this page does not own is not rehydrated from what another
|
||||||
|
page wrote, only the persisted record is — adopting a concurrently-written
|
||||||
|
value into `state` reintroduced the same clobber one page later, caught by
|
||||||
|
`tests/txStatus.test.js` red. Two writers of the same field still resolve
|
||||||
|
last-writer-wins, documented at the merge point. `tests/stateMerge.test.js`
|
||||||
|
covers the two-page save and the approval-window reproduction from the issue —
|
||||||
|
add a wallet in one page, force a save from a second page loaded before it,
|
||||||
|
both wallets survive — each demonstrated failing against the unfixed full-blob
|
||||||
|
write.
|
||||||
- 2026-08-20: A forgotten password no longer wedges the wallet
|
- 2026-08-20: A forgotten password no longer wedges the wallet
|
||||||
([#312](https://git.eeqj.de/sneak/AutistMask/issues/312)). Deleting a wallet
|
([#312](https://git.eeqj.de/sneak/AutistMask/issues/312)). Deleting a wallet
|
||||||
was password-gated and importing its recovery phrase again was refused as a
|
was password-gated and importing its recovery phrase again was refused as a
|
||||||
|
|||||||
60
build.js
60
build.js
@@ -3,6 +3,7 @@ const path = require("path");
|
|||||||
const crypto = require("crypto");
|
const crypto = require("crypto");
|
||||||
const { execSync } = require("child_process");
|
const { execSync } = require("child_process");
|
||||||
const esbuild = require("esbuild");
|
const esbuild = require("esbuild");
|
||||||
|
const { resolveVersion } = require("./script/lib/version");
|
||||||
|
|
||||||
const DIST = path.join(__dirname, "dist");
|
const DIST = path.join(__dirname, "dist");
|
||||||
const DIST_CHROME = path.join(DIST, "chrome");
|
const DIST_CHROME = path.join(DIST, "chrome");
|
||||||
@@ -160,28 +161,53 @@ function isDebugBuild() {
|
|||||||
return process.env.AUTISTMASK_DEBUG === "1";
|
return process.env.AUTISTMASK_DEBUG === "1";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A short git output, or null when git cannot answer. Distinguishing "git said
|
||||||
|
// nothing" from "git could not be asked" matters below: a working tree whose
|
||||||
|
// state is unknown must not be stamped as clean.
|
||||||
|
function git(args) {
|
||||||
|
try {
|
||||||
|
return execSync(`git ${args}`, {
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: ["ignore", "pipe", "ignore"],
|
||||||
|
}).trim();
|
||||||
|
} catch {
|
||||||
|
// not a git repo, or git not available
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The working-tree state, as a suffix for the displayed commit: "" when the
|
||||||
|
// tree matches HEAD, "-dirty" when it does not, "-unknown" when git answered
|
||||||
|
// the hash but not the status. Without this a build from a modified tree
|
||||||
|
// stamped a clean hash, so the About screen named a commit whose contents were
|
||||||
|
// not what was running — the one thing that stamp exists to establish.
|
||||||
|
//
|
||||||
|
// git status --porcelain honours .gitignore, so dist/ and node_modules/ do not
|
||||||
|
// make every build dirty; an untracked file that is NOT ignored does, and
|
||||||
|
// correctly: it may well be in the bundle.
|
||||||
|
function worktreeSuffix() {
|
||||||
|
const status = git("status --porcelain");
|
||||||
|
if (status === null) return "-unknown";
|
||||||
|
return status === "" ? "" : "-dirty";
|
||||||
|
}
|
||||||
|
|
||||||
function getBuildInfo() {
|
function getBuildInfo() {
|
||||||
const pkg = JSON.parse(
|
const pkg = JSON.parse(
|
||||||
fs.readFileSync(path.join(__dirname, "package.json"), "utf8"),
|
fs.readFileSync(path.join(__dirname, "package.json"), "utf8"),
|
||||||
);
|
);
|
||||||
let commitHash = "unknown";
|
const commitHashFull = git("rev-parse HEAD") || "unknown";
|
||||||
try {
|
const shortHash = git("rev-parse --short HEAD") || "unknown";
|
||||||
commitHash = execSync("git rev-parse --short HEAD", {
|
// The full hash is left clean because it is the href of the commit link in
|
||||||
encoding: "utf8",
|
// the About screen, and "abc123-dirty" is not a commit anyone can fetch.
|
||||||
}).trim();
|
// The displayed short hash carries the marker, so the screen says the tree
|
||||||
} catch {
|
// was modified while still linking somewhere real.
|
||||||
// not a git repo or git not available
|
const commitHash =
|
||||||
}
|
shortHash === "unknown" ? shortHash : shortHash + worktreeSuffix();
|
||||||
let commitHashFull = "unknown";
|
|
||||||
try {
|
|
||||||
commitHashFull = execSync("git rev-parse HEAD", {
|
|
||||||
encoding: "utf8",
|
|
||||||
}).trim();
|
|
||||||
} catch {
|
|
||||||
// not a git repo or git not available
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
version: pkg.version,
|
// Fails the build when package.json and the two manifests disagree;
|
||||||
|
// see script/lib/version.js. Called before anything is emitted, so a
|
||||||
|
// tree with no single version never reaches dist/.
|
||||||
|
version: resolveVersion(__dirname),
|
||||||
license: pkg.license,
|
license: pkg.license,
|
||||||
author: pkg.author,
|
author: pkg.author,
|
||||||
commitHash,
|
commitHash,
|
||||||
|
|||||||
@@ -3,6 +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",
|
||||||
|
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzy/G9gT4Z3Ci0HCmthUPEiCjENg+5meZpjdogyT7SiMfxENtHdrpDL6wGhAg1Dk0f1C67Ft8OYpMrMH3kiP2Wnt0UpHo45PY0YUUYzdJgbsp8u0kaykd5FFiY6FycIIFaTniMuh7wRKuNNdJWly+H3aG7qZ6nGu5PIMdb1GXUk35hY+yl7dz5dqFFYUCyxvWCT9XGBSYiI+XRBB/rVZjMWfWpaTmRPdOZ4+GO/Lx0OdMxKlPA/kLWoPot5vMlLn2FDPu6sASphiu7dKZnrINW+h/27jlHMJQS0jncB1EgqOHW0vbXrZnTveFX6UW+Qp86FfSkikhKtQgTW2A4mtWawIDAQAB",
|
||||||
"permissions": ["storage", "activeTab", "alarms"],
|
"permissions": ["storage", "activeTab", "alarms"],
|
||||||
"host_permissions": ["<all_urls>"],
|
"host_permissions": ["<all_urls>"],
|
||||||
"content_security_policy": {
|
"content_security_policy": {
|
||||||
|
|||||||
78
script/discard-dist-on-failure
Executable file
78
script/discard-dist-on-failure
Executable file
@@ -0,0 +1,78 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# script/discard-dist-on-failure: run one step of the RELEASE build, and if that
|
||||||
|
# step fails, remove dist/ before returning its exit status. Our own extension
|
||||||
|
# to scripts-to-rule-them-all, wrapped around every step of make build.
|
||||||
|
#
|
||||||
|
# Why: with AUTISTMASK_DEBUG=1 exported in the calling shell, make build
|
||||||
|
# compiles a debug bundle and then fails on it in script/verify-build — but the
|
||||||
|
# bundle is already written. It is loadable, and every wallet it creates gets
|
||||||
|
# the publicly committed test recovery phrase from src/shared/constants.js. A
|
||||||
|
# failed release build that leaves that behind is a smaller version of the trap
|
||||||
|
# the verifier exists to close, and "the failure was loud" only works on an
|
||||||
|
# operator who does not load dist/chrome/ anyway. Removing the artifact does not
|
||||||
|
# depend on that.
|
||||||
|
#
|
||||||
|
# Two things this deliberately does not do. It does not wrap make build-debug: a
|
||||||
|
# debug build that failed is not a mistakable artifact, and its output is the
|
||||||
|
# evidence of what went wrong. And it never removes anything on a step that
|
||||||
|
# SUCCEEDS, including the final check-censored --require-dist pass.
|
||||||
|
#
|
||||||
|
# The removal is never silent: it says dist/ is gone and why, on stderr, above
|
||||||
|
# the build's own failure.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
DIST="$ROOT/dist"
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
echo "usage: discard-dist-on-failure COMMAND [ARG...]" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
# Remove dist/, and say so. A removal that could not be completed is reported as
|
||||||
|
# loudly as one that was: the artifact is still on disk, and reporting nothing
|
||||||
|
# would leave the operator believing it is not.
|
||||||
|
discard_dist() {
|
||||||
|
if [ ! -e "$DIST" ] && [ ! -h "$DIST" ]; then
|
||||||
|
echo "discard-dist-on-failure: the release build failed. There was no" \
|
||||||
|
"dist/ to remove." >&2
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -rf "$DIST" || true
|
||||||
|
|
||||||
|
if [ -e "$DIST" ] || [ -h "$DIST" ]; then
|
||||||
|
echo "discard-dist-on-failure: the release build failed and dist/" \
|
||||||
|
"COULD NOT BE REMOVED, so it is still on disk. Do not load it:" \
|
||||||
|
"a release build that failed may hold a complete debug bundle," \
|
||||||
|
"whose wallets all use the publicly committed test recovery" \
|
||||||
|
"phrase. Remove it by hand (make clean)." >&2
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "discard-dist-on-failure: the release build failed, so dist/ WAS" \
|
||||||
|
"REMOVED and no longer exists. A release build that fails has often" \
|
||||||
|
"already emitted a complete, loadable debug bundle — every wallet it" \
|
||||||
|
"creates gets the publicly committed test recovery phrase — so the" \
|
||||||
|
"failed build is not left behind to be loaded. Fix the failure and" \
|
||||||
|
"re-run make build, or run make build-debug if a debug build is what" \
|
||||||
|
"was wanted; that target keeps its output." >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
[ "$#" -ge 1 ] || {
|
||||||
|
usage
|
||||||
|
echo "discard-dist-on-failure: no command given, so no build step ran" \
|
||||||
|
"and nothing was removed." >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
_status=0
|
||||||
|
"$@" || _status=$?
|
||||||
|
|
||||||
|
[ "$_status" -ne 0 ] || return 0
|
||||||
|
|
||||||
|
discard_dist
|
||||||
|
exit "$_status"
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
294
script/lib/package.js
Normal file
294
script/lib/package.js
Normal file
@@ -0,0 +1,294 @@
|
|||||||
|
// Turn a verified dist/ into the two distributable archives.
|
||||||
|
//
|
||||||
|
// Invoked by script/package, which runs `make build` first so that dist/ has
|
||||||
|
// already been checked against the build's own receipt (see the Build Receipts
|
||||||
|
// section of README.md). This program does not build anything and does not
|
||||||
|
// write into dist/: it reads the emitted tree and writes release/.
|
||||||
|
//
|
||||||
|
// release/autistmask-chrome-<version>.zip loaded via chrome://extensions
|
||||||
|
// release/autistmask-firefox-<version>.xpi an UNSIGNED add-on, see README
|
||||||
|
// release/SHA256SUMS
|
||||||
|
//
|
||||||
|
// Self-containment is checked rather than assumed, because the layout invites
|
||||||
|
// exactly one mistake: build.js emits dist/styles.css at the dist/ ROOT,
|
||||||
|
// outside both browser directories, and copies it into each of them as
|
||||||
|
// src/popup/styles.css. A naive `zip -r dist/chrome` is therefore correct only
|
||||||
|
// by accident, and would stop being correct the moment a reference pointed up
|
||||||
|
// and out. So every path the manifest and the popup HTML reference is resolved
|
||||||
|
// and required to be inside the archive, a reference that escapes the browser
|
||||||
|
// directory is a hard failure, and anything sitting at the dist/ root is
|
||||||
|
// listed as deliberately not shipped rather than silently dropped.
|
||||||
|
//
|
||||||
|
// The archive is then read back and compared byte for byte against the
|
||||||
|
// directory it was built from. An archive nobody opened is a claim, not an
|
||||||
|
// artifact.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const { readZip, writeZip } = require("./zip");
|
||||||
|
const { resolveVersion } = require("./version");
|
||||||
|
|
||||||
|
const ROOT = path.resolve(__dirname, "..", "..");
|
||||||
|
const DIST = path.join(ROOT, "dist");
|
||||||
|
const RELEASE = path.join(ROOT, "release");
|
||||||
|
|
||||||
|
const TARGETS = [
|
||||||
|
{ dir: "chrome", ext: "zip" },
|
||||||
|
// .xpi rather than .zip: it is the same container, but Firefox's install
|
||||||
|
// flow keys off the extension.
|
||||||
|
{ dir: "firefox", ext: "xpi" },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Strings in a manifest that name a file the extension loads. Matched by
|
||||||
|
// shape, not by a list of manifest keys, so a key added in a later manifest
|
||||||
|
// version is covered the day it appears rather than the day someone remembers
|
||||||
|
// to extend a list here. Nothing else in either manifest looks like this: the
|
||||||
|
// CSP strings, "<all_urls>", the version and the base64 key all fail it.
|
||||||
|
const MANIFEST_PATH_RE =
|
||||||
|
/^[A-Za-z0-9._][A-Za-z0-9._/-]*\.(?:js|css|html|json|png|svg|woff2?)$/;
|
||||||
|
|
||||||
|
// Local references out of an HTML document. Enough for what this repo emits —
|
||||||
|
// one stylesheet link and one script tag — and anything it does not understand
|
||||||
|
// is reported rather than passed over, see htmlReferences().
|
||||||
|
const HTML_REF_RE = /(?:src|href)\s*=\s*["']([^"']+)["']/gi;
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sha256(buf) {
|
||||||
|
return crypto.createHash("sha256").update(buf).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every regular file under dir, as archive-root-relative forward-slashed
|
||||||
|
// paths. A symlink is refused rather than followed: build.js emits regular
|
||||||
|
// files only, so a link under dist/ is not something the build produced, and
|
||||||
|
// dereferencing one would put bytes from outside dist/ into the artifact.
|
||||||
|
function listFiles(dir, prefix = "") {
|
||||||
|
const out = [];
|
||||||
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||||
|
if (entry.isSymbolicLink()) {
|
||||||
|
fail(
|
||||||
|
`${dir}/${entry.name} is a symlink. The build emits regular ` +
|
||||||
|
`files only, so this is not something it produced and it ` +
|
||||||
|
`will not be archived.`,
|
||||||
|
);
|
||||||
|
} else if (entry.isDirectory()) {
|
||||||
|
out.push(...listFiles(path.join(dir, entry.name), rel));
|
||||||
|
} else if (entry.isFile()) {
|
||||||
|
out.push(rel);
|
||||||
|
} else {
|
||||||
|
fail(
|
||||||
|
`${dir}/${entry.name} is neither a regular file nor a ` +
|
||||||
|
`directory, so it is not something the build emitted`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect every string anywhere in the manifest that looks like a file it
|
||||||
|
// loads, plus every string that tries to reach outside the extension root.
|
||||||
|
// The second half is the point: "../styles.css" never matches
|
||||||
|
// MANIFEST_PATH_RE, so without an explicit check an escaping reference would
|
||||||
|
// read as "not a path" and the missing file would be found only by a user
|
||||||
|
// whose popup rendered unstyled.
|
||||||
|
function manifestReferences(value, found = new Set()) {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
if (value.split("/").includes("..")) {
|
||||||
|
fail(
|
||||||
|
`the manifest references ${JSON.stringify(value)}, which ` +
|
||||||
|
`points outside the extension root. Everything the ` +
|
||||||
|
`browser loads has to be inside the archive; nothing ` +
|
||||||
|
`above it is shipped.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (MANIFEST_PATH_RE.test(value)) found.add(value);
|
||||||
|
} else if (Array.isArray(value)) {
|
||||||
|
for (const v of value) manifestReferences(v, found);
|
||||||
|
} else if (value && typeof value === "object") {
|
||||||
|
for (const v of Object.values(value)) manifestReferences(v, found);
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local references out of one HTML member, resolved against that member's own
|
||||||
|
// directory and returned archive-relative. Absolute URLs, data: URIs and
|
||||||
|
// in-page anchors are not files and are skipped; a relative reference that
|
||||||
|
// climbs out of the archive root is a failure for the same reason as above.
|
||||||
|
function htmlReferences(member, text) {
|
||||||
|
const base = path.posix.dirname(member);
|
||||||
|
const out = new Set();
|
||||||
|
for (const match of text.matchAll(HTML_REF_RE)) {
|
||||||
|
const ref = match[1].trim();
|
||||||
|
if (ref === "" || ref.startsWith("#") || ref.startsWith("//")) continue;
|
||||||
|
if (/^[a-z][a-z0-9+.-]*:/i.test(ref)) continue;
|
||||||
|
if (ref.startsWith("/")) {
|
||||||
|
fail(
|
||||||
|
`${member} references ${JSON.stringify(ref)} from the ` +
|
||||||
|
`extension root. Nothing here emits root-absolute ` +
|
||||||
|
`references and this packager does not resolve them.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const resolved = path.posix.normalize(path.posix.join(base, ref));
|
||||||
|
if (resolved.startsWith("..")) {
|
||||||
|
fail(
|
||||||
|
`${member} references ${JSON.stringify(ref)}, which resolves ` +
|
||||||
|
`outside the extension root. build.js copies the ` +
|
||||||
|
`compiled stylesheet into each browser directory for ` +
|
||||||
|
`exactly this reason: dist/styles.css lives at the dist/ ` +
|
||||||
|
`root and is not part of either archive.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
out.add(resolved);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Everything the browser is told to load, and the assertion that all of it is
|
||||||
|
// in the archive.
|
||||||
|
function checkSelfContained(target, members, read) {
|
||||||
|
if (!members.includes("manifest.json")) {
|
||||||
|
fail(`dist/${target} has no manifest.json at its root`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifest = JSON.parse(read("manifest.json").toString("utf8"));
|
||||||
|
const referenced = new Set(manifestReferences(manifest));
|
||||||
|
|
||||||
|
for (const member of members) {
|
||||||
|
if (!member.endsWith(".html")) continue;
|
||||||
|
for (const ref of htmlReferences(
|
||||||
|
member,
|
||||||
|
read(member).toString("utf8"),
|
||||||
|
)) {
|
||||||
|
referenced.add(ref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const missing = [...referenced].filter((r) => !members.includes(r));
|
||||||
|
if (missing.length > 0) {
|
||||||
|
fail(
|
||||||
|
`the ${target} archive would not be self-contained: it is told ` +
|
||||||
|
`to load ${missing.join(", ")}, which ${
|
||||||
|
missing.length === 1 ? "is" : "are"
|
||||||
|
} not in it`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { manifest, referenced };
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const version = resolveVersion(ROOT);
|
||||||
|
|
||||||
|
if (!fs.existsSync(DIST)) {
|
||||||
|
fail(
|
||||||
|
"there is no dist/ to package. script/package runs make build " +
|
||||||
|
"first; run it rather than this program.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.rmSync(RELEASE, { recursive: true, force: true });
|
||||||
|
fs.mkdirSync(RELEASE, { recursive: true });
|
||||||
|
|
||||||
|
// Files the build emits at the dist/ root, outside both browser
|
||||||
|
// directories. Printed rather than ignored: dist/styles.css is the
|
||||||
|
// Tailwind output that build.js then copies into each browser directory,
|
||||||
|
// so leaving it out is correct — but "correct and stated" and "dropped by
|
||||||
|
// a glob" are different things, and only one of them survives the next
|
||||||
|
// change to the build.
|
||||||
|
const rootOnly = fs
|
||||||
|
.readdirSync(DIST, { withFileTypes: true })
|
||||||
|
.filter((e) => !e.isDirectory())
|
||||||
|
.map((e) => e.name)
|
||||||
|
.sort();
|
||||||
|
if (rootOnly.length > 0) {
|
||||||
|
console.log(
|
||||||
|
`Not shipped (dist/ root, outside every browser directory, and ` +
|
||||||
|
`referenced by nothing inside one): ${rootOnly.join(", ")}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sums = [];
|
||||||
|
for (const { dir, ext } of TARGETS) {
|
||||||
|
const targetDir = path.join(DIST, dir);
|
||||||
|
if (!fs.existsSync(targetDir)) {
|
||||||
|
fail(`dist/${dir} does not exist; run make build`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const members = listFiles(targetDir);
|
||||||
|
const readFromDir = (member) =>
|
||||||
|
fs.readFileSync(path.join(targetDir, member));
|
||||||
|
|
||||||
|
const { manifest } = checkSelfContained(dir, members, readFromDir);
|
||||||
|
if (manifest.version !== version) {
|
||||||
|
fail(
|
||||||
|
`dist/${dir}/manifest.json says version ${manifest.version} ` +
|
||||||
|
`but this tree is ${version}. dist/ is stale: run make ` +
|
||||||
|
`build.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const archive = writeZip(
|
||||||
|
members.map((name) => ({ name, data: readFromDir(name) })),
|
||||||
|
);
|
||||||
|
const name = `autistmask-${dir}-${version}.${ext}`;
|
||||||
|
const outPath = path.join(RELEASE, name);
|
||||||
|
fs.writeFileSync(outPath, archive);
|
||||||
|
|
||||||
|
// Read the artifact back off disk, not the buffer that was just
|
||||||
|
// written: what ships is the file.
|
||||||
|
const written = fs.readFileSync(outPath);
|
||||||
|
const entries = readZip(written);
|
||||||
|
const inArchive = entries.map((e) => e.name).sort();
|
||||||
|
if (inArchive.join("\n") !== members.join("\n")) {
|
||||||
|
fail(
|
||||||
|
`${name} does not hold the same members as dist/${dir}: ` +
|
||||||
|
`archive has ${inArchive.length}, directory has ` +
|
||||||
|
`${members.length}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const onDisk = readFromDir(entry.name);
|
||||||
|
if (sha256(entry.data) !== sha256(onDisk)) {
|
||||||
|
fail(`${name} member ${entry.name} differs from dist/${dir}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Re-run the self-containment check against the ARCHIVE's own
|
||||||
|
// contents. The directory passing it is not the claim being made.
|
||||||
|
const byName = new Map(entries.map((e) => [e.name, e.data]));
|
||||||
|
checkSelfContained(dir, inArchive, (m) => byName.get(m));
|
||||||
|
|
||||||
|
const digest = sha256(written);
|
||||||
|
sums.push(`${digest} ${name}`);
|
||||||
|
console.log(
|
||||||
|
`${name}: ${entries.length} member(s), ${written.length} bytes, ` +
|
||||||
|
`sha256 ${digest}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(RELEASE, "SHA256SUMS"),
|
||||||
|
sums.map((l) => `${l}\n`).join(""),
|
||||||
|
);
|
||||||
|
console.log(`Wrote release/ for version ${version}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only when run as a program. The reference-resolving helpers are what decide
|
||||||
|
// whether an archive is self-contained, so tests/packaging.test.js exercises
|
||||||
|
// them directly and must be able to require this file without packaging
|
||||||
|
// anything.
|
||||||
|
if (require.main === module) {
|
||||||
|
try {
|
||||||
|
main();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`package: ${err && err.message ? err.message : err}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { checkSelfContained, htmlReferences, manifestReferences };
|
||||||
74
script/lib/version.js
Normal file
74
script/lib/version.js
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
// The version, and the rule that there is only one of it.
|
||||||
|
//
|
||||||
|
// Three files declare a version and none of them can be derived from another:
|
||||||
|
// Chrome and Firefox each need their own manifest, both are copied to dist/
|
||||||
|
// verbatim (tests/manifest.test.js asserts that what is in manifest/ is what
|
||||||
|
// ships), and package.json's copy is what build.js compiles into the About
|
||||||
|
// screen. So the single source of truth is enforced rather than generated —
|
||||||
|
// they must all agree or there is no version and no build.
|
||||||
|
//
|
||||||
|
// Reading one of the three and ignoring the rest is what this replaces. That
|
||||||
|
// shape cannot fail: it silently ships an extension whose About screen and
|
||||||
|
// whose browser-reported version disagree, and whose release artifact is named
|
||||||
|
// after whichever file the packager happened to read.
|
||||||
|
//
|
||||||
|
// Required by build.js, script/lib/package.js and tests/version.test.js, so
|
||||||
|
// the build, the release artifacts and make check all apply the same rule to
|
||||||
|
// the same files.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const VERSION_SOURCES = [
|
||||||
|
"package.json",
|
||||||
|
"manifest/chrome.json",
|
||||||
|
"manifest/firefox.json",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Every declared version, in VERSION_SOURCES order, as { source, version }.
|
||||||
|
// A file that declares nothing usable fails here rather than being skipped:
|
||||||
|
// a missing version is not agreement.
|
||||||
|
function declaredVersions(root) {
|
||||||
|
return VERSION_SOURCES.map((source) => {
|
||||||
|
const file = path.join(root, source);
|
||||||
|
let parsed;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(
|
||||||
|
`${source} could not be read as JSON: ${e.message}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const version = parsed.version;
|
||||||
|
if (typeof version !== "string" || version.trim() === "") {
|
||||||
|
throw new Error(
|
||||||
|
`${source} declares no usable "version" (found ` +
|
||||||
|
`${JSON.stringify(version)}). Every artifact is named and ` +
|
||||||
|
`stamped with it, so there is nothing to build without it.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return { source, version };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// The one version all three declare, or a failure naming every disagreeing
|
||||||
|
// file and what it said.
|
||||||
|
function resolveVersion(root) {
|
||||||
|
const declared = declaredVersions(root);
|
||||||
|
const distinct = [...new Set(declared.map((d) => d.version))];
|
||||||
|
if (distinct.length !== 1) {
|
||||||
|
throw new Error(
|
||||||
|
"the declared versions disagree, so this tree has no version: " +
|
||||||
|
declared.map((d) => `${d.source}=${d.version}`).join(", ") +
|
||||||
|
". Set all of them to the same value: the manifests are what " +
|
||||||
|
"the browser reports and package.json is what the About " +
|
||||||
|
"screen shows, and a build that picked one of them would " +
|
||||||
|
"ship the disagreement.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return distinct[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { VERSION_SOURCES, declaredVersions, resolveVersion };
|
||||||
274
script/lib/zip.js
Normal file
274
script/lib/zip.js
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
// A minimal, deterministic ZIP writer and reader.
|
||||||
|
//
|
||||||
|
// Used by script/lib/package.js to build the distributable archives: a Chrome
|
||||||
|
// zip and a Firefox XPI are both ordinary zip files with manifest.json at the
|
||||||
|
// root, so one implementation covers both.
|
||||||
|
//
|
||||||
|
// Why this rather than a package or the zip(1) binary. A dependency would have
|
||||||
|
// to be hash-pinned like everything else in REPO_POLICIES.md, and this is
|
||||||
|
// about a hundred lines of stdlib zlib for a format the archives use two
|
||||||
|
// features of. The binary is worse: the release artifact would then depend on
|
||||||
|
// whichever Info-ZIP the machine happens to have, which is the same objection
|
||||||
|
// that keeps linting inside a container.
|
||||||
|
//
|
||||||
|
// Deterministic on purpose. Entries are sorted by name, every timestamp is the
|
||||||
|
// same fixed 1980-01-01 the format's epoch starts at, and the compression
|
||||||
|
// level is fixed, so building the same dist/ twice produces byte-identical
|
||||||
|
// archives and the sha256 in SHA256SUMS is a property of the input rather than
|
||||||
|
// of the clock. Two builds of the same commit that disagree are then visible
|
||||||
|
// instead of expected.
|
||||||
|
//
|
||||||
|
// Deliberately NOT implemented: zip64, encryption, data descriptors,
|
||||||
|
// directory entries (browsers infer directories from member paths), and
|
||||||
|
// anything to do with symlinks. writeZip refuses input it cannot represent
|
||||||
|
// rather than emitting an archive that is quietly wrong.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const zlib = require("zlib");
|
||||||
|
|
||||||
|
const LOCAL_SIG = 0x04034b50;
|
||||||
|
const CENTRAL_SIG = 0x02014b50;
|
||||||
|
const EOCD_SIG = 0x06054b50;
|
||||||
|
|
||||||
|
const METHOD_STORE = 0;
|
||||||
|
const METHOD_DEFLATE = 8;
|
||||||
|
|
||||||
|
// 1980-01-01 00:00:00, the earliest the MS-DOS timestamp fields can express.
|
||||||
|
const DOS_DATE = (0 << 9) | (1 << 5) | 1;
|
||||||
|
const DOS_TIME = 0;
|
||||||
|
|
||||||
|
// Unix regular file, mode 0644, in the high 16 bits, which is where the "made
|
||||||
|
// by unix" convention puts it.
|
||||||
|
// >>> 0 because JS shifts are signed 32-bit and this one sets the top bit.
|
||||||
|
const EXTERNAL_ATTRS = (0o100644 << 16) >>> 0;
|
||||||
|
const VERSION_MADE_BY = (3 << 8) | 20; // unix, needs zip 2.0
|
||||||
|
const VERSION_NEEDED = 20;
|
||||||
|
|
||||||
|
// Without zip64 every size and offset is a u32.
|
||||||
|
const MAX_U32 = 0xffffffff;
|
||||||
|
|
||||||
|
const CRC_TABLE = (() => {
|
||||||
|
const table = new Int32Array(256);
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
let c = i;
|
||||||
|
for (let k = 0; k < 8; k++) {
|
||||||
|
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||||
|
}
|
||||||
|
table[i] = c;
|
||||||
|
}
|
||||||
|
return table;
|
||||||
|
})();
|
||||||
|
|
||||||
|
// Written out rather than taken from zlib.crc32, which only exists from node
|
||||||
|
// 22.2: this runs from script/ on whatever node the host has as well as inside
|
||||||
|
// the pinned image, and a checksum that silently is not there is worse than
|
||||||
|
// twelve lines.
|
||||||
|
function crc32(buf) {
|
||||||
|
let c = -1;
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
||||||
|
}
|
||||||
|
return (c ^ -1) >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Member names are stored as raw bytes. Anything outside ASCII would need the
|
||||||
|
// UTF-8 flag and interoperability care that nothing this repo emits requires,
|
||||||
|
// so it is refused instead of guessed at.
|
||||||
|
function encodeName(name) {
|
||||||
|
if (typeof name !== "string" || name === "") {
|
||||||
|
throw new Error(`zip: unusable member name ${JSON.stringify(name)}`);
|
||||||
|
}
|
||||||
|
const segments = name.split("/");
|
||||||
|
if (
|
||||||
|
name.startsWith("/") ||
|
||||||
|
name.includes("\\") ||
|
||||||
|
segments.some((s) => s === "" || s === "." || s === "..")
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`zip: refusing member name ${JSON.stringify(name)}: archive ` +
|
||||||
|
`members must be relative paths under the archive root`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (/[^\x20-\x7e]/.test(name)) {
|
||||||
|
throw new Error(
|
||||||
|
`zip: refusing non-ASCII member name ${JSON.stringify(name)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Buffer.from(name, "ascii");
|
||||||
|
}
|
||||||
|
|
||||||
|
function compress(data) {
|
||||||
|
if (data.length === 0) {
|
||||||
|
return { method: METHOD_STORE, body: data };
|
||||||
|
}
|
||||||
|
const deflated = zlib.deflateRawSync(data, { level: 9 });
|
||||||
|
if (deflated.length >= data.length) {
|
||||||
|
return { method: METHOD_STORE, body: data };
|
||||||
|
}
|
||||||
|
return { method: METHOD_DEFLATE, body: deflated };
|
||||||
|
}
|
||||||
|
|
||||||
|
// entries: [{ name, data }]. Returns the archive as a Buffer.
|
||||||
|
function writeZip(entries) {
|
||||||
|
if (!Array.isArray(entries) || entries.length === 0) {
|
||||||
|
throw new Error("zip: refusing to write an archive with no members");
|
||||||
|
}
|
||||||
|
|
||||||
|
const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : 1));
|
||||||
|
const seen = new Set();
|
||||||
|
const locals = [];
|
||||||
|
const centrals = [];
|
||||||
|
let offset = 0;
|
||||||
|
|
||||||
|
for (const entry of sorted) {
|
||||||
|
const name = encodeName(entry.name);
|
||||||
|
if (seen.has(entry.name)) {
|
||||||
|
throw new Error(`zip: duplicate member ${entry.name}`);
|
||||||
|
}
|
||||||
|
seen.add(entry.name);
|
||||||
|
|
||||||
|
const data = Buffer.from(entry.data);
|
||||||
|
const { method, body } = compress(data);
|
||||||
|
if (data.length > MAX_U32 || body.length > MAX_U32) {
|
||||||
|
throw new Error(
|
||||||
|
`zip: ${entry.name} is too large for a non-zip64 archive`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const crc = crc32(data);
|
||||||
|
|
||||||
|
const local = Buffer.alloc(30 + name.length);
|
||||||
|
local.writeUInt32LE(LOCAL_SIG, 0);
|
||||||
|
local.writeUInt16LE(VERSION_NEEDED, 4);
|
||||||
|
local.writeUInt16LE(0, 6);
|
||||||
|
local.writeUInt16LE(method, 8);
|
||||||
|
local.writeUInt16LE(DOS_TIME, 10);
|
||||||
|
local.writeUInt16LE(DOS_DATE, 12);
|
||||||
|
local.writeUInt32LE(crc, 14);
|
||||||
|
local.writeUInt32LE(body.length, 18);
|
||||||
|
local.writeUInt32LE(data.length, 22);
|
||||||
|
local.writeUInt16LE(name.length, 26);
|
||||||
|
local.writeUInt16LE(0, 28);
|
||||||
|
name.copy(local, 30);
|
||||||
|
|
||||||
|
const central = Buffer.alloc(46 + name.length);
|
||||||
|
central.writeUInt32LE(CENTRAL_SIG, 0);
|
||||||
|
central.writeUInt16LE(VERSION_MADE_BY, 4);
|
||||||
|
central.writeUInt16LE(VERSION_NEEDED, 6);
|
||||||
|
central.writeUInt16LE(0, 8);
|
||||||
|
central.writeUInt16LE(method, 10);
|
||||||
|
central.writeUInt16LE(DOS_TIME, 12);
|
||||||
|
central.writeUInt16LE(DOS_DATE, 14);
|
||||||
|
central.writeUInt32LE(crc, 16);
|
||||||
|
central.writeUInt32LE(body.length, 20);
|
||||||
|
central.writeUInt32LE(data.length, 24);
|
||||||
|
central.writeUInt16LE(name.length, 28);
|
||||||
|
central.writeUInt16LE(0, 30);
|
||||||
|
central.writeUInt16LE(0, 32);
|
||||||
|
central.writeUInt16LE(0, 34);
|
||||||
|
central.writeUInt16LE(0, 36);
|
||||||
|
central.writeUInt32LE(EXTERNAL_ATTRS, 38);
|
||||||
|
if (offset > MAX_U32) {
|
||||||
|
throw new Error("zip: archive too large for a non-zip64 archive");
|
||||||
|
}
|
||||||
|
central.writeUInt32LE(offset, 42);
|
||||||
|
name.copy(central, 46);
|
||||||
|
|
||||||
|
locals.push(local, body);
|
||||||
|
centrals.push(central);
|
||||||
|
offset += local.length + body.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
const centralBuf = Buffer.concat(centrals);
|
||||||
|
const eocd = Buffer.alloc(22);
|
||||||
|
eocd.writeUInt32LE(EOCD_SIG, 0);
|
||||||
|
eocd.writeUInt16LE(0, 4);
|
||||||
|
eocd.writeUInt16LE(0, 6);
|
||||||
|
eocd.writeUInt16LE(sorted.length, 8);
|
||||||
|
eocd.writeUInt16LE(sorted.length, 10);
|
||||||
|
eocd.writeUInt32LE(centralBuf.length, 12);
|
||||||
|
eocd.writeUInt32LE(offset, 16);
|
||||||
|
eocd.writeUInt16LE(0, 20);
|
||||||
|
|
||||||
|
return Buffer.concat([...locals, centralBuf, eocd]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read an archive back into [{ name, data }], from the central directory
|
||||||
|
// rather than by scanning for local headers: the central directory is the
|
||||||
|
// authoritative index, and a member reachable only by scanning is one a real
|
||||||
|
// unzipper would not extract.
|
||||||
|
//
|
||||||
|
// Every member's CRC is checked. The point of reading an archive back is to
|
||||||
|
// establish that it holds what it was meant to hold, so a member that does not
|
||||||
|
// decompress to its recorded checksum is a failure and never a warning.
|
||||||
|
function readZip(buf) {
|
||||||
|
if (buf.length < 22) {
|
||||||
|
throw new Error("zip: too short to be an archive");
|
||||||
|
}
|
||||||
|
// No archive this writes has a trailing comment, so the EOCD is the last
|
||||||
|
// 22 bytes. Anything else is not an archive this produced.
|
||||||
|
const eocdAt = buf.length - 22;
|
||||||
|
if (buf.readUInt32LE(eocdAt) !== EOCD_SIG) {
|
||||||
|
throw new Error(
|
||||||
|
"zip: no end-of-central-directory record at the end of the " +
|
||||||
|
"archive (a trailing comment, or not a zip at all)",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const count = buf.readUInt16LE(eocdAt + 10);
|
||||||
|
const centralSize = buf.readUInt32LE(eocdAt + 12);
|
||||||
|
let at = buf.readUInt32LE(eocdAt + 16);
|
||||||
|
if (at + centralSize > eocdAt) {
|
||||||
|
throw new Error("zip: central directory runs past the archive");
|
||||||
|
}
|
||||||
|
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
if (buf.readUInt32LE(at) !== CENTRAL_SIG) {
|
||||||
|
throw new Error(`zip: bad central directory entry ${i}`);
|
||||||
|
}
|
||||||
|
const method = buf.readUInt16LE(at + 10);
|
||||||
|
const crc = buf.readUInt32LE(at + 16);
|
||||||
|
const compSize = buf.readUInt32LE(at + 20);
|
||||||
|
const rawSize = buf.readUInt32LE(at + 24);
|
||||||
|
const nameLen = buf.readUInt16LE(at + 28);
|
||||||
|
const extraLen = buf.readUInt16LE(at + 30);
|
||||||
|
const commentLen = buf.readUInt16LE(at + 32);
|
||||||
|
const localAt = buf.readUInt32LE(at + 42);
|
||||||
|
const name = buf.toString("ascii", at + 46, at + 46 + nameLen);
|
||||||
|
at += 46 + nameLen + extraLen + commentLen;
|
||||||
|
|
||||||
|
if (buf.readUInt32LE(localAt) !== LOCAL_SIG) {
|
||||||
|
throw new Error(`zip: ${name} has no local header`);
|
||||||
|
}
|
||||||
|
// The local header's own name and extra lengths, not the central
|
||||||
|
// directory's: the two are allowed to differ and the data starts after
|
||||||
|
// the local ones.
|
||||||
|
const localNameLen = buf.readUInt16LE(localAt + 26);
|
||||||
|
const localExtraLen = buf.readUInt16LE(localAt + 28);
|
||||||
|
const dataAt = localAt + 30 + localNameLen + localExtraLen;
|
||||||
|
const body = buf.subarray(dataAt, dataAt + compSize);
|
||||||
|
|
||||||
|
let data;
|
||||||
|
if (method === METHOD_STORE) {
|
||||||
|
data = Buffer.from(body);
|
||||||
|
} else if (method === METHOD_DEFLATE) {
|
||||||
|
data = zlib.inflateRawSync(body);
|
||||||
|
} else {
|
||||||
|
throw new Error(`zip: ${name} uses compression method ${method}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.length !== rawSize) {
|
||||||
|
throw new Error(
|
||||||
|
`zip: ${name} decompressed to ${data.length} bytes, not the ` +
|
||||||
|
`recorded ${rawSize}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (crc32(data) !== crc) {
|
||||||
|
throw new Error(`zip: ${name} fails its recorded CRC32`);
|
||||||
|
}
|
||||||
|
out.push({ name, data });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { crc32, readZip, writeZip };
|
||||||
38
script/package
Executable file
38
script/package
Executable file
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# script/package: produce the release artifacts — one self-contained,
|
||||||
|
# versioned archive per browser — into release/. Our own extension to
|
||||||
|
# scripts-to-rule-them-all.
|
||||||
|
#
|
||||||
|
# It builds first, through `make build` rather than by calling build.js
|
||||||
|
# itself. That target is the only audited path to a release build: it creates
|
||||||
|
# the build receipt outside the repo, scrubs AUTISTMASK_DEBUG from the
|
||||||
|
# verifier's environment, tells script/verify-build in so many words to expect
|
||||||
|
# a RELEASE build, and re-runs script/check-censored against dist/.
|
||||||
|
# script/test-verify-build asserts that wiring by reading the recipe back out
|
||||||
|
# of `make -n`. Re-implementing that sequence here would give the release
|
||||||
|
# artifacts a second, unaudited path to dist/ — and it is the release
|
||||||
|
# artifacts, above everything else, that must never be built from a debug
|
||||||
|
# compile.
|
||||||
|
#
|
||||||
|
# This packages, it does not publish. Tagging, CRX packing and any upload are
|
||||||
|
# outward-facing acts and are nobody's job but the owner's.
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
|
main() {
|
||||||
|
cd "$ROOT"
|
||||||
|
|
||||||
|
if ! command -v make >/dev/null 2>&1; then
|
||||||
|
echo "package: make is required (the release build runs through" \
|
||||||
|
"make build)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
make build
|
||||||
|
|
||||||
|
echo "Packaging release artifacts..."
|
||||||
|
node script/lib/package.js
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@@ -78,6 +78,22 @@ main() {
|
|||||||
-e "E2E_TRACE_NETWORK=${E2E_TRACE_NETWORK:-0}" \
|
-e "E2E_TRACE_NETWORK=${E2E_TRACE_NETWORK:-0}" \
|
||||||
"$(cat "$IIDFILE")" \
|
"$(cat "$IIDFILE")" \
|
||||||
node tests/e2e/run.js
|
node tests/e2e/run.js
|
||||||
|
|
||||||
|
# Where chrome.storage.local lives, and what moves it: two unpacked loads
|
||||||
|
# from two different paths in one profile, with the shipped manifest and
|
||||||
|
# again with `key` stripped out. Its own browser sessions — four of them —
|
||||||
|
# because the whole subject is what happens ACROSS loads, which the suite
|
||||||
|
# above cannot express with one.
|
||||||
|
#
|
||||||
|
# No PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS here: this drives no
|
||||||
|
# RPC and installs no route handlers, and the browser is started with
|
||||||
|
# --host-resolver-rules=MAP * ~NOTFOUND so nothing it does can leave.
|
||||||
|
echo "Running the extension-id and storage-partition observations..."
|
||||||
|
docker run --rm \
|
||||||
|
--ipc=host \
|
||||||
|
-e HOME=/tmp \
|
||||||
|
"$(cat "$IIDFILE")" \
|
||||||
|
node tests/e2e/storagePartition.js
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@@ -72,6 +72,19 @@ main() {
|
|||||||
-e HOME=/tmp \
|
-e HOME=/tmp \
|
||||||
"$(cat "$IIDFILE")" \
|
"$(cat "$IIDFILE")" \
|
||||||
node tests/e2e/firefox/run.js dist/firefox
|
node tests/e2e/firefox/run.js dist/firefox
|
||||||
|
|
||||||
|
# The install/uninstall/re-install property, against the packaged XPI
|
||||||
|
# rather than the unpacked directory: it is the artifact a user would be
|
||||||
|
# handed, and this is the only place a real Firefox is asked to load it.
|
||||||
|
# Its own browser session, because it takes the add-on away in the middle
|
||||||
|
# and the suite above shares one session throughout.
|
||||||
|
echo "Running the Firefox re-install suite against the packaged XPI..."
|
||||||
|
docker run --rm \
|
||||||
|
--shm-size=1g \
|
||||||
|
--network none \
|
||||||
|
-e HOME=/tmp \
|
||||||
|
"$(cat "$IIDFILE")" \
|
||||||
|
node tests/e2e/firefox/reinstall.js
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/test-verify-build: exercise every failure mode of
|
# script/test-verify-build: exercise every failure mode of
|
||||||
# script/verify-build. Our own extension to scripts-to-rule-them-all, run
|
# script/verify-build, and what make build does with dist/ after one of them
|
||||||
# from script/check so make check covers it.
|
# (script/discard-dist-on-failure). Our own extension to
|
||||||
|
# scripts-to-rule-them-all, run from script/check so make check covers it.
|
||||||
#
|
#
|
||||||
# Why this exists: verify-build is the build-integrity guard, and four separate
|
# Why this exists: verify-build is the build-integrity guard, and four separate
|
||||||
# reviews of it each found a fresh vacuous pass — the grep exit-2 conflation,
|
# reviews of it each found a fresh vacuous pass — the grep exit-2 conflation,
|
||||||
@@ -31,6 +32,7 @@ set -eu
|
|||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
VERIFY_BUILD="$ROOT/script/verify-build"
|
VERIFY_BUILD="$ROOT/script/verify-build"
|
||||||
|
DISCARD_DIST="$ROOT/script/discard-dist-on-failure"
|
||||||
|
|
||||||
MARKER_ON="autistmask-build-debug=on"
|
MARKER_ON="autistmask-build-debug=on"
|
||||||
MARKER_OFF="autistmask-build-debug=off"
|
MARKER_OFF="autistmask-build-debug=off"
|
||||||
@@ -150,6 +152,7 @@ build_fixture() {
|
|||||||
|
|
||||||
mkdir -p "$FIXTURE/script"
|
mkdir -p "$FIXTURE/script"
|
||||||
ln -s "$VERIFY_BUILD" "$FIXTURE/script/verify-build"
|
ln -s "$VERIFY_BUILD" "$FIXTURE/script/verify-build"
|
||||||
|
ln -s "$DISCARD_DIST" "$FIXTURE/script/discard-dist-on-failure"
|
||||||
|
|
||||||
mkdir -p "$FIXTURE/dist/chrome/src/popup" \
|
mkdir -p "$FIXTURE/dist/chrome/src/popup" \
|
||||||
"$FIXTURE/dist/chrome/src/content" \
|
"$FIXTURE/dist/chrome/src/content" \
|
||||||
@@ -513,12 +516,125 @@ c_debug_build() {
|
|||||||
write_receipt
|
write_receipt
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c_no_dist() { rm -rf dist; }
|
||||||
|
|
||||||
|
# --- dist discard -----------------------------------------------------------
|
||||||
|
#
|
||||||
|
# make build wraps every step of the release path in
|
||||||
|
# script/discard-dist-on-failure, so a release build that fails removes dist/:
|
||||||
|
# with AUTISTMASK_DEBUG=1 exported it has already emitted a complete, loadable
|
||||||
|
# debug bundle whose every wallet uses the publicly committed test recovery
|
||||||
|
# phrase, and a loud failure alone does not stop someone loading dist/chrome/
|
||||||
|
# anyway. make build-debug is deliberately not wrapped.
|
||||||
|
#
|
||||||
|
# Both directions are asserted against the state of dist/ ON DISK after the run,
|
||||||
|
# not against the exit status: a case reading only the status would keep passing
|
||||||
|
# if the removal quietly stopped happening, which is the flip this exists to
|
||||||
|
# catch. The wrapper runs against the fixture — its ROOT is the fixture, via the
|
||||||
|
# symlink in the fixture's script/ — with trivial commands standing in for the
|
||||||
|
# build steps, because what is under test is what happens after a step says no,
|
||||||
|
# not the step.
|
||||||
|
|
||||||
|
# discard_case <name> <setup> <status> <gone|kept> <want> <unwanted> [cmd...]
|
||||||
|
discard_case() {
|
||||||
|
_dc_name="$1"
|
||||||
|
_dc_setup="$2"
|
||||||
|
_dc_want_status="$3"
|
||||||
|
_dc_want_dist="$4"
|
||||||
|
_dc_want="$5"
|
||||||
|
_dc_unwanted="$6"
|
||||||
|
shift 6
|
||||||
|
|
||||||
|
build_fixture
|
||||||
|
if ! (cd "$FIXTURE" && "$_dc_setup") >/dev/null 2>&1; then
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
echo " FAIL: $_dc_name"
|
||||||
|
echo " the case's own setup failed, so nothing was tested."
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
_dc_status=0
|
||||||
|
_dc_out="$(cd "$FIXTURE" &&
|
||||||
|
"$FIXTURE/script/discard-dist-on-failure" "$@" 2>&1)" || _dc_status=$?
|
||||||
|
|
||||||
|
_ok=yes
|
||||||
|
_why=""
|
||||||
|
|
||||||
|
if [ "$_dc_status" -ne "$_dc_want_status" ]; then
|
||||||
|
_ok=no
|
||||||
|
_why="exit status $_dc_status, wanted $_dc_want_status"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The assertion this case exists for: what is on disk now.
|
||||||
|
if [ -e "$FIXTURE/dist" ] || [ -h "$FIXTURE/dist" ]; then
|
||||||
|
_dc_dist=kept
|
||||||
|
else
|
||||||
|
_dc_dist=gone
|
||||||
|
fi
|
||||||
|
if [ "$_dc_dist" != "$_dc_want_dist" ]; then
|
||||||
|
_ok=no
|
||||||
|
_why="${_why:+$_why; }dist/ is $_dc_dist after the run, wanted"
|
||||||
|
_why="$_why $_dc_want_dist"
|
||||||
|
elif [ "$_dc_want_dist" = kept ] &&
|
||||||
|
[ ! -f "$FIXTURE/dist/chrome/src/popup/index.js" ]; then
|
||||||
|
# Kept has to mean intact: a dist/ emptied out is not one left alone.
|
||||||
|
_ok=no
|
||||||
|
_why="${_why:+$_why; }dist/ survived but its emitted bundle did not"
|
||||||
|
fi
|
||||||
|
|
||||||
|
_dc_check_message "$_dc_want" want
|
||||||
|
_dc_check_message "$_dc_unwanted" unwanted
|
||||||
|
|
||||||
|
if [ "$_ok" = yes ]; then
|
||||||
|
PASSED=$((PASSED + 1))
|
||||||
|
echo " ok: $_dc_name"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
echo " FAIL: $_dc_name"
|
||||||
|
echo " $_why"
|
||||||
|
echo " --- discard-dist-on-failure output ---"
|
||||||
|
printf '%s\n' "$_dc_out" | sed 's/^/ /'
|
||||||
|
echo " --- end output ---"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Require ($2 = want) or forbid ($2 = unwanted) a substring in the wrapper's
|
||||||
|
# output, updating _ok and _why. An empty substring asserts nothing. Same grep
|
||||||
|
# discipline as everywhere else here: 0 and 1 are answers, anything else means
|
||||||
|
# the message was never checked.
|
||||||
|
_dc_check_message() {
|
||||||
|
[ -n "$1" ] || return 0
|
||||||
|
|
||||||
|
_dcm_g=0
|
||||||
|
printf '%s\n' "$_dc_out" | grep -q -F -e "$1" || _dcm_g=$?
|
||||||
|
case "$_dcm_g" in
|
||||||
|
0)
|
||||||
|
[ "$2" = unwanted ] || return 0
|
||||||
|
_ok=no
|
||||||
|
_why="${_why:+$_why; }message contained: $1"
|
||||||
|
;;
|
||||||
|
1)
|
||||||
|
[ "$2" = want ] || return 0
|
||||||
|
_ok=no
|
||||||
|
_why="${_why:+$_why; }message did not contain: $1"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
_ok=no
|
||||||
|
_why="${_why:+$_why; }grep exited $_dcm_g matching the message, so the
|
||||||
|
message was never checked"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
# --- Makefile wiring --------------------------------------------------------
|
# --- Makefile wiring --------------------------------------------------------
|
||||||
|
|
||||||
# The verifier cases above prove what verify-build does when it is told what to
|
# The verifier cases above prove what verify-build does when it is told what to
|
||||||
# expect. This proves the Makefile tells it — with the mode as an argument, on
|
# expect, and the discard cases prove what the wrapper does with dist/. This
|
||||||
# a scrubbed environment, and identically whether or not AUTISTMASK_DEBUG is
|
# proves the Makefile wires both up — the mode as an argument, on a scrubbed
|
||||||
# exported in the shell that ran make. Read off `make -n`, so no build runs.
|
# environment, identically whether or not AUTISTMASK_DEBUG is exported in the
|
||||||
|
# shell that ran make, and the wrapper on the release path only. Read off
|
||||||
|
# `make -n`, so no build runs.
|
||||||
check_makefile_wiring() {
|
check_makefile_wiring() {
|
||||||
if ! command -v make >/dev/null 2>&1; then
|
if ! command -v make >/dev/null 2>&1; then
|
||||||
SKIPPED=$((SKIPPED + 1))
|
SKIPPED=$((SKIPPED + 1))
|
||||||
@@ -537,6 +653,34 @@ check_makefile_wiring() {
|
|||||||
build-debug "verify-build --expect debug"
|
build-debug "verify-build --expect debug"
|
||||||
_wiring_case "make build-debug scrubs AUTISTMASK_DEBUG for the verifier" \
|
_wiring_case "make build-debug scrubs AUTISTMASK_DEBUG for the verifier" \
|
||||||
build-debug "env -u AUTISTMASK_DEBUG"
|
build-debug "env -u AUTISTMASK_DEBUG"
|
||||||
|
|
||||||
|
# The release path runs its steps through the wrapper, including the final
|
||||||
|
# check-censored pass; the debug path runs none of them through it, which is
|
||||||
|
# what keeps a failed debug build's dist/ on disk.
|
||||||
|
_wiring_case "make build wraps its steps in discard-dist-on-failure" \
|
||||||
|
build "script/discard-dist-on-failure"
|
||||||
|
_wiring_case "make build wraps check-censored --require-dist too" \
|
||||||
|
build "script/discard-dist-on-failure script/check-censored"
|
||||||
|
_wiring_case_absent "make build-debug never discards its dist/" \
|
||||||
|
build-debug "discard-dist-on-failure"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Run `make -n TARGET` with AUTISTMASK_DEBUG=1 exported, into _wc_out. Returns
|
||||||
|
# non-zero, having already reported the failure, when make itself failed: a
|
||||||
|
# recipe that could not be printed was never checked.
|
||||||
|
_wiring_make_n() {
|
||||||
|
AUTISTMASK_DEBUG=1
|
||||||
|
export AUTISTMASK_DEBUG
|
||||||
|
_wc_status=0
|
||||||
|
_wc_out="$(cd "$ROOT" && make -n "$_wc_target" 2>&1)" || _wc_status=$?
|
||||||
|
unset AUTISTMASK_DEBUG
|
||||||
|
|
||||||
|
[ "$_wc_status" -ne 0 ] || return 0
|
||||||
|
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
echo " FAIL: $_wc_name"
|
||||||
|
echo " make -n $_wc_target exited $_wc_status"
|
||||||
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
_wiring_case() {
|
_wiring_case() {
|
||||||
@@ -544,18 +688,7 @@ _wiring_case() {
|
|||||||
_wc_target="$2"
|
_wc_target="$2"
|
||||||
_wc_want="$3"
|
_wc_want="$3"
|
||||||
|
|
||||||
AUTISTMASK_DEBUG=1
|
_wiring_make_n || return 0
|
||||||
export AUTISTMASK_DEBUG
|
|
||||||
_wc_status=0
|
|
||||||
_wc_out="$(cd "$ROOT" && make -n "$_wc_target" 2>&1)" || _wc_status=$?
|
|
||||||
unset AUTISTMASK_DEBUG
|
|
||||||
|
|
||||||
if [ "$_wc_status" -ne 0 ]; then
|
|
||||||
FAILED=$((FAILED + 1))
|
|
||||||
echo " FAIL: $_wc_name"
|
|
||||||
echo " make -n $_wc_target exited $_wc_status"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
_wc_g=0
|
_wc_g=0
|
||||||
printf '%s\n' "$_wc_out" | grep -q -F -e "$_wc_want" || _wc_g=$?
|
printf '%s\n' "$_wc_out" | grep -q -F -e "$_wc_want" || _wc_g=$?
|
||||||
@@ -577,6 +710,34 @@ _wiring_case() {
|
|||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# The inverse: the recipe must NOT run something.
|
||||||
|
_wiring_case_absent() {
|
||||||
|
_wc_name="$1"
|
||||||
|
_wc_target="$2"
|
||||||
|
_wc_want="$3"
|
||||||
|
|
||||||
|
_wiring_make_n || return 0
|
||||||
|
|
||||||
|
_wc_g=0
|
||||||
|
printf '%s\n' "$_wc_out" | grep -q -F -e "$_wc_want" || _wc_g=$?
|
||||||
|
case "$_wc_g" in
|
||||||
|
1)
|
||||||
|
PASSED=$((PASSED + 1))
|
||||||
|
echo " ok: $_wc_name"
|
||||||
|
;;
|
||||||
|
0)
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
echo " FAIL: $_wc_name"
|
||||||
|
echo " make -n $_wc_target runs: $_wc_want"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
FAILED=$((FAILED + 1))
|
||||||
|
echo " FAIL: $_wc_name"
|
||||||
|
echo " grep exited $_wc_g, so the recipe was never checked"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
run_cases() {
|
run_cases() {
|
||||||
check_case "control: untouched dist passes" \
|
check_case "control: untouched dist passes" \
|
||||||
no release 0 "2 bundle(s) $MARKER_OFF" c_control
|
no release 0 "2 bundle(s) $MARKER_OFF" c_control
|
||||||
@@ -712,6 +873,18 @@ run_cases() {
|
|||||||
no release 1 "carries a debug marker but the build did not" \
|
no release 1 "carries a debug marker but the build did not" \
|
||||||
c_marker_on_plain_file
|
c_marker_on_plain_file
|
||||||
|
|
||||||
|
discard_case "a failed release build step removes dist/" \
|
||||||
|
c_control 3 gone "dist/ WAS REMOVED" "" sh -c 'exit 3'
|
||||||
|
|
||||||
|
discard_case "a successful release build step leaves dist/ alone" \
|
||||||
|
c_control 0 kept "" "REMOVED" true
|
||||||
|
|
||||||
|
discard_case "a failed release build step with no dist/ says there was none" \
|
||||||
|
c_no_dist 3 gone "There was no dist/ to remove" "" sh -c 'exit 3'
|
||||||
|
|
||||||
|
discard_case "the wrapper given no command removes nothing" \
|
||||||
|
c_control 1 kept "no command given" ""
|
||||||
|
|
||||||
check_makefile_wiring
|
check_makefile_wiring
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -740,6 +913,10 @@ main() {
|
|||||||
echo "test-verify-build: $VERIFY_BUILD is missing or not executable" >&2
|
echo "test-verify-build: $VERIFY_BUILD is missing or not executable" >&2
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
[ -x "$DISCARD_DIST" ] || {
|
||||||
|
echo "test-verify-build: $DISCARD_DIST is missing or not executable" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
echo "Testing script/verify-build failure modes..."
|
echo "Testing script/verify-build failure modes..."
|
||||||
pick_sha256_tool
|
pick_sha256_tool
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/verify-build: assert that dist/ holds exactly what the build that just
|
# script/verify-build: assert that the regular files and symlinks under dist/
|
||||||
# ran emitted, and that the compiled DEBUG state of that output is the one the
|
# are exactly what the build that just ran emitted (other file types are out of
|
||||||
# caller asked for. Our own extension to scripts-to-rule-them-all, run at the
|
# scope; see "What that does and does not establish" below), and that the
|
||||||
# end of make build / make build-debug.
|
# compiled DEBUG state of that output is the one the caller asked for. Our own
|
||||||
|
# extension to scripts-to-rule-them-all, run at the end of make build /
|
||||||
|
# make build-debug.
|
||||||
#
|
#
|
||||||
# Why the DEBUG half exists: DEBUG makes the publicly committed test recovery
|
# Why the DEBUG half exists: DEBUG makes the publicly committed test recovery
|
||||||
# phrase the output of wallet creation, so a release artifact built with it live
|
# phrase the output of wallet creation, so a release artifact built with it live
|
||||||
@@ -29,12 +31,16 @@
|
|||||||
# path fresh per invocation, outside the repo, and deletes it afterwards.
|
# path fresh per invocation, outside the repo, and deletes it afterwards.
|
||||||
#
|
#
|
||||||
# What that does and does not establish. It establishes that dist/ is byte for
|
# What that does and does not establish. It establishes that dist/ is byte for
|
||||||
# byte the output of the build.js run that just finished, with nothing added,
|
# byte the output of the build.js run that just finished, with no regular file
|
||||||
# nothing missing and nothing altered in between, and that the audited bundles
|
# or symlink added, missing or altered in between, and that the audited bundles
|
||||||
# in it compiled to the requested mode. It does NOT establish that the source
|
# in it compiled to the requested mode. Regular files and symlinks are the whole
|
||||||
# tree or build.js were honest, and it says nothing at all to someone handed a
|
# of what the tree walk covers; fifos, sockets, device nodes and empty
|
||||||
# dist/ from elsewhere: without the receipt from its own build they have no
|
# directories under dist/ are not checked, because a build emits none of them,
|
||||||
# input to this check. That is signing, and it is not this control.
|
# none can carry a shippable payload, and grep on a fifo would hang rather than
|
||||||
|
# fail. It does NOT establish that the source tree or build.js were honest, and
|
||||||
|
# it says nothing at all to someone handed a dist/ from elsewhere: without the
|
||||||
|
# receipt from its own build they have no input to this check. That is signing,
|
||||||
|
# and it is not this control.
|
||||||
#
|
#
|
||||||
# It fails rather than passes whenever it cannot determine something. Minified
|
# It fails rather than passes whenever it cannot determine something. Minified
|
||||||
# output is not a stable contract, so "matched neither marker" is not evidence
|
# output is not a stable contract, so "matched neither marker" is not evidence
|
||||||
@@ -392,8 +398,10 @@ check_receipt_entries() {
|
|||||||
# its own command line, so a linked dist/ collapses this walk to one entry
|
# its own command line, so a linked dist/ collapses this walk to one entry
|
||||||
# and cross-checks nothing.
|
# and cross-checks nothing.
|
||||||
#
|
#
|
||||||
# Types other than regular files and symlinks are left out on purpose: a build
|
# Types other than regular files and symlinks — fifos, sockets, device nodes and
|
||||||
# emits none of them, and grep on a fifo would hang rather than fail.
|
# empty directories — are left out on purpose, and the guarantee is bounded to
|
||||||
|
# what is walked: a build emits none of them, none can carry a shippable
|
||||||
|
# payload, and grep on a fifo would hang rather than fail.
|
||||||
check_dist_tree() {
|
check_dist_tree() {
|
||||||
LISTING="$(mktemp "${TMPDIR:-/tmp}/verify-build-dist.XXXXXX")" ||
|
LISTING="$(mktemp "${TMPDIR:-/tmp}/verify-build-dist.XXXXXX")" ||
|
||||||
fail "could not create a temporary file for the dist/ listing, so the
|
fail "could not create a temporary file for the dist/ listing, so the
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ const {
|
|||||||
resolveTokenDecimals,
|
resolveTokenDecimals,
|
||||||
unknownDecimalsAmount,
|
unknownDecimalsAmount,
|
||||||
} = require("../../shared/approvalAmount");
|
} = require("../../shared/approvalAmount");
|
||||||
|
// Four decimals, with the nonzero floor these screens hold: every amount this
|
||||||
|
// view renders — the ERC-20 line, the ETH value, the max fee — and every one
|
||||||
|
// it carries forward to the wait/success/error screens goes through it.
|
||||||
|
const {
|
||||||
|
truncateAmountNeverZero: formatTxValue,
|
||||||
|
} = require("../../shared/amountDisplay");
|
||||||
const { decryptWithPassword } = require("../../shared/vault");
|
const { decryptWithPassword } = require("../../shared/vault");
|
||||||
const { getSignerForAddress } = require("../../shared/wallet");
|
const { getSignerForAddress } = require("../../shared/wallet");
|
||||||
const { walletDefect } = require("../../shared/walletDefects");
|
const { walletDefect } = require("../../shared/walletDefects");
|
||||||
@@ -40,13 +46,6 @@ function approvalAddressHtml(address) {
|
|||||||
return renderAddressHtml(address, { title });
|
return renderAddressHtml(address, { title });
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatTxValue(val) {
|
|
||||||
const parts = val.split(".");
|
|
||||||
if (parts.length === 1) return val + ".0000";
|
|
||||||
const dec = (parts[1] + "0000").slice(0, 4);
|
|
||||||
return parts[0] + "." + dec;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The amount line for a decoded ERC-20 call. With a known scale it is the
|
// The amount line for a decoded ERC-20 call. With a known scale it is the
|
||||||
// token quantity; with `decimals` null it is the base-unit integer with the
|
// token quantity; with `decimals` null it is the base-unit integer with the
|
||||||
// unknown scale stated, because formatting it with an assumed scale is what
|
// unknown scale stated, because formatting it with an assumed scale is what
|
||||||
@@ -74,6 +73,14 @@ function tokenLabel(address) {
|
|||||||
function decodeCalldata(data, toAddress) {
|
function decodeCalldata(data, toAddress) {
|
||||||
if (!data || data === "0x" || data.length < 10) return null;
|
if (!data || data === "0x" || data.length < 10) return null;
|
||||||
|
|
||||||
|
// Where a token's scale is looked for, for every decoder below: the ERC-20
|
||||||
|
// amount line and the swap's Amount and Min. received lines resolve it the
|
||||||
|
// same way, and refuse to format the same way when it is nowhere.
|
||||||
|
const decimalsSources = {
|
||||||
|
trackedTokens: state.trackedTokens,
|
||||||
|
wallets: state.wallets,
|
||||||
|
};
|
||||||
|
|
||||||
// Try ERC-20 (approve / transfer)
|
// Try ERC-20 (approve / transfer)
|
||||||
try {
|
try {
|
||||||
const parsed = erc20Iface.parseTransaction({ data });
|
const parsed = erc20Iface.parseTransaction({ data });
|
||||||
@@ -85,10 +92,10 @@ function decodeCalldata(data, toAddress) {
|
|||||||
// the wrong number, and for a token with fewer decimals than the
|
// the wrong number, and for a token with fewer decimals than the
|
||||||
// guess it is the wrong number in the direction that reads as
|
// guess it is the wrong number in the direction that reads as
|
||||||
// zero. See tokenAmountText().
|
// zero. See tokenAmountText().
|
||||||
const tokenDecimals = resolveTokenDecimals(toAddress, {
|
const tokenDecimals = resolveTokenDecimals(
|
||||||
trackedTokens: state.trackedTokens,
|
toAddress,
|
||||||
wallets: state.wallets,
|
decimalsSources,
|
||||||
});
|
);
|
||||||
const contractLabel = tokenSymbol
|
const contractLabel = tokenSymbol
|
||||||
? tokenSymbol + " (" + toAddress + ")"
|
? tokenSymbol + " (" + toAddress + ")"
|
||||||
: toAddress;
|
: toAddress;
|
||||||
@@ -168,7 +175,7 @@ function decodeCalldata(data, toAddress) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Try Uniswap Universal Router
|
// Try Uniswap Universal Router
|
||||||
const routerResult = uniswap.decode(data, toAddress);
|
const routerResult = uniswap.decode(data, toAddress, decimalsSources);
|
||||||
if (routerResult) return routerResult;
|
if (routerResult) return routerResult;
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
46
src/shared/amountDisplay.js
Normal file
46
src/shared/amountDisplay.js
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
// The 4-decimal amount rule from README.md's Display Consistency section, and
|
||||||
|
// the one exception to it, in one place. Three call sites had grown their own
|
||||||
|
// copy of the truncation — the history and balance lists
|
||||||
|
// (`src/shared/transactions.js`), the approval screen's ERC-20 amount line
|
||||||
|
// (`src/popup/views/approval.js`) and its Uniswap swap detail lines
|
||||||
|
// (`src/shared/uniswap.js`) — and a fix applied to one of them left the other
|
||||||
|
// two showing a different number for the same value.
|
||||||
|
//
|
||||||
|
// The two functions below are the two policies, not two implementations of
|
||||||
|
// one: summary lists truncate, and the screens that state what is being
|
||||||
|
// authorized truncate with a floor. Keeping them adjacent is the point, so a
|
||||||
|
// change to the rule cannot reach one screen and miss another.
|
||||||
|
|
||||||
|
// Truncate to exactly four decimal places. Truncation, never rounding: an
|
||||||
|
// amount must never be displayed as larger than it is, so 0.99999 stays
|
||||||
|
// 0.9999.
|
||||||
|
function truncateAmount(val) {
|
||||||
|
const parts = val.split(".");
|
||||||
|
if (parts.length === 1) return val + ".0000";
|
||||||
|
return parts[0] + "." + (parts[1] + "0000").slice(0, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same rule, plus the invariant the approval and confirmation screens
|
||||||
|
// hold: a nonzero amount never renders as zero. Truncating to four decimals
|
||||||
|
// does exactly that to an amount below 0.0001 — one base unit of an 18-decimal
|
||||||
|
// token, 500 of an 8-decimal one — and a real transfer or allowance then reads
|
||||||
|
// as "nothing is being moved" on the screen whose whole job is to say what is
|
||||||
|
// being authorized.
|
||||||
|
//
|
||||||
|
// When the truncated string carries no significant digit and the value does,
|
||||||
|
// the amount is extended to its first significant digit instead. It stays in
|
||||||
|
// token units, the same unit as the symbol printed beside it. A genuine zero
|
||||||
|
// still renders 0.0000, and anything at or above the floor is untouched.
|
||||||
|
function truncateAmountNeverZero(val) {
|
||||||
|
const truncated = truncateAmount(val);
|
||||||
|
// Tests the whole truncated string, integer part included: 1.00005 has a
|
||||||
|
// significant digit already and stays 1.0000.
|
||||||
|
if (/[1-9]/.test(truncated)) return truncated;
|
||||||
|
const parts = val.split(".");
|
||||||
|
if (parts.length === 1) return truncated;
|
||||||
|
const sig = parts[1].search(/[1-9]/);
|
||||||
|
if (sig === -1) return truncated;
|
||||||
|
return parts[0] + "." + parts[1].slice(0, sig + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { truncateAmount, truncateAmountNeverZero };
|
||||||
@@ -14,6 +14,10 @@
|
|||||||
// them answers, unknownDecimalsAmount() renders the base-unit integer with the
|
// them answers, unknownDecimalsAmount() renders the base-unit integer with the
|
||||||
// unknown scale stated, and no formatUnits() call is reached at all.
|
// unknown scale stated, and no formatUnits() call is reached at all.
|
||||||
//
|
//
|
||||||
|
// The Uniswap decoder's Amount and Min. received lines land on this same
|
||||||
|
// screen and use these same two functions, so there is one way of resolving a
|
||||||
|
// scale and one way of saying there is none.
|
||||||
|
//
|
||||||
// This is the display counterpart to transferAmount.js, which takes the same
|
// This is the display counterpart to transferAmount.js, which takes the same
|
||||||
// stance on the wallet's own send path: an amount whose scale is unknown or
|
// stance on the wallet's own send path: an amount whose scale is unknown or
|
||||||
// disputed is refused rather than guessed at.
|
// disputed is refused rather than guessed at.
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { networkById } = require("./networks");
|
|||||||
const { RESTORABLE_VIEWS } = require("../popup/restorableViews");
|
const { RESTORABLE_VIEWS } = require("../popup/restorableViews");
|
||||||
|
|
||||||
const { storageGet, storageSet } = require("./browserApi");
|
const { storageGet, storageSet } = require("./browserApi");
|
||||||
|
const { log } = require("./log");
|
||||||
|
|
||||||
const DEFAULT_STATE = {
|
const DEFAULT_STATE = {
|
||||||
hasWallet: false,
|
hasWallet: false,
|
||||||
@@ -88,135 +89,529 @@ function currentNetwork() {
|
|||||||
return networkById(state.networkId);
|
return networkById(state.networkId);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveState() {
|
// Every field written to and read from the single "autistmask" storage key.
|
||||||
const persisted = {
|
// hasWallet is deliberately excluded from the diffing/merge logic below —
|
||||||
hasWallet: state.hasWallet,
|
// like loadState() does, it is always derived from `wallets`, never carried
|
||||||
wallets: state.wallets,
|
// as an independent value.
|
||||||
trackedTokens: state.trackedTokens,
|
const PERSISTED_FIELDS = Object.keys(DEFAULT_STATE)
|
||||||
networkId: state.networkId,
|
.filter((key) => key !== "hasWallet")
|
||||||
rpcUrl: state.rpcUrl,
|
.concat([
|
||||||
blockscoutUrl: state.blockscoutUrl,
|
"currentView",
|
||||||
networkEndpoints: state.networkEndpoints,
|
"selectedWallet",
|
||||||
lastBalanceRefresh: state.lastBalanceRefresh,
|
"selectedAddress",
|
||||||
activeAddress: state.activeAddress,
|
"selectedToken",
|
||||||
allowedSites: state.allowedSites,
|
"viewData",
|
||||||
deniedSites: state.deniedSites,
|
"viewStack",
|
||||||
rememberSiteChoice: state.rememberSiteChoice,
|
]);
|
||||||
showZeroBalanceTokens: state.showZeroBalanceTokens,
|
|
||||||
hideSpoofedSymbols: state.hideSpoofedSymbols,
|
// Turn a raw stored (or missing) record into the full, defaulted shape
|
||||||
hideLowHolderTokens: state.hideLowHolderTokens,
|
// loadState() used to assign directly onto `state`. Pulled out as a pure
|
||||||
hideFraudContracts: state.hideFraudContracts,
|
// function so saveState() can apply it too: the fields THIS page did not
|
||||||
hideDustTransactions: state.hideDustTransactions,
|
// change still have to come from storage in their loaded-and-normalized
|
||||||
dustThresholdGwei: state.dustThresholdGwei,
|
// form, not as the raw bytes another page (or an old release) left there —
|
||||||
utcTimestamps: state.utcTimestamps,
|
// otherwise a legacy shape a load has always self-healed in memory (a
|
||||||
fraudContracts: state.fraudContracts,
|
// missing networkEndpoints map, an out-of-range flag) is dropped right back
|
||||||
tokenHolderCache: state.tokenHolderCache,
|
// into storage unfixed every time the page that DID normalize it saves
|
||||||
theme: state.theme,
|
// something unrelated, because that field's value never "changed" for that
|
||||||
debugMode: state.debugMode,
|
// page to notice.
|
||||||
currentView: state.currentView,
|
function normalizePersisted(saved) {
|
||||||
selectedWallet: state.selectedWallet,
|
saved = saved || {};
|
||||||
selectedAddress: state.selectedAddress,
|
const out = {};
|
||||||
selectedToken: state.selectedToken,
|
out.wallets = saved.wallets || [];
|
||||||
viewData: state.viewData,
|
// Derived, never trusted verbatim off storage — see loadState().
|
||||||
viewStack: state.viewStack,
|
out.hasWallet = out.wallets.length > 0;
|
||||||
};
|
out.trackedTokens = saved.trackedTokens || [];
|
||||||
await storageSet({ autistmask: persisted });
|
out.networkId = saved.networkId || DEFAULT_STATE.networkId;
|
||||||
|
out.rpcUrl = saved.rpcUrl || DEFAULT_STATE.rpcUrl;
|
||||||
|
out.blockscoutUrl = saved.blockscoutUrl || DEFAULT_STATE.blockscoutUrl;
|
||||||
|
// An actual object is required, not merely a truthy non-array: the code
|
||||||
|
// below and onChainSwitch() index and ASSIGN INTO this value, and
|
||||||
|
// assigning a property to a string or a number is a silent no-op in
|
||||||
|
// sloppy mode. Copied rather than referenced, nested pairs included, so
|
||||||
|
// normalizing never mutates the object a caller handed in.
|
||||||
|
const rawEndpoints =
|
||||||
|
typeof saved.networkEndpoints === "object" &&
|
||||||
|
saved.networkEndpoints !== null &&
|
||||||
|
!Array.isArray(saved.networkEndpoints)
|
||||||
|
? saved.networkEndpoints
|
||||||
|
: {};
|
||||||
|
out.networkEndpoints = {};
|
||||||
|
for (const netId of Object.keys(rawEndpoints)) {
|
||||||
|
out.networkEndpoints[netId] = { ...rawEndpoints[netId] };
|
||||||
|
}
|
||||||
|
// A profile written before this map existed carries exactly one pair of
|
||||||
|
// endpoints, belonging to whatever network it was last on. Adopt it as
|
||||||
|
// that network's remembered pair, so a custom endpoint set on the old
|
||||||
|
// build is not lost by the first switch away and back.
|
||||||
|
if (!out.networkEndpoints[out.networkId]) {
|
||||||
|
out.networkEndpoints[out.networkId] = {
|
||||||
|
rpcUrl: out.rpcUrl,
|
||||||
|
blockscoutUrl: out.blockscoutUrl,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
out.lastBalanceRefresh = saved.lastBalanceRefresh || 0;
|
||||||
|
out.activeAddress = saved.activeAddress || null;
|
||||||
|
out.allowedSites =
|
||||||
|
saved.allowedSites && !Array.isArray(saved.allowedSites)
|
||||||
|
? saved.allowedSites
|
||||||
|
: {};
|
||||||
|
out.deniedSites =
|
||||||
|
saved.deniedSites && !Array.isArray(saved.deniedSites)
|
||||||
|
? saved.deniedSites
|
||||||
|
: {};
|
||||||
|
out.rememberSiteChoice =
|
||||||
|
saved.rememberSiteChoice !== undefined
|
||||||
|
? saved.rememberSiteChoice
|
||||||
|
: true;
|
||||||
|
out.showZeroBalanceTokens =
|
||||||
|
saved.showZeroBalanceTokens !== undefined
|
||||||
|
? saved.showZeroBalanceTokens
|
||||||
|
: 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.
|
||||||
|
out.hideSpoofedSymbols =
|
||||||
|
saved.hideSpoofedSymbols !== undefined
|
||||||
|
? saved.hideSpoofedSymbols
|
||||||
|
: true;
|
||||||
|
out.hideLowHolderTokens =
|
||||||
|
saved.hideLowHolderTokens !== undefined
|
||||||
|
? saved.hideLowHolderTokens
|
||||||
|
: true;
|
||||||
|
out.hideFraudContracts =
|
||||||
|
saved.hideFraudContracts !== undefined
|
||||||
|
? saved.hideFraudContracts
|
||||||
|
: true;
|
||||||
|
out.hideDustTransactions =
|
||||||
|
saved.hideDustTransactions !== undefined
|
||||||
|
? saved.hideDustTransactions
|
||||||
|
: true;
|
||||||
|
out.dustThresholdGwei =
|
||||||
|
saved.dustThresholdGwei !== undefined
|
||||||
|
? saved.dustThresholdGwei
|
||||||
|
: 100000;
|
||||||
|
out.utcTimestamps =
|
||||||
|
saved.utcTimestamps !== undefined ? saved.utcTimestamps : false;
|
||||||
|
out.fraudContracts = saved.fraudContracts || [];
|
||||||
|
out.tokenHolderCache = saved.tokenHolderCache || {};
|
||||||
|
out.theme = saved.theme || "system";
|
||||||
|
out.debugMode = saved.debugMode !== undefined ? saved.debugMode : false;
|
||||||
|
out.currentView = saved.currentView || null;
|
||||||
|
out.selectedWallet =
|
||||||
|
saved.selectedWallet !== undefined ? saved.selectedWallet : null;
|
||||||
|
out.selectedAddress =
|
||||||
|
saved.selectedAddress !== undefined ? saved.selectedAddress : null;
|
||||||
|
out.selectedToken = saved.selectedToken || null;
|
||||||
|
out.viewData = saved.viewData || {};
|
||||||
|
out.viewStack = restorableStack(saved.viewStack, out.currentView);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The persisted fields as they stood at the end of this page's last
|
||||||
|
// loadState() or saveState(). saveState() diffs the live state against this
|
||||||
|
// to find only the fields THIS page actually changed.
|
||||||
|
//
|
||||||
|
// Deep-cloned, not a reference: callers mutate persisted objects and arrays
|
||||||
|
// in place (state.wallets.push(...)), and a reference baseline would mutate
|
||||||
|
// right along with `state`, so the diff would always come out empty.
|
||||||
|
let baseline = null;
|
||||||
|
|
||||||
|
function snapshotPersisted() {
|
||||||
|
const out = {};
|
||||||
|
for (const key of PERSISTED_FIELDS) out[key] = state[key];
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deepEqual(a, b) {
|
||||||
|
if (a === b) return true;
|
||||||
|
if (typeof a !== "object" || typeof b !== "object") return false;
|
||||||
|
if (a === null || b === null) return false;
|
||||||
|
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
||||||
|
const aKeys = Object.keys(a);
|
||||||
|
const bKeys = Object.keys(b);
|
||||||
|
if (aKeys.length !== bKeys.length) return false;
|
||||||
|
for (const key of aKeys) {
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
|
||||||
|
if (!deepEqual(a[key], b[key])) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stable identity for a wallet, independent of its position in the array
|
||||||
|
// (which shifts under a concurrent add/delete elsewhere) and independent of
|
||||||
|
// its mutable fields (name is user-editable; addresses gains/loses entries
|
||||||
|
// via scanning and deleteAddress.js). An "hd"/"xprv" wallet's xpub never
|
||||||
|
// changes for its lifetime and is already enforced unique
|
||||||
|
// (findWalletByXpub() in addWallet.js). A "key" wallet has no xpub, exactly
|
||||||
|
// one address for its whole lifetime (nothing ever adds to or removes from
|
||||||
|
// a key wallet's address list), and that address is already enforced
|
||||||
|
// unique (findWalletByAddress()) — so it stands in for identity there.
|
||||||
|
// Neither invariant is enforced by this function or by
|
||||||
|
// mergeListByIdentity() below — they hold only because every wallet-
|
||||||
|
// creation path in addWallet.js happens to populate one or the other before
|
||||||
|
// the wallet ever reaches state.wallets, and because canRemoveAddress() in
|
||||||
|
// walletDelete.js never lets a wallet's address list go to zero. A wallet
|
||||||
|
// with neither (an empty/legacy/corrupt record) falls back to the same
|
||||||
|
// "addr:" identity as every other such record, which is a genuine
|
||||||
|
// collision, not a proxy for one — see the collision handling in
|
||||||
|
// mergeListByIdentity().
|
||||||
|
function walletIdentity(wallet) {
|
||||||
|
if (wallet.xpub) return "xpub:" + wallet.xpub;
|
||||||
|
const first = wallet.addresses && wallet.addresses[0];
|
||||||
|
return "addr:" + (first ? String(first.address).toLowerCase() : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stable identity for an address within one wallet's address list. An
|
||||||
|
// address is unique within its wallet and, once derived or imported, never
|
||||||
|
// changes — only whether it is present.
|
||||||
|
function addressIdentity(addr) {
|
||||||
|
return String(addr.address).toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge one array of identity-bearing objects (wallets, or the addresses
|
||||||
|
// inside one wallet) by identity rather than by array index — an index
|
||||||
|
// shifts under a concurrent insert/delete elsewhere, which would merge the
|
||||||
|
// wrong pair of objects entirely.
|
||||||
|
//
|
||||||
|
// `theirs` (fresh storage) sets the membership baseline and the order:
|
||||||
|
// - An item this page never had baseline knowledge of, but that is in
|
||||||
|
// `theirs`, was added by someone else — kept as-is.
|
||||||
|
// - An item `base` had and `ours` no longer has was deleted by THIS page
|
||||||
|
// — dropped even though `theirs` still has it (this page's own delete
|
||||||
|
// must win over a background save that only touched leaf fields).
|
||||||
|
// - An item present in both `ours` and `theirs` is merged leaf-by-leaf via
|
||||||
|
// `mergeItem`, so a leaf this page changed (e.g. a renamed wallet) lands
|
||||||
|
// on top of `theirs`' otherwise-current copy (e.g. a refreshed balance).
|
||||||
|
// Anything left in `ours` that `base` never had and `theirs` does not have
|
||||||
|
// yet is this page's own new addition — appended.
|
||||||
|
//
|
||||||
|
// `identityOf` is not guaranteed collision-free (walletIdentity() falls
|
||||||
|
// back to one shared "addr:" value for any wallet with neither an xpub nor
|
||||||
|
// a populated first address). Two records that collide under it must never
|
||||||
|
// silently collapse into one — that is exactly how this function used to
|
||||||
|
// drop a wallet, encryptedSecret included, with no error and no log. Two
|
||||||
|
// defenses:
|
||||||
|
// - `ours` is indexed into GROUPS, not a single item per identity, so two
|
||||||
|
// colliding live items on this page can't overwrite each other in the
|
||||||
|
// index before the merge below even runs.
|
||||||
|
// - A matched pair with no shared `base` entry (neither page ever agreed
|
||||||
|
// on this identity) is only merged leaf-by-leaf when the two sides are
|
||||||
|
// already equal. If they differ, that is not "the same record edited
|
||||||
|
// twice", it is two different records that happen to share an identity
|
||||||
|
// — both are kept, unmerged, rather than guessing which one is real.
|
||||||
|
function mergeListByIdentity(base, ours, theirs, identityOf, mergeItem) {
|
||||||
|
base = base || [];
|
||||||
|
ours = ours || [];
|
||||||
|
theirs = theirs || [];
|
||||||
|
const baseIndex = new Map(base.map((item) => [identityOf(item), item]));
|
||||||
|
const oursIndex = new Map();
|
||||||
|
for (const item of ours) {
|
||||||
|
const id = identityOf(item);
|
||||||
|
if (!oursIndex.has(id)) oursIndex.set(id, []);
|
||||||
|
oursIndex.get(id).push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = [];
|
||||||
|
const seen = new Set();
|
||||||
|
|
||||||
|
for (const theirItem of theirs) {
|
||||||
|
const id = identityOf(theirItem);
|
||||||
|
seen.add(id);
|
||||||
|
const oursGroup = oursIndex.get(id);
|
||||||
|
if (baseIndex.has(id) && !oursGroup) continue;
|
||||||
|
if (oursGroup) {
|
||||||
|
const baseItem = baseIndex.get(id);
|
||||||
|
if (!baseItem && !deepEqual(oursGroup[0], theirItem)) {
|
||||||
|
log.errorf(
|
||||||
|
"state: identity collision merging",
|
||||||
|
JSON.stringify(id),
|
||||||
|
"- keeping both records instead of dropping one",
|
||||||
|
);
|
||||||
|
result.push(theirItem, ...oursGroup);
|
||||||
|
} else {
|
||||||
|
result.push(mergeItem(baseItem, oursGroup[0], theirItem));
|
||||||
|
for (let i = 1; i < oursGroup.length; i++) {
|
||||||
|
result.push(oursGroup[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result.push(theirItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of ours) {
|
||||||
|
const id = identityOf(item);
|
||||||
|
if (seen.has(id)) continue;
|
||||||
|
if (!baseIndex.has(id)) result.push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge one wallet's scalar/leaf fields (name, encryptedSecret, nextIndex,
|
||||||
|
// ...) against base, then recurse into its address list by identity. `base`
|
||||||
|
// is null when this page created the wallet itself and no other page has
|
||||||
|
// (yet) produced a same-identity record — nothing to merge in that case,
|
||||||
|
// this page's own copy wins outright. mergeListByIdentity() only ever calls
|
||||||
|
// this with `!base` when `ours` and `theirs` are already equal (a genuine
|
||||||
|
// collision between two DIFFERENT same-identity records is caught and kept
|
||||||
|
// as two separate entries before this function is reached), so returning
|
||||||
|
// `ours` here can't discard a different wallet's data.
|
||||||
|
function mergeWallet(base, ours, theirs) {
|
||||||
|
if (!base) return ours;
|
||||||
|
const merged = { ...theirs };
|
||||||
|
for (const key of Object.keys(ours)) {
|
||||||
|
if (key === "addresses") continue;
|
||||||
|
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||||
|
}
|
||||||
|
merged.addresses = mergeListByIdentity(
|
||||||
|
base.addresses,
|
||||||
|
ours.addresses,
|
||||||
|
theirs.addresses,
|
||||||
|
addressIdentity,
|
||||||
|
mergeAddress,
|
||||||
|
);
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge one address's leaf fields (balance, ensName, tokenBalances, ...).
|
||||||
|
// tokenBalances is itself an array, but only backgroundRefresh() ever
|
||||||
|
// writes it and always wholesale (refreshBalances() in
|
||||||
|
// src/shared/balances.js), so there is no membership to reconcile within
|
||||||
|
// it — it is a leaf like balance or ensName, not a list with its own
|
||||||
|
// identity.
|
||||||
|
function mergeAddress(base, ours, theirs) {
|
||||||
|
if (!base) return ours;
|
||||||
|
const merged = { ...theirs };
|
||||||
|
for (const key of Object.keys(ours)) {
|
||||||
|
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge a plain object keyed by string (allowedSites/deniedSites: address ->
|
||||||
|
// hostname list; networkEndpoints: networkId -> {rpcUrl, blockscoutUrl}) the
|
||||||
|
// same way mergeListByIdentity() merges an array — by key, not by whole-
|
||||||
|
// object diff — so a key one page added or removed applies independently of
|
||||||
|
// a key another page edited. Unlike an array's identity function, an object
|
||||||
|
// key can't collide with a different logical entry (Object.keys() is
|
||||||
|
// already deduplicated), so this needs no collision floor of its own.
|
||||||
|
function mergeMapByKey(base, ours, theirs, mergeLeaf) {
|
||||||
|
base = base || {};
|
||||||
|
ours = ours || {};
|
||||||
|
theirs = theirs || {};
|
||||||
|
const result = {};
|
||||||
|
const seen = new Set();
|
||||||
|
|
||||||
|
for (const key of Object.keys(theirs)) {
|
||||||
|
seen.add(key);
|
||||||
|
const inBase = Object.prototype.hasOwnProperty.call(base, key);
|
||||||
|
const inOurs = Object.prototype.hasOwnProperty.call(ours, key);
|
||||||
|
if (inBase && !inOurs) continue; // this page deleted the whole entry
|
||||||
|
if (inOurs) {
|
||||||
|
result[key] = mergeLeaf(base[key], ours[key], theirs[key]);
|
||||||
|
} else {
|
||||||
|
result[key] = theirs[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of Object.keys(ours)) {
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(base, key)) {
|
||||||
|
result[key] = ours[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// allowedSites/deniedSites: { [address]: [hostname, ...] }. The hostname
|
||||||
|
// list is itself membership, not a leaf — src/background/index.js pushes a
|
||||||
|
// newly approved/denied hostname onto it in place, and the Settings "revoke"
|
||||||
|
// button (src/popup/views/settings.js) filters a hostname out of it in
|
||||||
|
// place, from a different page. Merge it the same way wallets are merged:
|
||||||
|
// identity is the hostname itself, so a merged pair is always equal and
|
||||||
|
// mergeItem is a no-op pick.
|
||||||
|
function mergeHostnameList(base, ours, theirs) {
|
||||||
|
return mergeListByIdentity(
|
||||||
|
base,
|
||||||
|
ours,
|
||||||
|
theirs,
|
||||||
|
(hostname) => hostname,
|
||||||
|
(b, o, t) => t,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeSiteMap(base, ours, theirs) {
|
||||||
|
return mergeMapByKey(base, ours, theirs, mergeHostnameList);
|
||||||
|
}
|
||||||
|
|
||||||
|
// networkEndpoints: { [networkId]: {rpcUrl, blockscoutUrl} }. onChainSwitch()
|
||||||
|
// (src/shared/chainSwitch.js) writes state.networkEndpoints[networkId] in
|
||||||
|
// place before saving. No code path ever removes a key from this map, so the
|
||||||
|
// membership collision that matters for allowedSites/wallets (an add on one
|
||||||
|
// page racing a delete on another) can't happen here — but two pages
|
||||||
|
// switching to two different networks concurrently still race a whole-field
|
||||||
|
// diff the same way, so it gets the same per-key merge for the leaf edit
|
||||||
|
// case (e.g. Settings saving a custom RPC URL for the active network).
|
||||||
|
function mergeEndpointEntry(base, ours, theirs) {
|
||||||
|
if (!base) return ours;
|
||||||
|
const merged = { ...theirs };
|
||||||
|
for (const key of Object.keys(ours)) {
|
||||||
|
if (!deepEqual(ours[key], base[key])) merged[key] = ours[key];
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeNetworkEndpoints(base, ours, theirs) {
|
||||||
|
return mergeMapByKey(base, ours, theirs, mergeEndpointEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read-modify-write, merged per field, rather than one full-blob write.
|
||||||
|
//
|
||||||
|
// Every extension page (the toolbar popup, a dApp approval window, the
|
||||||
|
// background's backgroundRefresh()) holds its own in-memory `state`, loaded
|
||||||
|
// once, and showView() saves on every navigation. A full-blob write here
|
||||||
|
// clobbers whatever a second page had written since — including, in the
|
||||||
|
// worst case, an entire wallet and its encrypted secret with no attacker
|
||||||
|
// and no unusual input (see the issue this fixes).
|
||||||
|
//
|
||||||
|
// Only the fields this page actually changed — those that differ from
|
||||||
|
// `baseline`, captured at the last loadState()/saveState() on this page —
|
||||||
|
// are written; every other field is carried forward from whatever is in
|
||||||
|
// storage right now, which may already be a value another page wrote.
|
||||||
|
//
|
||||||
|
// `wallets` is merged structurally (mergeListByIdentity(), by wallet
|
||||||
|
// identity and then by address identity within each wallet), not as one
|
||||||
|
// whole field: backgroundRefresh() mutates wallets IN PLACE (addr.balance /
|
||||||
|
// ensName / tokenBalances, via refreshBalances()), so a whole-field diff
|
||||||
|
// would mark all of `wallets` "changed" the moment any balance moved and
|
||||||
|
// write back background's own copy — loaded before its multi-second network
|
||||||
|
// round trip — clobbering a wallet another page added, or resurrecting one
|
||||||
|
// another page deleted, in that window. Merging by identity lets
|
||||||
|
// background's leaf changes and another page's membership changes
|
||||||
|
// (add/delete a wallet or an address) apply independently instead of
|
||||||
|
// colliding as the same field.
|
||||||
|
//
|
||||||
|
// `allowedSites` and `deniedSites` get the same treatment (mergeSiteMap(),
|
||||||
|
// by address key and then by hostname within each address's list), for the
|
||||||
|
// identical reason: src/background/index.js pushes a newly
|
||||||
|
// approved/denied hostname onto them in place, and the Settings "revoke"
|
||||||
|
// button (src/popup/views/settings.js) filters one out in place, from a
|
||||||
|
// different page. A whole-field diff here doesn't just lose data, it is a
|
||||||
|
// security defect — a stale page's save can resurrect a just-revoked site
|
||||||
|
// permission, or silently wipe a permission just granted elsewhere.
|
||||||
|
//
|
||||||
|
// `networkEndpoints` gets the same treatment too (mergeNetworkEndpoints(),
|
||||||
|
// by network id), since onChainSwitch() writes into it in place; the value
|
||||||
|
// per key is a small leaf object with no membership of its own; see the
|
||||||
|
// comment at mergeEndpointEntry() for why the collision this closes is
|
||||||
|
// milder than the other two.
|
||||||
|
//
|
||||||
|
// Every other persisted field stays a whole-field diff:
|
||||||
|
// `trackedTokens`/`fraudContracts`/`viewStack` are arrays of scalars with no
|
||||||
|
// per-element identity to merge by; `tokenHolderCache` is a map shaped like
|
||||||
|
// the ones above, but nothing in src/ ever writes an entry into it — it is
|
||||||
|
// only ever reset wholesale to `{}` (onChainSwitch()) — so there is no
|
||||||
|
// in-place mutation for a whole-field diff to collide with; `viewData` is
|
||||||
|
// this page's own UI scratch space, not data another page has any reason to
|
||||||
|
// share membership of.
|
||||||
|
//
|
||||||
|
// This does not make two pages that both change the SAME leaf concurrently
|
||||||
|
// safe: last write wins on that one leaf, same as before. What it removes
|
||||||
|
// is the cross-field (and now cross-membership-vs-leaf) clobber — a page
|
||||||
|
// that only navigated, or only refreshed a balance, overwriting a wallet or
|
||||||
|
// address list it never touched the membership of.
|
||||||
|
//
|
||||||
|
// This page's own live `state` is deliberately NOT rehydrated from a field
|
||||||
|
// another page changed — only the record written to storage is merged.
|
||||||
|
// showView() fires saveState() on every navigation without awaiting it,
|
||||||
|
// which is what makes the queue above necessary in the first place, and a
|
||||||
|
// save that is slow to come back has no way to tell whether the field it
|
||||||
|
// is about to hand back is still the current answer or has since been
|
||||||
|
// overtaken by something this very page did in the meantime; writing it
|
||||||
|
// into `state` regardless reintroduced exactly the clobber this function
|
||||||
|
// exists to remove, just delayed and confined to one page instead of two
|
||||||
|
// (caught by tests/txStatus.test.js). A page's live picture of a field it
|
||||||
|
// does not own goes on being whatever its last loadState() saw, same as
|
||||||
|
// before this fix; only the persisted record is guaranteed current.
|
||||||
|
async function saveStateOnce() {
|
||||||
|
const current = snapshotPersisted();
|
||||||
|
const result = await storageGet("autistmask");
|
||||||
|
// Normalized, not raw: a field this page did not change still has to
|
||||||
|
// come from storage in its loaded (self-healed) shape. See
|
||||||
|
// normalizePersisted() above.
|
||||||
|
const fresh = normalizePersisted(result.autistmask);
|
||||||
|
|
||||||
|
const merged = { ...fresh };
|
||||||
|
for (const key of PERSISTED_FIELDS) {
|
||||||
|
if (key === "wallets") {
|
||||||
|
merged.wallets = mergeListByIdentity(
|
||||||
|
baseline ? baseline.wallets : [],
|
||||||
|
current.wallets,
|
||||||
|
fresh.wallets,
|
||||||
|
walletIdentity,
|
||||||
|
mergeWallet,
|
||||||
|
);
|
||||||
|
} else if (key === "allowedSites" || key === "deniedSites") {
|
||||||
|
merged[key] = mergeSiteMap(
|
||||||
|
baseline ? baseline[key] : {},
|
||||||
|
current[key],
|
||||||
|
fresh[key],
|
||||||
|
);
|
||||||
|
} else if (key === "networkEndpoints") {
|
||||||
|
merged.networkEndpoints = mergeNetworkEndpoints(
|
||||||
|
baseline ? baseline.networkEndpoints : {},
|
||||||
|
current.networkEndpoints,
|
||||||
|
fresh.networkEndpoints,
|
||||||
|
);
|
||||||
|
} else if (
|
||||||
|
baseline === null ||
|
||||||
|
!deepEqual(current[key], baseline[key])
|
||||||
|
) {
|
||||||
|
merged[key] = current[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merged.hasWallet = Boolean(merged.wallets && merged.wallets.length > 0);
|
||||||
|
|
||||||
|
await storageSet({ autistmask: merged });
|
||||||
|
|
||||||
|
// Derived from this page's own wallets, never adopted off the wire —
|
||||||
|
// see loadState(). Everything else this page did not change is left
|
||||||
|
// exactly as it stood; see the note above.
|
||||||
|
state.hasWallet = state.wallets.length > 0;
|
||||||
|
|
||||||
|
baseline = structuredClone(snapshotPersisted());
|
||||||
|
}
|
||||||
|
|
||||||
|
// showView() calls saveState() on every navigation without awaiting it, so
|
||||||
|
// two saves from the SAME page can be in flight at once — e.g. a screen
|
||||||
|
// shown, then immediately replaced before the first save's storageGet()
|
||||||
|
// round trip has come back. Left concurrent, the first save's turn would
|
||||||
|
// finish after the second's live-state mutation and then re-hydrate `state`
|
||||||
|
// from what IT read, stomping the second, later change back to a stale
|
||||||
|
// value — the same clobber this function exists to prevent, just between
|
||||||
|
// two saves on one page instead of two pages. Queuing makes every save's
|
||||||
|
// snapshot-diff-write-rehydrate run start to finish before the next one
|
||||||
|
// begins, so each one only ever sees the true live state at its turn.
|
||||||
|
let saveQueue = Promise.resolve();
|
||||||
|
|
||||||
|
function saveState() {
|
||||||
|
const turn = saveQueue.then(saveStateOnce);
|
||||||
|
// The queue must advance even when a save rejects, or every save after
|
||||||
|
// it queues behind a promise that never settles.
|
||||||
|
saveQueue = turn.catch(() => {});
|
||||||
|
return turn;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadState() {
|
async function loadState() {
|
||||||
const result = await storageGet("autistmask");
|
const result = await storageGet("autistmask");
|
||||||
if (result.autistmask) {
|
if (result.autistmask) {
|
||||||
const saved = result.autistmask;
|
Object.assign(state, normalizePersisted(result.autistmask));
|
||||||
state.wallets = saved.wallets || [];
|
|
||||||
// Derived, never read from storage: a profile persisted with the flag
|
|
||||||
// out of step with the wallet list would otherwise stay broken on
|
|
||||||
// every load. Nothing depends on the two disagreeing.
|
|
||||||
state.hasWallet = state.wallets.length > 0;
|
|
||||||
state.trackedTokens = saved.trackedTokens || [];
|
|
||||||
state.networkId = saved.networkId || DEFAULT_STATE.networkId;
|
|
||||||
state.rpcUrl = saved.rpcUrl || DEFAULT_STATE.rpcUrl;
|
|
||||||
state.blockscoutUrl =
|
|
||||||
saved.blockscoutUrl || DEFAULT_STATE.blockscoutUrl;
|
|
||||||
// An actual object is required, not merely a truthy non-array: the
|
|
||||||
// code below and onChainSwitch() index and ASSIGN INTO this value,
|
|
||||||
// and assigning a property to a string or a number is a silent no-op
|
|
||||||
// in sloppy mode. A stored primitive would therefore be re-persisted
|
|
||||||
// unchanged forever, and every switch would fall back to the network
|
|
||||||
// default — the endpoint loss this map exists to prevent, with no
|
|
||||||
// self-healing. The allowedSites/deniedSites guards below are only
|
|
||||||
// read from, which is why they can be looser.
|
|
||||||
state.networkEndpoints =
|
|
||||||
typeof saved.networkEndpoints === "object" &&
|
|
||||||
saved.networkEndpoints !== null &&
|
|
||||||
!Array.isArray(saved.networkEndpoints)
|
|
||||||
? saved.networkEndpoints
|
|
||||||
: {};
|
|
||||||
// A profile written before this map existed carries exactly one pair
|
|
||||||
// of endpoints, belonging to whatever network it was last on. Adopt
|
|
||||||
// it as that network's remembered pair, so a custom endpoint set on
|
|
||||||
// the old build is not lost by the first switch away and back.
|
|
||||||
if (!state.networkEndpoints[state.networkId]) {
|
|
||||||
state.networkEndpoints[state.networkId] = {
|
|
||||||
rpcUrl: state.rpcUrl,
|
|
||||||
blockscoutUrl: state.blockscoutUrl,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
state.lastBalanceRefresh = saved.lastBalanceRefresh || 0;
|
|
||||||
state.activeAddress = saved.activeAddress || null;
|
|
||||||
state.allowedSites =
|
|
||||||
saved.allowedSites && !Array.isArray(saved.allowedSites)
|
|
||||||
? saved.allowedSites
|
|
||||||
: {};
|
|
||||||
state.deniedSites =
|
|
||||||
saved.deniedSites && !Array.isArray(saved.deniedSites)
|
|
||||||
? saved.deniedSites
|
|
||||||
: {};
|
|
||||||
state.rememberSiteChoice =
|
|
||||||
saved.rememberSiteChoice !== undefined
|
|
||||||
? saved.rememberSiteChoice
|
|
||||||
: true;
|
|
||||||
state.showZeroBalanceTokens =
|
|
||||||
saved.showZeroBalanceTokens !== undefined
|
|
||||||
? saved.showZeroBalanceTokens
|
|
||||||
: 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 =
|
|
||||||
saved.hideLowHolderTokens !== undefined
|
|
||||||
? saved.hideLowHolderTokens
|
|
||||||
: true;
|
|
||||||
state.hideFraudContracts =
|
|
||||||
saved.hideFraudContracts !== undefined
|
|
||||||
? saved.hideFraudContracts
|
|
||||||
: true;
|
|
||||||
state.hideDustTransactions =
|
|
||||||
saved.hideDustTransactions !== undefined
|
|
||||||
? saved.hideDustTransactions
|
|
||||||
: true;
|
|
||||||
state.dustThresholdGwei =
|
|
||||||
saved.dustThresholdGwei !== undefined
|
|
||||||
? saved.dustThresholdGwei
|
|
||||||
: 100000;
|
|
||||||
state.utcTimestamps =
|
|
||||||
saved.utcTimestamps !== undefined ? saved.utcTimestamps : false;
|
|
||||||
state.fraudContracts = saved.fraudContracts || [];
|
|
||||||
state.tokenHolderCache = saved.tokenHolderCache || {};
|
|
||||||
state.theme = saved.theme || "system";
|
|
||||||
state.debugMode =
|
|
||||||
saved.debugMode !== undefined ? saved.debugMode : false;
|
|
||||||
state.currentView = saved.currentView || null;
|
|
||||||
state.selectedWallet =
|
|
||||||
saved.selectedWallet !== undefined ? saved.selectedWallet : null;
|
|
||||||
state.selectedAddress =
|
|
||||||
saved.selectedAddress !== undefined ? saved.selectedAddress : null;
|
|
||||||
state.selectedToken = saved.selectedToken || null;
|
|
||||||
state.viewData = saved.viewData || {};
|
|
||||||
state.viewStack = restorableStack(saved.viewStack, state.currentView);
|
|
||||||
}
|
}
|
||||||
|
// The point of comparison every saveState() on this page diffs against,
|
||||||
|
// whether storage had a profile or was empty. See PERSISTED_FIELDS above
|
||||||
|
// saveState() for why a reference here would be wrong.
|
||||||
|
baseline = structuredClone(snapshotPersisted());
|
||||||
}
|
}
|
||||||
|
|
||||||
function currentAddress() {
|
function currentAddress() {
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ const { log, debugFetch } = require("./log");
|
|||||||
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||||
const { parseHoldersCount, isLowHolderCount } = require("./holders");
|
const { parseHoldersCount, isLowHolderCount } = require("./holders");
|
||||||
const { isSpoofedSymbol } = require("./symbolSpoof");
|
const { isSpoofedSymbol } = require("./symbolSpoof");
|
||||||
|
// The plain 4-decimal rule. The history and balance lists deliberately keep
|
||||||
|
// truncation without the approval screens' nonzero floor: the transaction
|
||||||
|
// detail view is the authoritative record and already shows exact precision.
|
||||||
|
const { truncateAmount: formatTxValue } = require("./amountDisplay");
|
||||||
|
|
||||||
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
// Ethereum addresses are case-insensitive: EIP-55 mixed case is a checksum
|
||||||
// over the address, not part of its identity. Every address comparison in
|
// over the address, not part of its identity. Every address comparison in
|
||||||
@@ -20,13 +24,6 @@ function normalizeAddress(addr) {
|
|||||||
return (addr || "").toLowerCase();
|
return (addr || "").toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatTxValue(val) {
|
|
||||||
const parts = val.split(".");
|
|
||||||
if (parts.length === 1) return val + ".0000";
|
|
||||||
const dec = (parts[1] + "0000").slice(0, 4);
|
|
||||||
return parts[0] + "." + dec;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseTx(tx, addrLower) {
|
function parseTx(tx, addrLower) {
|
||||||
const from = tx.from?.hash || "";
|
const from = tx.from?.hash || "";
|
||||||
const to = tx.to?.hash || "";
|
const to = tx.to?.hash || "";
|
||||||
|
|||||||
@@ -3,6 +3,11 @@
|
|||||||
|
|
||||||
const { Interface, AbiCoder, getBytes, formatUnits } = require("ethers");
|
const { Interface, AbiCoder, getBytes, formatUnits } = require("ethers");
|
||||||
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
const { TOKEN_BY_ADDRESS } = require("./tokenList");
|
||||||
|
const { truncateAmountNeverZero } = require("./amountDisplay");
|
||||||
|
const {
|
||||||
|
resolveTokenDecimals,
|
||||||
|
unknownDecimalsAmount,
|
||||||
|
} = require("./approvalAmount");
|
||||||
|
|
||||||
const coder = AbiCoder.defaultAbiCoder();
|
const coder = AbiCoder.defaultAbiCoder();
|
||||||
|
|
||||||
@@ -34,20 +39,46 @@ const COMMAND_NAMES = {
|
|||||||
0x21: "Execute Sub-Plan",
|
0x21: "Execute Sub-Plan",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// The swap's Amount and Min. received lines land on the same approval screen,
|
||||||
|
// and Amount is carried to the wait/success/error screens as the ERC-20 line
|
||||||
|
// is, so they take the same nonzero floor: a swap of an amount below 0.0001 is
|
||||||
|
// not "0.0000", and a slippage floor of one base unit does not read as "you may
|
||||||
|
// receive nothing".
|
||||||
function formatAmount(raw, decimals) {
|
function formatAmount(raw, decimals) {
|
||||||
const parts = formatUnits(raw, decimals).split(".");
|
return truncateAmountNeverZero(formatUnits(raw, decimals));
|
||||||
if (parts.length === 1) return parts[0] + ".0000";
|
|
||||||
const dec = (parts[1] + "0000").slice(0, 4);
|
|
||||||
return parts[0] + "." + dec;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function tokenInfo(address) {
|
// `decimals` is null when nothing knows this token's scale. It is not
|
||||||
|
// defaulted to 18: the swap lines land on the same approval screen as the
|
||||||
|
// ERC-20 line, and a scale guessed there is what showed a 1,000 USDT swap as
|
||||||
|
// 0.000000000001. `sources` is { trackedTokens, wallets }, shaped as they are
|
||||||
|
// on `state`; resolveTokenDecimals() reads the bundled list, then those.
|
||||||
|
function tokenInfo(address, sources) {
|
||||||
if (!address || address === "0x0000000000000000000000000000000000000000") {
|
if (!address || address === "0x0000000000000000000000000000000000000000") {
|
||||||
return { symbol: "ETH", decimals: 18, address: null };
|
return { symbol: "ETH", decimals: 18, address: null };
|
||||||
}
|
}
|
||||||
const t = TOKEN_BY_ADDRESS.get(address.toLowerCase());
|
const t = TOKEN_BY_ADDRESS.get(address.toLowerCase());
|
||||||
if (t) return { symbol: t.symbol, decimals: t.decimals, address };
|
return {
|
||||||
return { symbol: null, decimals: 18, address };
|
symbol: t ? t.symbol : null,
|
||||||
|
decimals: resolveTokenDecimals(address, sources),
|
||||||
|
address,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// A swap amount line. With a scale it is the token quantity; with none it is
|
||||||
|
// the base-unit integer with the unknown scale stated, the same refusal the
|
||||||
|
// ERC-20 amount line makes, so the screen has one way of saying it. `display`
|
||||||
|
// is the line on the screen, `raw` is what the status screens carry.
|
||||||
|
function amountText(raw, info) {
|
||||||
|
if (info.decimals === null) {
|
||||||
|
const unknown = unknownDecimalsAmount(raw);
|
||||||
|
return { raw: unknown, display: unknown };
|
||||||
|
}
|
||||||
|
const formatted = formatAmount(raw, info.decimals);
|
||||||
|
return {
|
||||||
|
raw: formatted,
|
||||||
|
display: formatted + (info.symbol ? " " + info.symbol : ""),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode PERMIT2_PERMIT (command 0x0a) input bytes.
|
// Decode PERMIT2_PERMIT (command 0x0a) input bytes.
|
||||||
@@ -320,7 +351,7 @@ function decodeV4Swap(input) {
|
|||||||
// Try to decode a Universal Router execute() call.
|
// Try to decode a Universal Router execute() call.
|
||||||
// Returns { name, description, details } matching the format used by
|
// Returns { name, description, details } matching the format used by
|
||||||
// the approval UI, or null if the calldata is not a recognised execute().
|
// the approval UI, or null if the calldata is not a recognised execute().
|
||||||
function decode(data, toAddress) {
|
function decode(data, toAddress, sources) {
|
||||||
try {
|
try {
|
||||||
const parsed = ROUTER_IFACE.parseTransaction({ data });
|
const parsed = ROUTER_IFACE.parseTransaction({ data });
|
||||||
if (!parsed) return null;
|
if (!parsed) return null;
|
||||||
@@ -413,10 +444,10 @@ function decode(data, toAddress) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Resolve token info
|
// Resolve token info
|
||||||
const inInfo = tokenInfo(inputToken);
|
const inInfo = tokenInfo(inputToken, sources);
|
||||||
const outInfo = hasUnwrapWeth
|
const outInfo = hasUnwrapWeth
|
||||||
? { symbol: "ETH", decimals: 18, address: null }
|
? { symbol: "ETH", decimals: 18, address: null }
|
||||||
: tokenInfo(outputToken);
|
: tokenInfo(outputToken, sources);
|
||||||
|
|
||||||
const inSymbol = inInfo.symbol;
|
const inSymbol = inInfo.symbol;
|
||||||
const outSymbol = outInfo.symbol;
|
const outSymbol = outInfo.symbol;
|
||||||
@@ -453,16 +484,15 @@ function decode(data, toAddress) {
|
|||||||
"0xffffffffffffffffffffffffffffffffffffffff",
|
"0xffffffffffffffffffffffffffffffffffffffff",
|
||||||
);
|
);
|
||||||
const isUnlimited = inputAmount >= maxUint160;
|
const isUnlimited = inputAmount >= maxUint160;
|
||||||
const amountRaw = isUnlimited
|
// An unbounded permit needs no scale to describe, so it is still
|
||||||
? "Unlimited"
|
// named rather than refused.
|
||||||
: formatAmount(inputAmount, inInfo.decimals);
|
const amount = isUnlimited
|
||||||
const amountStr = isUnlimited
|
? { raw: "Unlimited", display: "Unlimited" }
|
||||||
? "Unlimited"
|
: amountText(inputAmount, inInfo);
|
||||||
: amountRaw + (inSymbol ? " " + inSymbol : "");
|
|
||||||
details.push({
|
details.push({
|
||||||
label: "Amount",
|
label: "Amount",
|
||||||
value: amountStr,
|
value: amount.display,
|
||||||
rawValue: amountRaw,
|
rawValue: amount.raw,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -483,10 +513,10 @@ function decode(data, toAddress) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (minOutput !== null && minOutput !== undefined) {
|
if (minOutput !== null && minOutput !== undefined) {
|
||||||
const minStr =
|
details.push({
|
||||||
formatAmount(minOutput, outInfo.decimals) +
|
label: "Min. received",
|
||||||
(outSymbol ? " " + outSymbol : "");
|
value: amountText(minOutput, outInfo).display,
|
||||||
details.push({ label: "Min. received", value: minStr });
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
details.push({ label: "Steps", value: commandNames.join(" \u2192 ") });
|
details.push({ label: "Steps", value: commandNames.join(" \u2192 ") });
|
||||||
|
|||||||
190
tests/approvalDisplayFloor.test.js
Normal file
190
tests/approvalDisplayFloor.test.js
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
// The floor of the approval screen's amount line.
|
||||||
|
//
|
||||||
|
// Amounts are truncated to four decimal places for scannability (README.md,
|
||||||
|
// Display Consistency). With the token's true scale resolved, that truncation
|
||||||
|
// can still take a real amount below the floor and print it as `0.0000`: one
|
||||||
|
// base unit of an 18-decimal token, or a few hundred of an 8-decimal one. On
|
||||||
|
// the one screen whose job is to state what is being authorized, a nonzero
|
||||||
|
// transfer or allowance then reads as nothing.
|
||||||
|
//
|
||||||
|
// The invariant asserted here is narrow: a nonzero amount never renders as
|
||||||
|
// zero. The four-decimal rule itself is unchanged, and the string the
|
||||||
|
// confirmation screens carry as `txInfo.amount` is the same one, so it is
|
||||||
|
// asserted on `rawValue` alongside the displayed line.
|
||||||
|
//
|
||||||
|
// Both amount paths of that screen are covered: the ERC-20 line decoded by
|
||||||
|
// `src/popup/views/approval.js`, and the swap's `Amount` and `Min. received`
|
||||||
|
// lines decoded by `src/shared/uniswap.js`.
|
||||||
|
|
||||||
|
globalThis.chrome = {
|
||||||
|
storage: { local: { get: async () => ({}), set: async () => {} } },
|
||||||
|
};
|
||||||
|
|
||||||
|
const { AbiCoder, Interface } = require("ethers");
|
||||||
|
const { ERC20_ABI } = require("../src/shared/constants");
|
||||||
|
const { state } = require("../src/shared/state");
|
||||||
|
const { decodeCalldata } = require("../src/popup/views/approval");
|
||||||
|
const uniswap = require("../src/shared/uniswap");
|
||||||
|
const {
|
||||||
|
truncateAmount,
|
||||||
|
truncateAmountNeverZero,
|
||||||
|
} = require("../src/shared/amountDisplay");
|
||||||
|
|
||||||
|
const iface = new Interface(ERC20_ABI);
|
||||||
|
|
||||||
|
// Bundled tokens, so the scale and the symbol both come from the list.
|
||||||
|
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // 6 decimals
|
||||||
|
const WBT = "0x925206b8a707096Ed26ae47C84747fE0bb734F59"; // 8 decimals
|
||||||
|
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F"; // 18 decimals
|
||||||
|
// Outside the list, so the scale comes from what the user tracks and the line
|
||||||
|
// carries no symbol.
|
||||||
|
const NOVEL = "0xE2E0000000000000000000000000000000000E2e";
|
||||||
|
|
||||||
|
const RECIPIENT = "0xC0FfEE0000000000000000000000000000c0fFEe";
|
||||||
|
const SPENDER = "0x1111111111111111111111111111111111111111";
|
||||||
|
|
||||||
|
// The Uniswap swap lines land on this same approval screen.
|
||||||
|
const ROUTER = "0x66a9893cc07d91d95644aedd05d03f95e1dba8af";
|
||||||
|
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7"; // 6 decimals
|
||||||
|
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"; // 18 decimals
|
||||||
|
|
||||||
|
const coder = AbiCoder.defaultAbiCoder();
|
||||||
|
const routerIface = new Interface([
|
||||||
|
"function execute(bytes commands, bytes[] inputs, uint256 deadline)",
|
||||||
|
]);
|
||||||
|
|
||||||
|
// A V2_SWAP_EXACT_IN (command 0x08) execute() call: `amountIn` of USDT for at
|
||||||
|
// least `amountOutMin` of WETH.
|
||||||
|
function swapData(amountIn, amountOutMin) {
|
||||||
|
const input = coder.encode(
|
||||||
|
["address", "uint256", "uint256", "address[]", "bool"],
|
||||||
|
[RECIPIENT, amountIn, amountOutMin, [USDT, WETH], true],
|
||||||
|
);
|
||||||
|
return routerIface.encodeFunctionData("execute", [
|
||||||
|
"0x08",
|
||||||
|
[input],
|
||||||
|
9999999999n,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function swapDetail(amountIn, amountOutMin, label) {
|
||||||
|
const decoded = uniswap.decode(swapData(amountIn, amountOutMin), ROUTER);
|
||||||
|
return decoded.details.find((d) => d.label === label);
|
||||||
|
}
|
||||||
|
|
||||||
|
function transferData(amount) {
|
||||||
|
return iface.encodeFunctionData("transfer", [RECIPIENT, amount]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function approveData(amount) {
|
||||||
|
return iface.encodeFunctionData("approve", [SPENDER, amount]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Amount detail as the approval screen renders it: `value` is the line on
|
||||||
|
// the screen, `rawValue` is what is carried to the wait/success/error screens.
|
||||||
|
function amount(data, token) {
|
||||||
|
const decoded = decodeCalldata(data, token);
|
||||||
|
return decoded.details.find((d) => d.label === "Amount");
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
state.trackedTokens = [];
|
||||||
|
state.wallets = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a nonzero amount never renders as zero", () => {
|
||||||
|
test("500 base units of a 6-decimal token", () => {
|
||||||
|
const detail = amount(transferData(500n), USDC);
|
||||||
|
expect(detail.value).toBe("0.0005 USDC");
|
||||||
|
expect(detail.rawValue).toBe("0.0005");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("1 base unit of an 18-decimal token", () => {
|
||||||
|
const detail = amount(transferData(1n), DAI);
|
||||||
|
expect(detail.value).toBe("0.000000000000000001 DAI");
|
||||||
|
expect(detail.rawValue).toBe("0.000000000000000001");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("500 base units of an 8-decimal token", () => {
|
||||||
|
expect(amount(transferData(500n), WBT).rawValue).toBe("0.000005");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an allowance below the floor is not rendered as zero either", () => {
|
||||||
|
expect(amount(approveData(1n), DAI).value).toBe(
|
||||||
|
"0.000000000000000001 DAI",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The floor holds at any scale, not only the three above: for every
|
||||||
|
// decimals a token can declare, one base unit has to show a digit.
|
||||||
|
test("one base unit shows a significant digit at every scale", () => {
|
||||||
|
for (let decimals = 0; decimals <= 30; decimals++) {
|
||||||
|
state.trackedTokens = [{ address: NOVEL, decimals }];
|
||||||
|
expect(amount(transferData(1n), NOVEL).rawValue).toMatch(/[1-9]/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The swap decoder formats its own amounts, so the same floor has to hold on
|
||||||
|
// the swap lines of the same screen. `Min. received` is the sharper of the
|
||||||
|
// two: the slippage floor rendered as `0.0000` states that the swap may return
|
||||||
|
// nothing.
|
||||||
|
describe("a swap's amounts never render as zero either", () => {
|
||||||
|
test("a swap input below the floor keeps a significant digit", () => {
|
||||||
|
// 50 base units of a 6-decimal token is 0.00005.
|
||||||
|
const detail = swapDetail(50n, 10n ** 15n, "Amount");
|
||||||
|
expect(detail.value).toBe("0.00005 USDT");
|
||||||
|
expect(detail.rawValue).toBe("0.00005");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a min-received below the floor keeps a significant digit", () => {
|
||||||
|
// 1 wei of an 18-decimal token.
|
||||||
|
expect(swapDetail(10n ** 6n, 1n, "Min. received").value).toBe(
|
||||||
|
"0.000000000000000001 WETH",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("swap amounts at or above the floor are still truncated", () => {
|
||||||
|
expect(swapDetail(1000000n, 10n ** 15n, "Amount").rawValue).toBe(
|
||||||
|
"1.0000",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
swapDetail(1000000n, 999999999999999999n, "Min. received").value,
|
||||||
|
).toBe("0.9999 WETH");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the four-decimal rule is otherwise unchanged", () => {
|
||||||
|
test("a whole amount keeps exactly four decimals", () => {
|
||||||
|
expect(amount(transferData(5000000000n), USDC).rawValue).toBe(
|
||||||
|
"5000.0000",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("precision beyond four decimals is still truncated", () => {
|
||||||
|
expect(amount(transferData(1234567890123456789n), DAI).rawValue).toBe(
|
||||||
|
"1.2345",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an amount at the floor is not extended", () => {
|
||||||
|
expect(amount(transferData(100000000000000n), DAI).rawValue).toBe(
|
||||||
|
"0.0001",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a genuine zero still renders as zero", () => {
|
||||||
|
expect(amount(transferData(0n), DAI).rawValue).toBe("0.0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
// The three truncators now share one module. The floor is a policy of the
|
||||||
|
// approval and confirmation screens only: the history and balance lists
|
||||||
|
// keep plain truncation, because the transaction detail view is the
|
||||||
|
// authoritative record and already shows exact precision.
|
||||||
|
test("the list rule stays unfloored", () => {
|
||||||
|
expect(truncateAmount("0.000000000000000001")).toBe("0.0000");
|
||||||
|
expect(truncateAmountNeverZero("0.000000000000000001")).toBe(
|
||||||
|
"0.000000000000000001",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -72,6 +72,11 @@ RUN script/bootstrap
|
|||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
RUN make build
|
# make package builds (and verifies) dist/ and then writes the release
|
||||||
|
# artifacts, so the image carries both: run.js installs the unpacked
|
||||||
|
# dist/firefox and reinstall.js installs the packaged .xpi, which is how the
|
||||||
|
# artifact that would actually be handed to someone gets exercised in a real
|
||||||
|
# Firefox rather than only being produced.
|
||||||
|
RUN make package
|
||||||
|
|
||||||
CMD ["node", "tests/e2e/firefox/run.js", "dist/firefox"]
|
CMD ["node", "tests/e2e/firefox/run.js", "dist/firefox"]
|
||||||
|
|||||||
@@ -103,7 +103,13 @@ class Driver {
|
|||||||
|
|
||||||
// ------------------------------------------------------------ setup
|
// ------------------------------------------------------------ setup
|
||||||
|
|
||||||
async newSession() {
|
// `profileDir` reuses an existing profile directory in place instead of
|
||||||
|
// letting geckodriver make a throwaway one. That is the only way to ask
|
||||||
|
// what survives a browser RESTART, which for a Firefox add-on that can
|
||||||
|
// only be installed temporarily is the question that decides whether the
|
||||||
|
// extension is usable at all: a temporary add-on is unloaded when Firefox
|
||||||
|
// exits, so every session begins by adding it again.
|
||||||
|
async newSession(profileDir) {
|
||||||
const prefs = {
|
const prefs = {
|
||||||
// See EXTENSION_UUID above. The pref is a string pref whose
|
// See EXTENSION_UUID above. The pref is a string pref whose
|
||||||
// value is itself JSON.
|
// value is itself JSON.
|
||||||
@@ -132,26 +138,27 @@ class Driver {
|
|||||||
"extensions.openPopupWithoutUserGesture.enabled": false,
|
"extensions.openPopupWithoutUserGesture.enabled": false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const args = [
|
||||||
|
"-headless",
|
||||||
|
// Mandatory on Firefox 153: without it, navigating to
|
||||||
|
// moz-extension:// and running chrome-context script both
|
||||||
|
// fail with "unsupported operation".
|
||||||
|
//
|
||||||
|
// It grants the driver FULL CHROME PRIVILEGES over this
|
||||||
|
// browser. Acceptable only because the browser is a
|
||||||
|
// throwaway in a CI container; never point a session with
|
||||||
|
// this flag at anything you care about.
|
||||||
|
"-remote-allow-system-access",
|
||||||
|
];
|
||||||
|
if (profileDir) args.push("-profile", profileDir);
|
||||||
|
|
||||||
const value = await this.send("POST", "/session", {
|
const value = await this.send("POST", "/session", {
|
||||||
capabilities: {
|
capabilities: {
|
||||||
alwaysMatch: {
|
alwaysMatch: {
|
||||||
browserName: "firefox",
|
browserName: "firefox",
|
||||||
"moz:firefoxOptions": {
|
"moz:firefoxOptions": {
|
||||||
binary: FIREFOX_BIN,
|
binary: FIREFOX_BIN,
|
||||||
args: [
|
args,
|
||||||
"-headless",
|
|
||||||
// Mandatory on Firefox 153: without it,
|
|
||||||
// navigating to moz-extension:// and running
|
|
||||||
// chrome-context script both fail with
|
|
||||||
// "unsupported operation".
|
|
||||||
//
|
|
||||||
// It grants the driver FULL CHROME PRIVILEGES
|
|
||||||
// over this browser. Acceptable only because
|
|
||||||
// the browser is a throwaway in a CI
|
|
||||||
// container; never point a session with this
|
|
||||||
// flag at anything you care about.
|
|
||||||
"-remote-allow-system-access",
|
|
||||||
],
|
|
||||||
prefs,
|
prefs,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -162,16 +169,30 @@ class Driver {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Installs the unpacked MV2 build straight from a directory.
|
// Installs the MV2 build, either from an unpacked directory or from an
|
||||||
// temporary:true bypasses signature checks, so no XPI and no signing
|
// XPI file. temporary:true bypasses signature checks — which is the only
|
||||||
// are involved, and the add-on dies with the profile.
|
// way an UNSIGNED xpi installs at all, and the reason README.md says
|
||||||
async installAddon(dir) {
|
// release Firefox will refuse the artifact this repo produces — and the
|
||||||
|
// add-on dies with the profile.
|
||||||
|
//
|
||||||
|
// Returns the add-on id Firefox assigned, which is
|
||||||
|
// browser_specific_settings.gecko.id from the manifest and is what
|
||||||
|
// uninstallAddon() takes.
|
||||||
|
async installAddon(pathToAddon) {
|
||||||
return this.session("POST", "/moz/addon/install", {
|
return this.session("POST", "/moz/addon/install", {
|
||||||
path: dir,
|
path: pathToAddon,
|
||||||
temporary: true,
|
temporary: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Removes an installed add-on, the way clicking Remove in about:addons
|
||||||
|
// does. tests/e2e/firefox/reinstall.js uses it to ask the one question
|
||||||
|
// that decides whether this extension can be used at all on Firefox: does
|
||||||
|
// the vault survive being removed and added again.
|
||||||
|
async uninstallAddon(id) {
|
||||||
|
return this.session("POST", "/moz/addon/uninstall", { id });
|
||||||
|
}
|
||||||
|
|
||||||
// Classic navigation on purpose. BiDi's browsingContext.navigate
|
// Classic navigation on purpose. BiDi's browsingContext.navigate
|
||||||
// refuses moz-extension:// URLs outright.
|
// refuses moz-extension:// URLs outright.
|
||||||
async navigate(url) {
|
async navigate(url) {
|
||||||
|
|||||||
438
tests/e2e/firefox/reinstall.js
Normal file
438
tests/e2e/firefox/reinstall.js
Normal file
@@ -0,0 +1,438 @@
|
|||||||
|
// Does the wallet survive being installed again on Firefox?
|
||||||
|
//
|
||||||
|
// This is the question behind
|
||||||
|
// https://git.eeqj.de/sneak/AutistMask/issues/310, and it is the one property
|
||||||
|
// that has to hold before real money goes into this extension. The only route
|
||||||
|
// that works on release Firefox is a TEMPORARY add-on, which is unloaded when
|
||||||
|
// the browser exits: daily use means adding it again from about:debugging on
|
||||||
|
// every browser start. If extension storage did not survive that, every start
|
||||||
|
// would present an empty wallet and the recovery phrase would be the only copy
|
||||||
|
// of the money.
|
||||||
|
//
|
||||||
|
// manifest/firefox.json declares a fixed browser_specific_settings.gecko.id,
|
||||||
|
// which is the right SHAPE for storage to survive — Firefox keys the storage
|
||||||
|
// area by add-on id — but shape is not observation, and nothing asserted it.
|
||||||
|
//
|
||||||
|
// Two different things are asked here, because they have different answers and
|
||||||
|
// conflating them would be the whole mistake:
|
||||||
|
//
|
||||||
|
// RESTART one profile, two browser runs, the add-on added temporarily
|
||||||
|
// in each. This is what a user does every day, and the vault
|
||||||
|
// has to survive it.
|
||||||
|
// REMOVAL an explicit uninstall, the way about:addons "Remove" works,
|
||||||
|
// inside one browser run. Firefox destroys an add-on's storage
|
||||||
|
// when it is uninstalled, and the observed result is recorded
|
||||||
|
// here rather than wished away — for a wallet it means Remove
|
||||||
|
// is irreversible except from the recovery phrase.
|
||||||
|
//
|
||||||
|
// The vault is not merely compared as bytes in the restart case. It is
|
||||||
|
// DECRYPTED with the original password through the real Show Recovery Phrase
|
||||||
|
// screen and the phrase is compared against the one wallet creation produced,
|
||||||
|
// because "the ciphertext is still in storage" and "the wallet still works"
|
||||||
|
// are different claims and only the second one is worth anything.
|
||||||
|
//
|
||||||
|
// Run through script/test-e2e-firefox, which builds the artifact and the
|
||||||
|
// pinned container. The one argument is what to install — an unpacked
|
||||||
|
// directory or an .xpi. With none, the packaged XPI in release/ is used, so
|
||||||
|
// this doubles as the check that the release artifact installs in a real
|
||||||
|
// Firefox.
|
||||||
|
//
|
||||||
|
// node tests/e2e/firefox/reinstall.js release/autistmask-firefox-0.1.0.xpi
|
||||||
|
//
|
||||||
|
// A separate program from run.js rather than another step in it: every step
|
||||||
|
// there shares one browser session with one installed add-on, and this needs
|
||||||
|
// two browsers and three installs.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const { EXTENSION_ID, EXTENSION_UUID, start } = require("./driver");
|
||||||
|
|
||||||
|
const REPO_ROOT = path.resolve(__dirname, "..", "..", "..");
|
||||||
|
const PASSWORD = "e2e-harness-password";
|
||||||
|
|
||||||
|
const STEP_TIMEOUT_MS = 120000;
|
||||||
|
|
||||||
|
const checks = [];
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
function check(name, cond, detail) {
|
||||||
|
checks.push(name);
|
||||||
|
if (cond) {
|
||||||
|
console.log("ok " + checks.length + " - " + name);
|
||||||
|
} else {
|
||||||
|
failed += 1;
|
||||||
|
console.log("not ok " + checks.length + " - " + name);
|
||||||
|
if (detail) console.log(" " + detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The moz-extension:// uuid Firefox currently serves this add-on from, read
|
||||||
|
// out of the pref that holds the mapping. Privileged scope, because that pref
|
||||||
|
// is not reachable from content.
|
||||||
|
//
|
||||||
|
// It has to be read after every install and never assumed. driver.js pins a
|
||||||
|
// uuid through extensions.webextensions.uuids at each session start, but an
|
||||||
|
// uninstall inside a running session drops that mapping and the next install
|
||||||
|
// mints a fresh one — and navigating to the stale origin does not fail, it
|
||||||
|
// HANGS until the session times out, which is how this was found.
|
||||||
|
async function extensionUuid(d) {
|
||||||
|
const raw = await d.executeChrome(
|
||||||
|
`return Services.prefs.getStringPref(
|
||||||
|
"extensions.webextensions.uuids", "{}");`,
|
||||||
|
);
|
||||||
|
let map;
|
||||||
|
try {
|
||||||
|
map = JSON.parse(raw);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(
|
||||||
|
"extensions.webextensions.uuids is not JSON (" +
|
||||||
|
e.message +
|
||||||
|
"): " +
|
||||||
|
raw,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return map[EXTENSION_ID] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openPopup(d) {
|
||||||
|
const uuid = await extensionUuid(d);
|
||||||
|
if (!uuid) {
|
||||||
|
throw new Error(
|
||||||
|
"no uuid for " +
|
||||||
|
EXTENSION_ID +
|
||||||
|
" in extensions.webextensions.uuids, so the popup has no " +
|
||||||
|
"origin to be served from",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await d.navigate("moz-extension://" + uuid + "/src/popup/index.html");
|
||||||
|
// Whichever screen it lands on, wait for one of the two it can land on.
|
||||||
|
// Waiting for #view-main directly would time out rather than say what
|
||||||
|
// happened, and an empty storage partition is exactly the case where it
|
||||||
|
// lands on the other one.
|
||||||
|
await d.waitFor(
|
||||||
|
"the popup to finish restoring",
|
||||||
|
`const w = document.getElementById("view-welcome");
|
||||||
|
const m = document.getElementById("view-main");
|
||||||
|
if (!w || !m) return false;
|
||||||
|
const shown = (el) => {
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
return r.width > 0 && r.height > 0;
|
||||||
|
};
|
||||||
|
return shown(w) || shown(m);`,
|
||||||
|
[],
|
||||||
|
STEP_TIMEOUT_MS,
|
||||||
|
);
|
||||||
|
return uuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The persisted record, straight out of extension storage, read from the popup
|
||||||
|
// page — the one moz-extension:// document this program opens and therefore
|
||||||
|
// the only place the storage API is reachable from.
|
||||||
|
async function readVault(d) {
|
||||||
|
const outcome = await d.executeAsync(
|
||||||
|
`const done = arguments[arguments.length - 1];
|
||||||
|
const api = typeof browser !== "undefined" ? browser : chrome;
|
||||||
|
Promise.resolve(api.storage.local.get("autistmask"))
|
||||||
|
.then((r) => {
|
||||||
|
const s = r.autistmask;
|
||||||
|
if (!s) return done({ present: false });
|
||||||
|
const w = (s.wallets || [])[0];
|
||||||
|
if (!w) return done({ present: false });
|
||||||
|
done({
|
||||||
|
present: true,
|
||||||
|
wallets: s.wallets.length,
|
||||||
|
name: w.name,
|
||||||
|
xpub: w.xpub,
|
||||||
|
address: (w.addresses || []).map((a) => a.address)[0],
|
||||||
|
vault: JSON.stringify(w.encryptedSecret),
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((e) => done({ error: String((e && e.message) || e) }));`,
|
||||||
|
);
|
||||||
|
if (outcome && outcome.error) {
|
||||||
|
throw new Error("could not read extension storage: " + outcome.error);
|
||||||
|
}
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createWallet(d) {
|
||||||
|
await d.click("#btn-welcome-add");
|
||||||
|
await d.waitVisible("#view-add-wallet");
|
||||||
|
await d.click("#btn-generate-phrase");
|
||||||
|
await d.waitFor(
|
||||||
|
"a generated recovery phrase of at least 12 words",
|
||||||
|
`const el = document.getElementById("wallet-mnemonic");
|
||||||
|
return !!el && el.value.trim().split(/\\s+/).length >= 12;`,
|
||||||
|
);
|
||||||
|
const phrase = (await d.value("#wallet-mnemonic")).trim();
|
||||||
|
await d.fill("#add-wallet-password", PASSWORD);
|
||||||
|
await d.fill("#add-wallet-password-confirm", PASSWORD);
|
||||||
|
await d.click("#btn-add-wallet-confirm");
|
||||||
|
// Argon2id under libsodium, for real.
|
||||||
|
await d.waitVisible("#view-main", STEP_TIMEOUT_MS);
|
||||||
|
return phrase;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The phrase the vault decrypts to, obtained the way a user would: Settings,
|
||||||
|
// Show Recovery Phrase, the original password.
|
||||||
|
async function revealPhrase(d) {
|
||||||
|
if (!(await d.isVisible("#view-settings"))) {
|
||||||
|
await d.click("#btn-settings");
|
||||||
|
}
|
||||||
|
await d.waitVisible("#view-settings");
|
||||||
|
await d.click("#settings-wallet-list .btn-show-phrase");
|
||||||
|
await d.waitVisible("#view-show-phrase");
|
||||||
|
await d.fill("#show-phrase-password", PASSWORD);
|
||||||
|
await d.click("#btn-show-phrase-reveal");
|
||||||
|
await d.waitVisible("#show-phrase-result", STEP_TIMEOUT_MS);
|
||||||
|
return (await d.text("#show-phrase-value")).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// What to install. An explicit argument wins; with none, the packaged XPI in
|
||||||
|
// release/ is used, and there is deliberately no fallback to dist/firefox: the
|
||||||
|
// point of running this against the artifact is that the artifact is what gets
|
||||||
|
// installed, and quietly testing something else instead would leave the XPI
|
||||||
|
// unexercised while the run stayed green.
|
||||||
|
function resolveArtifact() {
|
||||||
|
if (process.argv[2]) return path.resolve(REPO_ROOT, process.argv[2]);
|
||||||
|
|
||||||
|
const releaseDir = path.join(REPO_ROOT, "release");
|
||||||
|
const xpis = fs.existsSync(releaseDir)
|
||||||
|
? fs.readdirSync(releaseDir).filter((f) => f.endsWith(".xpi"))
|
||||||
|
: [];
|
||||||
|
if (xpis.length !== 1) {
|
||||||
|
throw new Error(
|
||||||
|
"expected exactly one .xpi in release/, found " +
|
||||||
|
xpis.length +
|
||||||
|
" (" +
|
||||||
|
xpis.join(", ") +
|
||||||
|
"). Run make package, or name the artifact as the argument.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return path.join(releaseDir, xpis[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
let artifact;
|
||||||
|
try {
|
||||||
|
artifact = resolveArtifact();
|
||||||
|
} catch (e) {
|
||||||
|
console.error("e2e-firefox-reinstall: " + e.message);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!fs.existsSync(artifact)) {
|
||||||
|
console.error(
|
||||||
|
"e2e-firefox-reinstall: nothing to install at " + artifact,
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log("# installing: " + artifact);
|
||||||
|
|
||||||
|
// One profile, reused by both browser runs below. geckodriver would
|
||||||
|
// otherwise make a throwaway one per session, and "survives a restart"
|
||||||
|
// cannot be asked of a profile that does not.
|
||||||
|
const profile = fs.mkdtempSync(
|
||||||
|
path.join(os.tmpdir(), "autistmask-reinstall-profile-"),
|
||||||
|
);
|
||||||
|
|
||||||
|
let phrase = null;
|
||||||
|
let before = null;
|
||||||
|
let first;
|
||||||
|
|
||||||
|
// --- run one: install, create a wallet, close the browser --------------
|
||||||
|
try {
|
||||||
|
first = await start();
|
||||||
|
await first.newSession(profile);
|
||||||
|
} catch (e) {
|
||||||
|
// A browser we cannot start is a failure of this program, never an
|
||||||
|
// absent one.
|
||||||
|
console.error("e2e-firefox-reinstall: cannot run: " + e.message);
|
||||||
|
if (first) await first.quit().catch(() => {});
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const firstId = await first.installAddon(artifact);
|
||||||
|
check(
|
||||||
|
"the artifact installs and reports the manifest's gecko id",
|
||||||
|
firstId === EXTENSION_ID,
|
||||||
|
"installed add-on id is " +
|
||||||
|
JSON.stringify(firstId) +
|
||||||
|
", expected " +
|
||||||
|
JSON.stringify(EXTENSION_ID) +
|
||||||
|
". Without a stable id Firefox has no key to hang the " +
|
||||||
|
"storage area on, and nothing below can hold.",
|
||||||
|
);
|
||||||
|
|
||||||
|
const firstUuid = await openPopup(first);
|
||||||
|
await first.waitVisible("#view-welcome", STEP_TIMEOUT_MS);
|
||||||
|
phrase = await createWallet(first);
|
||||||
|
before = await readVault(first);
|
||||||
|
check(
|
||||||
|
"a wallet created through the UI is in extension storage",
|
||||||
|
before.present && before.wallets === 1 && !!before.vault,
|
||||||
|
JSON.stringify(before),
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
"# run 1 moz-extension uuid: " +
|
||||||
|
firstUuid +
|
||||||
|
(firstUuid === EXTENSION_UUID ? " (the pinned one)" : ""),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
failed += 1;
|
||||||
|
console.log("# ERROR in run 1: " + (e && e.stack ? e.stack : e));
|
||||||
|
} finally {
|
||||||
|
await first.quit().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- run two: same profile, add-on added again -------------------------
|
||||||
|
//
|
||||||
|
// This is the restart. The temporary add-on died with the previous
|
||||||
|
// browser; the profile, and whatever Firefox kept in it, did not.
|
||||||
|
let second;
|
||||||
|
try {
|
||||||
|
second = await start();
|
||||||
|
await second.newSession(profile);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(
|
||||||
|
"e2e-firefox-reinstall: cannot restart the browser: " + e.message,
|
||||||
|
);
|
||||||
|
if (second) await second.quit().catch(() => {});
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const secondId = await second.installAddon(artifact);
|
||||||
|
check(
|
||||||
|
"the add-on installs again after a browser restart with the " +
|
||||||
|
"same id",
|
||||||
|
secondId === EXTENSION_ID,
|
||||||
|
"re-installed id is " + JSON.stringify(secondId),
|
||||||
|
);
|
||||||
|
|
||||||
|
const secondUuid = await openPopup(second);
|
||||||
|
// The origin the popup is served from is not the thing that carries
|
||||||
|
// the wallet, and the uuid is read live for exactly that reason. In
|
||||||
|
// this run it comes back as the pinned one, because driver.js writes
|
||||||
|
// extensions.webextensions.uuids into the profile at every session
|
||||||
|
// start; an uninstall inside a running session drops the mapping and
|
||||||
|
// the next install mints a fresh uuid instead. Either way the storage
|
||||||
|
// area is keyed on the add-on id, never on this.
|
||||||
|
console.log(
|
||||||
|
"# run 2 moz-extension uuid: " +
|
||||||
|
secondUuid +
|
||||||
|
(secondUuid === EXTENSION_UUID
|
||||||
|
? " (the pinned one, re-applied at session start)"
|
||||||
|
: " (freshly minted)"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const onWelcome = await second.isVisible("#view-welcome");
|
||||||
|
check(
|
||||||
|
"after a restart and re-add, the extension does not come up as " +
|
||||||
|
"a fresh install",
|
||||||
|
!onWelcome,
|
||||||
|
"the popup shows the welcome screen, which is what an empty " +
|
||||||
|
"storage partition looks like: the wallet is gone and only " +
|
||||||
|
"the recovery phrase would get it back.",
|
||||||
|
);
|
||||||
|
|
||||||
|
const after = await readVault(second);
|
||||||
|
check(
|
||||||
|
"the vault, xpub and first address survive the restart unchanged",
|
||||||
|
after.present &&
|
||||||
|
after.wallets === before.wallets &&
|
||||||
|
after.vault === before.vault &&
|
||||||
|
after.xpub === before.xpub &&
|
||||||
|
after.address === before.address,
|
||||||
|
"before: " +
|
||||||
|
JSON.stringify(before) +
|
||||||
|
" after: " +
|
||||||
|
JSON.stringify(after),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (after.present) {
|
||||||
|
const revealed = await revealPhrase(second);
|
||||||
|
check(
|
||||||
|
"the vault still decrypts with the original password to the " +
|
||||||
|
"original recovery phrase",
|
||||||
|
revealed === phrase,
|
||||||
|
"the recovery phrase read back after the restart is not the " +
|
||||||
|
"one the wallet was created with",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
check(
|
||||||
|
"the vault still decrypts with the original password to the " +
|
||||||
|
"original recovery phrase",
|
||||||
|
false,
|
||||||
|
"there was no vault left to decrypt",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- an explicit removal, in the same browser run ------------------
|
||||||
|
//
|
||||||
|
// Leave the popup FIRST. Removing the add-on destroys every document
|
||||||
|
// it serves, and the popup is this session's only window: uninstalling
|
||||||
|
// while it is on screen discards the browsing context, and every
|
||||||
|
// subsequent WebDriver command fails with "no such window" rather than
|
||||||
|
// with anything about the add-on. Observed, not anticipated.
|
||||||
|
await second.navigate("about:blank");
|
||||||
|
await second.uninstallAddon(EXTENSION_ID);
|
||||||
|
await second.installAddon(artifact);
|
||||||
|
await openPopup(second);
|
||||||
|
|
||||||
|
const afterRemoval = await readVault(second);
|
||||||
|
console.log(
|
||||||
|
"# after an explicit uninstall: " + JSON.stringify(afterRemoval),
|
||||||
|
);
|
||||||
|
// Recorded as observed behaviour, not as something this repo wants.
|
||||||
|
// Firefox destroys an add-on's storage when it is uninstalled, and
|
||||||
|
// that is correct of a browser — it is stated here, and in README.md,
|
||||||
|
// because for a WALLET it means about:addons "Remove" is irreversible
|
||||||
|
// except from the recovery phrase. If a Firefox ever stops doing it
|
||||||
|
// this fails and the claim gets rewritten from a new observation.
|
||||||
|
check(
|
||||||
|
"an explicit uninstall DESTROYS the vault (observed Firefox " +
|
||||||
|
"behaviour: Remove is irreversible, unlike a restart)",
|
||||||
|
afterRemoval.present === false,
|
||||||
|
"the vault survived an explicit uninstall: " +
|
||||||
|
JSON.stringify(afterRemoval),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
failed += 1;
|
||||||
|
console.log("# ERROR in run 2: " + (e && e.stack ? e.stack : e));
|
||||||
|
} finally {
|
||||||
|
await second.quit().catch(() => {});
|
||||||
|
fs.rmSync(profile, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("1.." + checks.length);
|
||||||
|
if (checks.length === 0) {
|
||||||
|
console.log("# FAILED: this program asserted nothing");
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
"# " +
|
||||||
|
(checks.length - failed) +
|
||||||
|
"/" +
|
||||||
|
checks.length +
|
||||||
|
" checks passed",
|
||||||
|
);
|
||||||
|
if (failed > 0) {
|
||||||
|
console.log("# FAILED");
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error("e2e-firefox-reinstall: " + (e && e.stack ? e.stack : e));
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
303
tests/e2e/storagePartition.js
Normal file
303
tests/e2e/storagePartition.js
Normal file
@@ -0,0 +1,303 @@
|
|||||||
|
// Where does chrome.storage.local live, and what moves it?
|
||||||
|
//
|
||||||
|
// The finding behind https://git.eeqj.de/sneak/AutistMask/issues/310: an
|
||||||
|
// unpacked Chrome extension with no `key` in its manifest gets an extension id
|
||||||
|
// derived from the ABSOLUTE PATH it was loaded from, and chrome.storage.local
|
||||||
|
// is partitioned by that id. README.md documents Load unpacked from
|
||||||
|
// dist/chrome/ as the install route, so moving the checkout, re-cloning it, or
|
||||||
|
// loading a second copy from anywhere else means a different id, a different
|
||||||
|
// storage partition, and a wallet that reads as empty — with no error, no
|
||||||
|
// prompt and nothing in the UI to say what happened.
|
||||||
|
//
|
||||||
|
// So this OBSERVES the behaviour rather than restating it. Two unpacked loads
|
||||||
|
// from two different directories, in one profile, with the shipped manifest
|
||||||
|
// and again with `key` stripped out, and it reports what each pair actually
|
||||||
|
// does. The assertions are on what was seen when this was written and are
|
||||||
|
// annotated as such; if Chrome's derivation ever changes, this says so instead
|
||||||
|
// of passing.
|
||||||
|
//
|
||||||
|
// Run through script/test-e2e, which builds the extension and the pinned
|
||||||
|
// container.
|
||||||
|
//
|
||||||
|
// node tests/e2e/storagePartition.js
|
||||||
|
//
|
||||||
|
// A separate program from run.js because every test there shares one browser
|
||||||
|
// and one extension load, and the whole subject here is what happens across
|
||||||
|
// two of each.
|
||||||
|
//
|
||||||
|
// The extension's own UI is deliberately not driven. What is under test is the
|
||||||
|
// storage partition, so a sentinel key the extension never reads or writes is
|
||||||
|
// written and read back directly: a wallet would prove the same thing more
|
||||||
|
// slowly, and would confuse an empty partition with a UI that failed to
|
||||||
|
// render.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const { chromium } = require("playwright-core");
|
||||||
|
|
||||||
|
const REPO_ROOT = path.resolve(__dirname, "..", "..");
|
||||||
|
const DIST_CHROME = path.join(REPO_ROOT, "dist", "chrome");
|
||||||
|
|
||||||
|
// Never touched by the extension: src/shared/state.js reads and writes the
|
||||||
|
// single key "autistmask" and nothing else.
|
||||||
|
const SENTINEL_KEY = "e2e-storage-partition-sentinel";
|
||||||
|
const SENTINEL_VALUE = "written-by-the-first-load";
|
||||||
|
|
||||||
|
const checks = [];
|
||||||
|
let failed = 0;
|
||||||
|
const scratch = [];
|
||||||
|
|
||||||
|
function check(name, cond, detail) {
|
||||||
|
checks.push(name);
|
||||||
|
if (cond) {
|
||||||
|
console.log("ok " + checks.length + " - " + name);
|
||||||
|
} else {
|
||||||
|
failed += 1;
|
||||||
|
console.log("not ok " + checks.length + " - " + name);
|
||||||
|
if (detail) console.log(" " + detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tmpdir(tag) {
|
||||||
|
const dir = fs.mkdtempSync(
|
||||||
|
path.join(os.tmpdir(), "autistmask-" + tag + "-"),
|
||||||
|
);
|
||||||
|
scratch.push(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy of the built extension at a fresh absolute path. `withKey: false`
|
||||||
|
// strips the manifest's `key`, which is the pre-fix state of this repo and the
|
||||||
|
// control the whole program is built around.
|
||||||
|
function extensionCopy(tag, withKey) {
|
||||||
|
const dir = path.join(tmpdir(tag), "chrome");
|
||||||
|
fs.cpSync(DIST_CHROME, dir, { recursive: true });
|
||||||
|
const manifestPath = path.join(dir, "manifest.json");
|
||||||
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
||||||
|
if (withKey) {
|
||||||
|
if (!manifest.key) {
|
||||||
|
throw new Error(
|
||||||
|
"dist/chrome/manifest.json has no `key`, so this program has " +
|
||||||
|
"nothing to observe. That field is what pins the " +
|
||||||
|
"extension id; see tests/extensionId.test.js.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
delete manifest.key;
|
||||||
|
}
|
||||||
|
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function launch(profileDir, extensionDirs) {
|
||||||
|
const ctx = await chromium.launchPersistentContext(profileDir, {
|
||||||
|
// See the note in harness.js: the default headless shell silently
|
||||||
|
// refuses to load extensions.
|
||||||
|
channel: "chromium",
|
||||||
|
headless: true,
|
||||||
|
args: [
|
||||||
|
"--disable-extensions-except=" + extensionDirs.join(","),
|
||||||
|
"--load-extension=" + extensionDirs.join(","),
|
||||||
|
"--no-sandbox",
|
||||||
|
// Nothing here should reach the network; this makes sure it
|
||||||
|
// cannot.
|
||||||
|
"--host-resolver-rules=MAP * ~NOTFOUND",
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every extension id Chrome ended up with in this context, from the service
|
||||||
|
// worker urls. MV3 registers one worker per loaded extension.
|
||||||
|
async function extensionIds(ctx, expected) {
|
||||||
|
const deadline = Date.now() + 30000;
|
||||||
|
for (;;) {
|
||||||
|
const ids = [
|
||||||
|
...new Set(ctx.serviceWorkers().map((w) => new URL(w.url()).host)),
|
||||||
|
].sort();
|
||||||
|
if (ids.length >= expected) return ids;
|
||||||
|
if (Date.now() > deadline) return ids;
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open one extension's popup and run `fn` in it. The popup page is used rather
|
||||||
|
// than the service worker because Chrome stops an idle MV3 worker, and a
|
||||||
|
// handle to a stopped worker cannot be evaluated in.
|
||||||
|
async function inExtension(ctx, id, fn, arg) {
|
||||||
|
const page = await ctx.newPage();
|
||||||
|
try {
|
||||||
|
await page.goto("chrome-extension://" + id + "/src/popup/index.html");
|
||||||
|
return await page.evaluate(fn, arg);
|
||||||
|
} finally {
|
||||||
|
await page.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const writeSentinel = ([key, value]) =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
chrome.storage.local.set({ [key]: value }, () => resolve(true));
|
||||||
|
});
|
||||||
|
|
||||||
|
const readSentinel = (key) =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
chrome.storage.local.get(key, (r) => resolve(r[key] ?? null));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load `firstDir` in a fresh profile, write the sentinel, close; load
|
||||||
|
// `secondDir` in the SAME profile, read it back. Returns both ids and what the
|
||||||
|
// second load saw.
|
||||||
|
async function acrossTwoPaths(tag, firstDir, secondDir) {
|
||||||
|
const profile = tmpdir(tag + "-profile");
|
||||||
|
|
||||||
|
const first = await launch(profile, [firstDir]);
|
||||||
|
let firstId;
|
||||||
|
try {
|
||||||
|
[firstId] = await extensionIds(first, 1);
|
||||||
|
if (!firstId) throw new Error("no extension loaded from " + firstDir);
|
||||||
|
await inExtension(first, firstId, writeSentinel, [
|
||||||
|
SENTINEL_KEY,
|
||||||
|
SENTINEL_VALUE,
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
await first.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const second = await launch(profile, [secondDir]);
|
||||||
|
let secondId;
|
||||||
|
let seen;
|
||||||
|
try {
|
||||||
|
[secondId] = await extensionIds(second, 1);
|
||||||
|
if (!secondId) throw new Error("no extension loaded from " + secondDir);
|
||||||
|
seen = await inExtension(second, secondId, readSentinel, SENTINEL_KEY);
|
||||||
|
} finally {
|
||||||
|
await second.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { firstId, secondId, seen };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
if (!fs.existsSync(path.join(DIST_CHROME, "manifest.json"))) {
|
||||||
|
console.error(
|
||||||
|
"storagePartition: no unpacked build at " +
|
||||||
|
DIST_CHROME +
|
||||||
|
" — run make build first",
|
||||||
|
);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// --- the shipped manifest, which carries `key` ----------------------
|
||||||
|
const keyedA = extensionCopy("keyed-a", true);
|
||||||
|
const keyedB = extensionCopy("keyed-b", true);
|
||||||
|
const keyed = await acrossTwoPaths("keyed", keyedA, keyedB);
|
||||||
|
console.log("# with `key`: " + keyedA + " -> " + keyed.firstId);
|
||||||
|
console.log("# with `key`: " + keyedB + " -> " + keyed.secondId);
|
||||||
|
console.log("# with `key`: sentinel read back: " + keyed.seen);
|
||||||
|
|
||||||
|
check(
|
||||||
|
"with `key`, two different paths produce the SAME extension id",
|
||||||
|
keyed.firstId === keyed.secondId,
|
||||||
|
keyed.firstId + " != " + keyed.secondId,
|
||||||
|
);
|
||||||
|
check(
|
||||||
|
"with `key`, the second path reads the first path's storage",
|
||||||
|
keyed.seen === SENTINEL_VALUE,
|
||||||
|
"the second load read " +
|
||||||
|
JSON.stringify(keyed.seen) +
|
||||||
|
" instead of the value the first load wrote. The storage " +
|
||||||
|
"partition did not follow the extension across the move, " +
|
||||||
|
"which is the wallet silently reading as empty.",
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- the same build with `key` removed: the control -----------------
|
||||||
|
const barePath = extensionCopy("bare-a", false);
|
||||||
|
const bareB = extensionCopy("bare-b", false);
|
||||||
|
const bare = await acrossTwoPaths("bare", barePath, bareB);
|
||||||
|
console.log("# without `key`: " + barePath + " -> " + bare.firstId);
|
||||||
|
console.log("# without `key`: " + bareB + " -> " + bare.secondId);
|
||||||
|
console.log("# without `key`: sentinel read back: " + bare.seen);
|
||||||
|
|
||||||
|
// Observed, not assumed. If Chrome ever stops deriving the id from
|
||||||
|
// the load path these two fail, and the right response is to record
|
||||||
|
// what it does now — not to delete them.
|
||||||
|
check(
|
||||||
|
"without `key`, two different paths produce DIFFERENT ids " +
|
||||||
|
"(observed Chrome behaviour, the defect this fixes)",
|
||||||
|
bare.firstId !== bare.secondId,
|
||||||
|
"both loads got " +
|
||||||
|
bare.firstId +
|
||||||
|
", so the id no longer follows the load path on this Chrome",
|
||||||
|
);
|
||||||
|
check(
|
||||||
|
"without `key`, the second path sees an EMPTY partition " +
|
||||||
|
"(observed Chrome behaviour, the defect this fixes)",
|
||||||
|
bare.seen === null,
|
||||||
|
"the second load read " +
|
||||||
|
JSON.stringify(bare.seen) +
|
||||||
|
" from a different id's partition",
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- both copies loaded at once, in one profile ---------------------
|
||||||
|
// The literal shape of the question, kept because "two unpacked loads
|
||||||
|
// in one profile" is what a user does when they forget to remove the
|
||||||
|
// old one. With `key`, both copies claim the same id.
|
||||||
|
const profile = tmpdir("simultaneous-profile");
|
||||||
|
const ctx = await launch(profile, [keyedA, keyedB]);
|
||||||
|
let ids = [];
|
||||||
|
try {
|
||||||
|
ids = await extensionIds(ctx, 2);
|
||||||
|
} finally {
|
||||||
|
await ctx.close();
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
"# both keyed copies loaded at once: " +
|
||||||
|
ids.length +
|
||||||
|
" extension id(s): " +
|
||||||
|
ids.join(", "),
|
||||||
|
);
|
||||||
|
check(
|
||||||
|
"loading both keyed copies at once yields one id, not two " +
|
||||||
|
"(observed: Chrome does not load a second copy of an id it " +
|
||||||
|
"already has)",
|
||||||
|
ids.length === 1 && ids[0] === keyed.firstId,
|
||||||
|
"saw " + JSON.stringify(ids) + ", expected exactly one id",
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
failed += 1;
|
||||||
|
console.log("# ERROR: " + (e && e.stack ? e.stack : e));
|
||||||
|
} finally {
|
||||||
|
for (const dir of scratch) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("1.." + checks.length);
|
||||||
|
if (checks.length === 0) {
|
||||||
|
console.log("# FAILED: this program asserted nothing");
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
"# " +
|
||||||
|
(checks.length - failed) +
|
||||||
|
"/" +
|
||||||
|
checks.length +
|
||||||
|
" checks passed",
|
||||||
|
);
|
||||||
|
if (failed > 0) {
|
||||||
|
console.log("# FAILED");
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error("storagePartition: " + (e && e.stack ? e.stack : e));
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
119
tests/extensionId.test.js
Normal file
119
tests/extensionId.test.js
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
// The extension identity on both browsers, pinned.
|
||||||
|
//
|
||||||
|
// This is the anti-regression check for
|
||||||
|
// https://git.eeqj.de/sneak/AutistMask/issues/310. An unpacked Chrome
|
||||||
|
// extension with no `key` in its manifest gets an id derived from the
|
||||||
|
// ABSOLUTE PATH it was loaded from, and chrome.storage.local is partitioned by
|
||||||
|
// that id. Move the checkout, re-clone it, or load it from a second directory,
|
||||||
|
// and the wallet is silently gone: the extension comes up on a fresh, empty
|
||||||
|
// storage partition with no error anywhere. `key` pins the id to the public
|
||||||
|
// key instead of to the path, which is what makes the storage survive.
|
||||||
|
//
|
||||||
|
// So the id is asserted as a literal. A test that merely recomputed the id
|
||||||
|
// from whatever `key` happened to be in the manifest would pass after someone
|
||||||
|
// replaced the key — and replacing the key is exactly the change that orphans
|
||||||
|
// every existing wallet. The value below is the promise; changing it is a
|
||||||
|
// migration, not an edit.
|
||||||
|
//
|
||||||
|
// Firefox needs no key: browser_specific_settings.gecko.id declares the id
|
||||||
|
// directly, and it is pinned here for the same reason. The Firefox e2e suite
|
||||||
|
// depends on it too (tests/e2e/firefox/driver.js maps it to a fixed uuid), and
|
||||||
|
// tests/e2e/firefox/reinstall.js is the empirical half — it removes the add-on
|
||||||
|
// and installs it again and reads the vault back out.
|
||||||
|
|
||||||
|
const crypto = require("crypto");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const MANIFEST_DIR = path.join(__dirname, "..", "manifest");
|
||||||
|
|
||||||
|
// The public half of an RSA keypair, DER-encoded SubjectPublicKeyInfo, base64.
|
||||||
|
// The PRIVATE half is not in this repo and is not needed to build, load or
|
||||||
|
// test anything here: it is only ever used to sign a CRX, which this repo does
|
||||||
|
// not do.
|
||||||
|
const CHROME_KEY =
|
||||||
|
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzy/G9gT4Z3Ci0HCmthUPEiCjENg+" +
|
||||||
|
"5meZpjdogyT7SiMfxENtHdrpDL6wGhAg1Dk0f1C67Ft8OYpMrMH3kiP2Wnt0UpHo45PY0YUU" +
|
||||||
|
"YzdJgbsp8u0kaykd5FFiY6FycIIFaTniMuh7wRKuNNdJWly+H3aG7qZ6nGu5PIMdb1GXUk35" +
|
||||||
|
"hY+yl7dz5dqFFYUCyxvWCT9XGBSYiI+XRBB/rVZjMWfWpaTmRPdOZ4+GO/Lx0OdMxKlPA/kL" +
|
||||||
|
"WoPot5vMlLn2FDPu6sASphiu7dKZnrINW+h/27jlHMJQS0jncB1EgqOHW0vbXrZnTveFX6UW" +
|
||||||
|
"+Qp86FfSkikhKtQgTW2A4mtWawIDAQAB";
|
||||||
|
|
||||||
|
// chrome.storage.local for this extension lives under this id, and nowhere
|
||||||
|
// else.
|
||||||
|
const CHROME_EXTENSION_ID = "gipbhkogfopeahplcjhipkgpcimdpkip";
|
||||||
|
|
||||||
|
const FIREFOX_EXTENSION_ID = "autistmask@sneak.berlin";
|
||||||
|
|
||||||
|
// Chrome's id derivation: sha256 of the DER public key, first 16 bytes, each
|
||||||
|
// hex digit mapped 0-f onto a-p. Written out here rather than taken on trust,
|
||||||
|
// because the whole claim of this file is that the committed key produces that
|
||||||
|
// id.
|
||||||
|
function chromeExtensionId(keyBase64) {
|
||||||
|
const der = Buffer.from(keyBase64, "base64");
|
||||||
|
const digest = crypto.createHash("sha256").update(der).digest("hex");
|
||||||
|
return [...digest.slice(0, 32)]
|
||||||
|
.map((c) => String.fromCharCode(97 + parseInt(c, 16)))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function readManifest(name) {
|
||||||
|
return JSON.parse(
|
||||||
|
fs.readFileSync(path.join(MANIFEST_DIR, name + ".json"), "utf8"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("chrome extension identity", () => {
|
||||||
|
test("the manifest carries the pinned key", () => {
|
||||||
|
expect(readManifest("chrome").key).toBe(CHROME_KEY);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the key is a well-formed RSA public key", () => {
|
||||||
|
const der = Buffer.from(CHROME_KEY, "base64");
|
||||||
|
// Round-trips: a truncated or re-wrapped base64 blob would still
|
||||||
|
// decode to bytes, and Chrome would then derive an id from garbage.
|
||||||
|
expect(der.toString("base64")).toBe(CHROME_KEY);
|
||||||
|
const key = crypto.createPublicKey({
|
||||||
|
key: der,
|
||||||
|
format: "der",
|
||||||
|
type: "spki",
|
||||||
|
});
|
||||||
|
expect(key.asymmetricKeyType).toBe("rsa");
|
||||||
|
expect(key.asymmetricKeyDetails.modulusLength).toBe(2048);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the key derives the pinned extension id", () => {
|
||||||
|
expect(chromeExtensionId(CHROME_KEY)).toBe(CHROME_EXTENSION_ID);
|
||||||
|
expect(CHROME_EXTENSION_ID).toMatch(/^[a-p]{32}$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The private half is a credential. It has never been in this repo and no
|
||||||
|
// target generates one into the working tree; this fails loudly if that
|
||||||
|
// ever changes, because a committed .pem is a key anyone can sign a CRX
|
||||||
|
// with under this extension's id.
|
||||||
|
test("no private key is committed anywhere in the tree", () => {
|
||||||
|
const tracked = require("child_process")
|
||||||
|
.execSync("git ls-files", {
|
||||||
|
cwd: path.join(__dirname, ".."),
|
||||||
|
encoding: "utf8",
|
||||||
|
})
|
||||||
|
.split("\n")
|
||||||
|
.filter(Boolean);
|
||||||
|
expect(tracked.filter((f) => /\.(pem|key|p12|pfx)$/i.test(f))).toEqual(
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("firefox extension identity", () => {
|
||||||
|
test("the manifest declares the pinned gecko id", () => {
|
||||||
|
const gecko = readManifest("firefox").browser_specific_settings.gecko;
|
||||||
|
expect(gecko.id).toBe(FIREFOX_EXTENSION_ID);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Firefox derives nothing from the path, so no key field belongs here; one
|
||||||
|
// would be ignored and would only suggest the id came from somewhere else.
|
||||||
|
test("the firefox manifest carries no chrome key field", () => {
|
||||||
|
expect(readManifest("firefox").key).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
190
tests/packaging.test.js
Normal file
190
tests/packaging.test.js
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
// The release archives: the zip container, and the self-containment rule.
|
||||||
|
//
|
||||||
|
// script/package produces one archive per browser and script/lib/package.js
|
||||||
|
// decides what goes in it. The trap that rule exists for is real and specific:
|
||||||
|
// build.js writes the compiled stylesheet to dist/styles.css at the dist/
|
||||||
|
// ROOT, outside both browser directories, and copies it into each of them as
|
||||||
|
// src/popup/styles.css. A `zip -r dist/chrome` is correct only because of that
|
||||||
|
// copy, and would silently start shipping a popup with no stylesheet the
|
||||||
|
// moment a reference pointed up and out of the directory.
|
||||||
|
//
|
||||||
|
// So the packager resolves every reference in the manifest and in every HTML
|
||||||
|
// document, and fails on any that leaves the extension root. These are the
|
||||||
|
// cases for that, plus the archive format itself — new code, and the thing the
|
||||||
|
// artifact is made of.
|
||||||
|
|
||||||
|
const {
|
||||||
|
checkSelfContained,
|
||||||
|
htmlReferences,
|
||||||
|
manifestReferences,
|
||||||
|
} = require("../script/lib/package");
|
||||||
|
const { readZip, writeZip } = require("../script/lib/zip");
|
||||||
|
|
||||||
|
function archiveOf(files) {
|
||||||
|
return {
|
||||||
|
members: Object.keys(files).sort(),
|
||||||
|
read: (name) => Buffer.from(files[name] ?? "", "utf8"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const MINIMAL_MANIFEST = {
|
||||||
|
manifest_version: 3,
|
||||||
|
name: "AutistMask",
|
||||||
|
version: "0.1.0",
|
||||||
|
action: { default_popup: "src/popup/index.html" },
|
||||||
|
background: { service_worker: "src/background/index.js" },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("archive self-containment", () => {
|
||||||
|
test("a complete tree passes", () => {
|
||||||
|
const { members, read } = archiveOf({
|
||||||
|
"manifest.json": JSON.stringify(MINIMAL_MANIFEST),
|
||||||
|
"src/popup/index.html":
|
||||||
|
'<link rel="stylesheet" href="styles.css" />' +
|
||||||
|
'<script src="index.js"></script>',
|
||||||
|
"src/popup/styles.css": "body{}",
|
||||||
|
"src/popup/index.js": "//",
|
||||||
|
"src/background/index.js": "//",
|
||||||
|
});
|
||||||
|
expect(() => checkSelfContained("chrome", members, read)).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a manifest naming a file that is not in the archive fails", () => {
|
||||||
|
const { members, read } = archiveOf({
|
||||||
|
"manifest.json": JSON.stringify(MINIMAL_MANIFEST),
|
||||||
|
"src/popup/index.html": "<html></html>",
|
||||||
|
"src/popup/index.js": "//",
|
||||||
|
});
|
||||||
|
expect(() => checkSelfContained("chrome", members, read)).toThrow(
|
||||||
|
/would not be self-contained.*src\/background\/index\.js/s,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The dist/styles.css case, exactly: a popup that reached up out of its
|
||||||
|
// own browser directory for the stylesheet the build leaves at the dist/
|
||||||
|
// root. Nothing would be missing from disk, and the zip would still be
|
||||||
|
// built — the archive would just have no stylesheet in it.
|
||||||
|
test("an HTML reference that escapes the extension root fails", () => {
|
||||||
|
const { members, read } = archiveOf({
|
||||||
|
"manifest.json": JSON.stringify(MINIMAL_MANIFEST),
|
||||||
|
"src/popup/index.html":
|
||||||
|
'<link rel="stylesheet" href="../../../styles.css" />',
|
||||||
|
"src/popup/index.js": "//",
|
||||||
|
"src/background/index.js": "//",
|
||||||
|
});
|
||||||
|
expect(() => checkSelfContained("chrome", members, read)).toThrow(
|
||||||
|
/resolves outside the extension root/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a manifest reference that escapes the extension root fails", () => {
|
||||||
|
const { members, read } = archiveOf({
|
||||||
|
"manifest.json": JSON.stringify({
|
||||||
|
...MINIMAL_MANIFEST,
|
||||||
|
background: { service_worker: "../shared/index.js" },
|
||||||
|
}),
|
||||||
|
"src/popup/index.html": "<html></html>",
|
||||||
|
});
|
||||||
|
expect(() => checkSelfContained("chrome", members, read)).toThrow(
|
||||||
|
/points outside the extension root/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an archive with no manifest.json at its root fails", () => {
|
||||||
|
const { members, read } = archiveOf({ "src/popup/index.js": "//" });
|
||||||
|
expect(() => checkSelfContained("chrome", members, read)).toThrow(
|
||||||
|
/no manifest\.json at its root/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("manifest strings that are not paths are not treated as files", () => {
|
||||||
|
const found = manifestReferences({
|
||||||
|
name: "AutistMask",
|
||||||
|
version: "0.1.0",
|
||||||
|
permissions: ["storage", "<all_urls>"],
|
||||||
|
content_security_policy: {
|
||||||
|
extension_pages: "default-src 'self'; script-src 'self'",
|
||||||
|
},
|
||||||
|
key: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzy",
|
||||||
|
});
|
||||||
|
expect([...found]).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("absolute, data: and anchor HTML references are not files", () => {
|
||||||
|
const refs = htmlReferences(
|
||||||
|
"src/popup/index.html",
|
||||||
|
'<a href="https://example.com/x.js">a</a>' +
|
||||||
|
'<img src="data:image/png;base64,AAAA" />' +
|
||||||
|
'<a href="#view-main">b</a>' +
|
||||||
|
'<script src="index.js"></script>',
|
||||||
|
);
|
||||||
|
expect([...refs]).toEqual(["src/popup/index.js"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the zip container", () => {
|
||||||
|
const files = [
|
||||||
|
{ name: "manifest.json", data: Buffer.from('{"a":1}') },
|
||||||
|
// Long enough that deflate wins, so both paths through compress() are
|
||||||
|
// exercised by one archive.
|
||||||
|
{ name: "src/popup/index.js", data: Buffer.from("x".repeat(5000)) },
|
||||||
|
{ name: "empty.txt", data: Buffer.alloc(0) },
|
||||||
|
];
|
||||||
|
|
||||||
|
test("round-trips every member byte for byte", () => {
|
||||||
|
const entries = readZip(writeZip(files));
|
||||||
|
expect(entries.map((e) => e.name)).toEqual([
|
||||||
|
"empty.txt",
|
||||||
|
"manifest.json",
|
||||||
|
"src/popup/index.js",
|
||||||
|
]);
|
||||||
|
for (const original of files) {
|
||||||
|
const found = entries.find((e) => e.name === original.name);
|
||||||
|
expect(found.data.equals(original.data)).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The sha256 in release/SHA256SUMS has to be a property of the input. Two
|
||||||
|
// builds of one commit that produce different archives cannot be compared
|
||||||
|
// to each other, which is most of what publishing a digest is for.
|
||||||
|
test("is byte-identical across runs and independent of input order", () => {
|
||||||
|
const a = writeZip(files);
|
||||||
|
const b = writeZip([...files].reverse());
|
||||||
|
expect(a.equals(b)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reading an archive back is how script/lib/package.js establishes that
|
||||||
|
// the artifact holds what dist/ holds, so a member whose bytes changed
|
||||||
|
// after it was written has to fail rather than be handed back.
|
||||||
|
test("a corrupted member fails its CRC on read", () => {
|
||||||
|
// One member, incompressible at this size, so it is stored verbatim
|
||||||
|
// and its bytes begin at a known offset: local header (30) + name.
|
||||||
|
const name = "a.js";
|
||||||
|
const archive = writeZip([{ name, data: Buffer.from("hello") }]);
|
||||||
|
expect(readZip(archive)[0].data.toString()).toBe("hello");
|
||||||
|
archive[30 + name.length] ^= 0xff;
|
||||||
|
expect(() => readZip(archive)).toThrow(/fails its recorded CRC32/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([["/abs.js"], ["../up.js"], ["a/../b.js"], ["a\\b.js"], [""]])(
|
||||||
|
"refuses the member name %p",
|
||||||
|
(name) => {
|
||||||
|
expect(() => writeZip([{ name, data: Buffer.from("x") }])).toThrow(
|
||||||
|
/member name/,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("refuses an archive with no members", () => {
|
||||||
|
expect(() => writeZip([])).toThrow(/no members/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("refuses duplicate members", () => {
|
||||||
|
expect(() =>
|
||||||
|
writeZip([
|
||||||
|
{ name: "a.js", data: Buffer.from("1") },
|
||||||
|
{ name: "a.js", data: Buffer.from("2") },
|
||||||
|
]),
|
||||||
|
).toThrow(/duplicate member/);
|
||||||
|
});
|
||||||
|
});
|
||||||
443
tests/stateMerge.test.js
Normal file
443
tests/stateMerge.test.js
Normal file
@@ -0,0 +1,443 @@
|
|||||||
|
// saveState() used to write the entire state blob every time
|
||||||
|
// (src/shared/state.js). Every extension page — the toolbar popup, a dApp
|
||||||
|
// approval window opened by the background, backgroundRefresh() in
|
||||||
|
// src/background/index.js — holds its own in-memory `state`, loaded once,
|
||||||
|
// and src/popup/views/helpers.js showView() saves on EVERY navigation. So
|
||||||
|
// any second page that saved after a first page had written something new
|
||||||
|
// overwrote it, with no attacker and no unusual input: a whole wallet, name,
|
||||||
|
// addresses and encrypted secret included, silently gone
|
||||||
|
// (https://git.eeqj.de/sneak/AutistMask/issues/304).
|
||||||
|
//
|
||||||
|
// Both cases below drive the real state.js module through two independent
|
||||||
|
// module registries sharing one storage backend, the way two real extension
|
||||||
|
// pages share one chrome.storage.local. The storage stub structured-clones
|
||||||
|
// on both get and set — a stub that hands back the object it was given
|
||||||
|
// aliases the caller's own mutation and would make this entire defect class
|
||||||
|
// invisible (see https://git.eeqj.de/sneak/AutistMask/issues/324).
|
||||||
|
|
||||||
|
function makeStorage() {
|
||||||
|
let store = {};
|
||||||
|
return {
|
||||||
|
get: async (keys) => {
|
||||||
|
const wanted =
|
||||||
|
keys === undefined || keys === null
|
||||||
|
? Object.keys(store)
|
||||||
|
: [].concat(keys);
|
||||||
|
const out = {};
|
||||||
|
for (const key of wanted) {
|
||||||
|
if (key in store) out[key] = structuredClone(store[key]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
set: async (items) => {
|
||||||
|
for (const [key, value] of Object.entries(items)) {
|
||||||
|
store[key] = structuredClone(value);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// One extension page: a fresh module registry over the shared storage.
|
||||||
|
// state.js resolves the storage API at require time, so the stub has to be
|
||||||
|
// installed before the module is loaded, and `state` is a module-level
|
||||||
|
// singleton, so each page needs its own registry to hold its own copy.
|
||||||
|
function loadPage(storage) {
|
||||||
|
jest.resetModules();
|
||||||
|
globalThis.chrome = { storage: { local: storage } };
|
||||||
|
return {
|
||||||
|
state: require("../src/shared/state"),
|
||||||
|
helpers: require("../src/popup/views/helpers"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function wallet(name, secret, address) {
|
||||||
|
return {
|
||||||
|
type: "hd",
|
||||||
|
name,
|
||||||
|
xpub: "xpub-" + name,
|
||||||
|
encryptedSecret: secret,
|
||||||
|
nextIndex: 1,
|
||||||
|
addresses: [{ address, balance: "0", tokenBalances: [] }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const W1 = wallet(
|
||||||
|
"Wallet 1",
|
||||||
|
"secret-one",
|
||||||
|
"0x66133E8ea0f5D1d612D2502a968757D1048c214a",
|
||||||
|
);
|
||||||
|
const W2 = wallet(
|
||||||
|
"Wallet 2",
|
||||||
|
"secret-two",
|
||||||
|
"0xdAC17F958D2ee523a2206206994597C13D831ec7",
|
||||||
|
);
|
||||||
|
|
||||||
|
// Minimal DOM: showView() toggles view elements, clears the flash line and
|
||||||
|
// creates/removes the debug banner. Nothing here is asserted; it only has to
|
||||||
|
// answer without throwing, the way the popup's own index.html would.
|
||||||
|
function makeElement(id) {
|
||||||
|
const classes = new Set();
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
textContent: "",
|
||||||
|
style: {},
|
||||||
|
classList: {
|
||||||
|
add: (...n) => n.forEach((c) => classes.add(c)),
|
||||||
|
remove: (...n) => n.forEach((c) => classes.delete(c)),
|
||||||
|
toggle: (c, force) => {
|
||||||
|
const on = force === undefined ? !classes.has(c) : force;
|
||||||
|
if (on) classes.add(c);
|
||||||
|
else classes.delete(c);
|
||||||
|
return on;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
remove: () => {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeDocument() {
|
||||||
|
const els = new Map();
|
||||||
|
return {
|
||||||
|
getElementById(id) {
|
||||||
|
if (id === "debug-banner") return null;
|
||||||
|
if (!els.has(id)) els.set(id, makeElement(id));
|
||||||
|
return els.get(id);
|
||||||
|
},
|
||||||
|
createElement: () => makeElement("created"),
|
||||||
|
body: { prepend: () => {} },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
delete globalThis.chrome;
|
||||||
|
delete globalThis.document;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a save from a page that never saw a wallet another page added", () => {
|
||||||
|
// The first DoD case on the issue: add a wallet in one page, then force
|
||||||
|
// a save from a second page loaded before that wallet existed. Both
|
||||||
|
// wallets must survive.
|
||||||
|
test("both wallets are in storage afterwards", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({ autistmask: { wallets: [W1] } });
|
||||||
|
|
||||||
|
// Loaded while storage held only Wallet 1, and never reloads —
|
||||||
|
// the approval window in the reproduction, or a second popup that
|
||||||
|
// has been open for a while.
|
||||||
|
const stale = loadPage(storage);
|
||||||
|
await stale.state.loadState();
|
||||||
|
expect(stale.state.state.wallets).toHaveLength(1);
|
||||||
|
|
||||||
|
// A second page, loaded after, adds a wallet — the exact sequence
|
||||||
|
// src/popup/views/addWallet.js uses.
|
||||||
|
const fresh = loadPage(storage);
|
||||||
|
await fresh.state.loadState();
|
||||||
|
fresh.state.state.wallets.push(W2);
|
||||||
|
fresh.state.state.hasWallet = true;
|
||||||
|
await fresh.state.saveState();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.wallets,
|
||||||
|
).toHaveLength(2);
|
||||||
|
|
||||||
|
// The stale page saves something that has nothing to do with
|
||||||
|
// wallets — exactly what showView() does on every navigation, and
|
||||||
|
// what backgroundRefresh() does after a balance poll.
|
||||||
|
stale.state.state.currentView = "settings";
|
||||||
|
await stale.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||||
|
"Wallet 1",
|
||||||
|
"Wallet 2",
|
||||||
|
]);
|
||||||
|
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||||
|
"secret-one",
|
||||||
|
"secret-two",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the approval-window reproduction", () => {
|
||||||
|
// approval window open, add a wallet in the popup, confirm the approval
|
||||||
|
// — the exact sequence from the issue. The approval window and the
|
||||||
|
// popup are the same popup code with a different starting view, so
|
||||||
|
// showView() is the real save path in both: src/popup/views/approval.js
|
||||||
|
// showTxApproval() calls showView("approve-tx") when the window opens,
|
||||||
|
// and a successful confirm calls
|
||||||
|
// src/popup/views/txStatus.js showWait() -> startWait(), which calls
|
||||||
|
// showView("wait-tx") — the save that clobbered the second wallet in
|
||||||
|
// the reproduction on the issue.
|
||||||
|
test("the wallet added in the popup survives confirming the approval", async () => {
|
||||||
|
globalThis.document = makeDocument();
|
||||||
|
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({ autistmask: { wallets: [W1] } });
|
||||||
|
|
||||||
|
// The background opens the approval window on the approve-tx
|
||||||
|
// screen; nothing else has happened yet.
|
||||||
|
const approvalWindow = loadPage(storage);
|
||||||
|
await approvalWindow.state.loadState();
|
||||||
|
approvalWindow.helpers.showView("approve-tx");
|
||||||
|
// showView() does not await its own saveState(); an extra save
|
||||||
|
// joins the same queue and only resolves once that one has too,
|
||||||
|
// which is the black-box way to know it landed.
|
||||||
|
await approvalWindow.state.saveState();
|
||||||
|
|
||||||
|
// The user adds a wallet in the popup — a separate page, loaded
|
||||||
|
// after the approval window.
|
||||||
|
const popup = loadPage(storage);
|
||||||
|
await popup.state.loadState();
|
||||||
|
popup.state.state.wallets.push(W2);
|
||||||
|
popup.state.state.hasWallet = true;
|
||||||
|
await popup.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.wallets,
|
||||||
|
).toHaveLength(2);
|
||||||
|
|
||||||
|
// The user confirms the approval. The approval window navigates
|
||||||
|
// approve-tx -> wait-tx, saving again from state it loaded before
|
||||||
|
// Wallet 2 ever existed.
|
||||||
|
approvalWindow.helpers.showView("wait-tx");
|
||||||
|
await approvalWindow.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||||
|
"Wallet 1",
|
||||||
|
"Wallet 2",
|
||||||
|
]);
|
||||||
|
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||||
|
"secret-one",
|
||||||
|
"secret-two",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// backgroundRefresh() (src/background/index.js) loads state, spends seconds
|
||||||
|
// on network I/O in refreshBalances() (src/shared/balances.js) mutating
|
||||||
|
// addr.balance/ensName/tokenBalances IN PLACE on the wallets it already
|
||||||
|
// knew about, then saves. Precondition 2 on the issue: that refresh window
|
||||||
|
// overlapping a membership change (add or delete) on another page must not
|
||||||
|
// clobber or resurrect a wallet — a whole-field diff on `wallets` failed
|
||||||
|
// this, because "background changed a balance" and "another page changed
|
||||||
|
// membership" collided as the same field.
|
||||||
|
describe("background refresh racing a wallet added on another page", () => {
|
||||||
|
test("the wallet added elsewhere survives background's stale balance save", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({ autistmask: { wallets: [W1] } });
|
||||||
|
|
||||||
|
// "background": loads first, and its save is the one that lands
|
||||||
|
// last, modeling the multi-second network round trip in between.
|
||||||
|
const background = loadPage(storage);
|
||||||
|
await background.state.loadState();
|
||||||
|
background.state.state.wallets[0].addresses[0].balance = "1.2345";
|
||||||
|
|
||||||
|
// A second page, loaded after, adds a wallet while background's
|
||||||
|
// refresh is still in flight.
|
||||||
|
const popup = loadPage(storage);
|
||||||
|
await popup.state.loadState();
|
||||||
|
popup.state.state.wallets.push(W2);
|
||||||
|
popup.state.state.hasWallet = true;
|
||||||
|
await popup.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.wallets,
|
||||||
|
).toHaveLength(2);
|
||||||
|
|
||||||
|
// background's save lands last, carrying only its balance update.
|
||||||
|
await background.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.wallets.map((w) => w.name)).toEqual([
|
||||||
|
"Wallet 1",
|
||||||
|
"Wallet 2",
|
||||||
|
]);
|
||||||
|
expect(persisted.wallets.map((w) => w.encryptedSecret)).toEqual([
|
||||||
|
"secret-one",
|
||||||
|
"secret-two",
|
||||||
|
]);
|
||||||
|
// The balance update itself must not be lost either — this is a
|
||||||
|
// merge, not deletion-always-wins.
|
||||||
|
expect(persisted.wallets[0].addresses[0].balance).toBe("1.2345");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("background refresh racing a wallet deleted on another page", () => {
|
||||||
|
test("the wallet deleted elsewhere stays deleted after background's stale balance save", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({ autistmask: { wallets: [W1, W2] } });
|
||||||
|
|
||||||
|
const background = loadPage(storage);
|
||||||
|
await background.state.loadState();
|
||||||
|
background.state.state.wallets[0].addresses[0].balance = "1.2345";
|
||||||
|
|
||||||
|
// A second page deletes Wallet 2 while background's refresh is in
|
||||||
|
// flight — the same splice deleteWallet.js's removeWalletFromState()
|
||||||
|
// does.
|
||||||
|
const popup = loadPage(storage);
|
||||||
|
await popup.state.loadState();
|
||||||
|
popup.state.state.wallets.splice(1, 1);
|
||||||
|
popup.state.state.hasWallet = popup.state.state.wallets.length > 0;
|
||||||
|
await popup.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.wallets,
|
||||||
|
).toHaveLength(1);
|
||||||
|
|
||||||
|
await background.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.wallets.map((w) => w.name)).toEqual(["Wallet 1"]);
|
||||||
|
expect(persisted.wallets[0].addresses[0].balance).toBe("1.2345");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// allowedSites/deniedSites: { [address]: [hostname, ...] }. Mutated in place
|
||||||
|
// from two different contexts — src/background/index.js:592-599 pushes a
|
||||||
|
// newly approved hostname onto state.allowedSites[activeAddress], and the
|
||||||
|
// Settings "revoke" button (src/popup/views/settings.js:55-68) filters a
|
||||||
|
// hostname out of state[key][addr] in place, deleting the address key
|
||||||
|
// entirely once its list is empty — the exact membership-vs-whole-field
|
||||||
|
// pattern that made the whole-field `wallets` diff unsafe, on a
|
||||||
|
// security-relevant field: a stale whole-field save here can resurrect a
|
||||||
|
// revoked permission or wipe a freshly granted one.
|
||||||
|
const ADDR1 = "0x66133E8ea0f5D1d612D2502a968757D1048c214a";
|
||||||
|
const ADDR2 = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
|
||||||
|
|
||||||
|
function approveSite(pageState, address, hostname) {
|
||||||
|
if (!pageState.allowedSites[address]) {
|
||||||
|
pageState.allowedSites[address] = [];
|
||||||
|
}
|
||||||
|
if (!pageState.allowedSites[address].includes(hostname)) {
|
||||||
|
pageState.allowedSites[address].push(hostname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function revokeSite(pageState, hostname) {
|
||||||
|
for (const addr of Object.keys(pageState.allowedSites)) {
|
||||||
|
pageState.allowedSites[addr] = pageState.allowedSites[addr].filter(
|
||||||
|
(h) => h !== hostname,
|
||||||
|
);
|
||||||
|
if (pageState.allowedSites[addr].length === 0) {
|
||||||
|
delete pageState.allowedSites[addr];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("a dApp approval racing a stale Settings page's later save", () => {
|
||||||
|
test("the fresh approval survives Settings revoking an unrelated site", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({
|
||||||
|
autistmask: {
|
||||||
|
wallets: [W1],
|
||||||
|
allowedSites: { [ADDR2]: ["other.example"] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Settings loads first, and its save lands last — before either has
|
||||||
|
// any idea a dApp approval happened elsewhere in between.
|
||||||
|
const settings = loadPage(storage);
|
||||||
|
await settings.state.loadState();
|
||||||
|
|
||||||
|
// A dApp approval window, opened later, approves a new site for a
|
||||||
|
// different address and saves — the real sequence at
|
||||||
|
// src/background/index.js:592-599.
|
||||||
|
const approval = loadPage(storage);
|
||||||
|
await approval.state.loadState();
|
||||||
|
approveSite(approval.state.state, ADDR1, "dapp.example");
|
||||||
|
await approval.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.allowedSites[ADDR1],
|
||||||
|
).toEqual(["dapp.example"]);
|
||||||
|
|
||||||
|
// Settings revokes its own, unrelated site — the real sequence at
|
||||||
|
// src/popup/views/settings.js:55-68 — and saves from state loaded
|
||||||
|
// before the dApp approval ever happened.
|
||||||
|
revokeSite(settings.state.state, "other.example");
|
||||||
|
await settings.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.allowedSites[ADDR1]).toEqual(["dapp.example"]);
|
||||||
|
expect(persisted.allowedSites[ADDR2]).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a revoked site permission against a stale page's later save", () => {
|
||||||
|
test("the revocation holds even when the stale page approves something else", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({
|
||||||
|
autistmask: {
|
||||||
|
wallets: [W1],
|
||||||
|
allowedSites: { [ADDR1]: ["evil.example"] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// A stale page loads while the permission still stands.
|
||||||
|
const stale = loadPage(storage);
|
||||||
|
await stale.state.loadState();
|
||||||
|
|
||||||
|
// Settings revokes it — src/popup/views/settings.js:55-68 — from a
|
||||||
|
// second page.
|
||||||
|
const settings = loadPage(storage);
|
||||||
|
await settings.state.loadState();
|
||||||
|
revokeSite(settings.state.state, "evil.example");
|
||||||
|
await settings.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.allowedSites[ADDR1],
|
||||||
|
).toBeUndefined();
|
||||||
|
|
||||||
|
// The stale page, unaware of the revoke, approves an unrelated site
|
||||||
|
// for a different address and saves — src/background/index.js:592-599.
|
||||||
|
approveSite(stale.state.state, ADDR2, "good.example");
|
||||||
|
await stale.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
expect(persisted.allowedSites[ADDR2]).toEqual(["good.example"]);
|
||||||
|
expect(persisted.allowedSites[ADDR1]).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// mergeListByIdentity()'s identity function is not guaranteed collision-free
|
||||||
|
// — walletIdentity() falls back to one shared "addr:" value for any wallet
|
||||||
|
// with neither an xpub nor a populated first address (a legacy or corrupt
|
||||||
|
// record). Two such records created independently on two different pages
|
||||||
|
// must not silently collapse into one, dropping the loser's
|
||||||
|
// encryptedSecret with no error and no log.
|
||||||
|
function legacyWallet(name, secret) {
|
||||||
|
return {
|
||||||
|
type: "legacy",
|
||||||
|
name,
|
||||||
|
encryptedSecret: secret,
|
||||||
|
nextIndex: 0,
|
||||||
|
addresses: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("two wallets independently created with a colliding identity", () => {
|
||||||
|
test("both survive, encryptedSecret included, instead of one silently replacing the other", async () => {
|
||||||
|
const storage = makeStorage();
|
||||||
|
await storage.set({ autistmask: { wallets: [W1] } });
|
||||||
|
|
||||||
|
// Both pages load before either has created their malformed wallet,
|
||||||
|
// so neither has baseline knowledge of the other's.
|
||||||
|
const pageA = loadPage(storage);
|
||||||
|
await pageA.state.loadState();
|
||||||
|
const pageB = loadPage(storage);
|
||||||
|
await pageB.state.loadState();
|
||||||
|
|
||||||
|
pageA.state.state.wallets.push(legacyWallet("Legacy A", "secret-a"));
|
||||||
|
pageA.state.state.hasWallet = true;
|
||||||
|
await pageA.state.saveState();
|
||||||
|
expect(
|
||||||
|
(await storage.get("autistmask")).autistmask.wallets,
|
||||||
|
).toHaveLength(2);
|
||||||
|
|
||||||
|
pageB.state.state.wallets.push(legacyWallet("Legacy B", "secret-b"));
|
||||||
|
pageB.state.state.hasWallet = true;
|
||||||
|
await pageB.state.saveState();
|
||||||
|
|
||||||
|
const persisted = (await storage.get("autistmask")).autistmask;
|
||||||
|
const secrets = persisted.wallets.map((w) => w.encryptedSecret);
|
||||||
|
expect(secrets).toContain("secret-one");
|
||||||
|
expect(secrets).toContain("secret-a");
|
||||||
|
expect(secrets).toContain("secret-b");
|
||||||
|
});
|
||||||
|
});
|
||||||
176
tests/uniswapUnknownDecimals.test.js
Normal file
176
tests/uniswapUnknownDecimals.test.js
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
// The scale the swap lines of the dApp approval screen are displayed with.
|
||||||
|
//
|
||||||
|
// Issue #340: `tokenInfo()` in `src/shared/uniswap.js` returned `decimals: 18`
|
||||||
|
// for any token absent from the bundled list — the same guess
|
||||||
|
// https://git.eeqj.de/sneak/AutistMask/issues/306 removed from the ERC-20
|
||||||
|
// amount line, still live on the swap path. A 1,000-token swap of a 6-decimal
|
||||||
|
// token then rendered as `0.000000001` on the one screen whose job is to state
|
||||||
|
// what is being authorized, and every newly listed token reaches it.
|
||||||
|
//
|
||||||
|
// What is asserted here is the rule #306 established: resolve the real scale
|
||||||
|
// wherever the wallet already has it, and where nothing has it refuse to
|
||||||
|
// format — base units with the scale stated, never a quantity.
|
||||||
|
|
||||||
|
globalThis.chrome = {
|
||||||
|
storage: { local: { get: async () => ({}), set: async () => {} } },
|
||||||
|
};
|
||||||
|
|
||||||
|
const { AbiCoder, Interface } = require("ethers");
|
||||||
|
const { state } = require("../src/shared/state");
|
||||||
|
const { unknownDecimalsAmount } = require("../src/shared/approvalAmount");
|
||||||
|
const { decodeCalldata } = require("../src/popup/views/approval");
|
||||||
|
|
||||||
|
const ROUTER = "0x66a9893cc07d91d95644aedd05d03f95e1dba8af";
|
||||||
|
const RECIPIENT = "0xC0FfEE0000000000000000000000000000c0fFEe";
|
||||||
|
// Outside the bundled list, as every newly listed token is.
|
||||||
|
const NOVEL = "0xE2E0000000000000000000000000000000000E2e";
|
||||||
|
// Also outside it, standing in for the swap's output side.
|
||||||
|
const NOVEL_OUT = "0xd0d0000000000000000000000000000000000d0d";
|
||||||
|
// In the bundled list, at 18 decimals.
|
||||||
|
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
|
||||||
|
|
||||||
|
// 1,000.00 of a 6-decimal token — the amount from the issue, which the 18
|
||||||
|
// guess rendered as 0.000000001.
|
||||||
|
const THOUSAND_AT_SIX = 1000000000n;
|
||||||
|
// 0.5 WETH out, so the Min. received line has a real number of its own.
|
||||||
|
const HALF_WETH = 500000000000000000n;
|
||||||
|
|
||||||
|
const coder = AbiCoder.defaultAbiCoder();
|
||||||
|
const routerIface = new Interface([
|
||||||
|
"function execute(bytes commands, bytes[] inputs, uint256 deadline)",
|
||||||
|
]);
|
||||||
|
|
||||||
|
// A V2_SWAP_EXACT_IN (command 0x08) execute() call: `amountIn` of `tokenIn`
|
||||||
|
// for at least `amountOutMin` of `tokenOut`.
|
||||||
|
function swapData(tokenIn, amountIn, tokenOut, amountOutMin) {
|
||||||
|
const input = coder.encode(
|
||||||
|
["address", "uint256", "uint256", "address[]", "bool"],
|
||||||
|
[RECIPIENT, amountIn, amountOutMin, [tokenIn, tokenOut], true],
|
||||||
|
);
|
||||||
|
return routerIface.encodeFunctionData("execute", [
|
||||||
|
"0x08",
|
||||||
|
[input],
|
||||||
|
9999999999n,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A wallet holding `token` with the decimals the block explorer reported,
|
||||||
|
// shaped as balances.js writes it onto state.
|
||||||
|
function walletsHolding(token, decimals) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: "Wallet 1",
|
||||||
|
addresses: [
|
||||||
|
{
|
||||||
|
address: "0x" + "a".repeat(40),
|
||||||
|
balance: "1.0",
|
||||||
|
tokenBalances: [
|
||||||
|
{
|
||||||
|
address: token,
|
||||||
|
symbol: "NOVEL",
|
||||||
|
decimals,
|
||||||
|
balance: "1000.0",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// The swap detail line as the approval screen renders it. It goes through
|
||||||
|
// decodeCalldata() rather than uniswap.decode() directly, because the scale
|
||||||
|
// sources the screen supplies are part of what is under test.
|
||||||
|
function swapDetail(data, label) {
|
||||||
|
const decoded = decodeCalldata(data, ROUTER);
|
||||||
|
return decoded.details.find((d) => d.label === label);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
state.trackedTokens = [];
|
||||||
|
state.wallets = [];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a swap of a token outside the bundled list", () => {
|
||||||
|
const data = () => swapData(NOVEL, THOUSAND_AT_SIX, WETH, HALF_WETH);
|
||||||
|
|
||||||
|
test("shows the true quantity when the user tracks the token", () => {
|
||||||
|
state.trackedTokens = [
|
||||||
|
{ address: NOVEL, symbol: "NOVEL", decimals: 6 },
|
||||||
|
];
|
||||||
|
expect(swapDetail(data(), "Amount").value).toBe("1000.0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows the true quantity from the explorer's decimals", () => {
|
||||||
|
state.wallets = walletsHolding(NOVEL, "6");
|
||||||
|
expect(swapDetail(data(), "Amount").value).toBe("1000.0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("refuses to format when nothing knows the scale", () => {
|
||||||
|
const detail = swapDetail(data(), "Amount");
|
||||||
|
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||||
|
expect(detail.value).toBe(unknownDecimalsAmount(THOUSAND_AT_SIX));
|
||||||
|
// The defect: an 18-decimal guess renders this swap as 0.000000001, a
|
||||||
|
// quantity, and a wrong one.
|
||||||
|
expect(detail.value).not.toMatch(/^0\./);
|
||||||
|
expect(detail.value).not.toMatch(/[0-9]\.[0-9]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the amount carried to the status screens is the same refusal", () => {
|
||||||
|
expect(swapDetail(data(), "Amount").rawValue).toBe(
|
||||||
|
"1000000000 base units (decimals unknown)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a bundled token on the other side still formats", () => {
|
||||||
|
expect(swapDetail(data(), "Min. received").value).toBe("0.5000 WETH");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the Min. received line takes the same rule", () => {
|
||||||
|
test("refuses to format an output token of unknown scale", () => {
|
||||||
|
const data = swapData(WETH, HALF_WETH, NOVEL_OUT, THOUSAND_AT_SIX);
|
||||||
|
const detail = swapDetail(data, "Min. received");
|
||||||
|
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||||
|
expect(detail.value).not.toMatch(/[0-9]\.[0-9]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows the true quantity when the user tracks the output token", () => {
|
||||||
|
state.trackedTokens = [
|
||||||
|
{ address: NOVEL_OUT, symbol: "NOVEL", decimals: 6 },
|
||||||
|
];
|
||||||
|
const data = swapData(WETH, HALF_WETH, NOVEL_OUT, THOUSAND_AT_SIX);
|
||||||
|
expect(swapDetail(data, "Min. received").value).toBe("1000.0000");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the permit amount takes the same rule", () => {
|
||||||
|
// PERMIT2_PERMIT (command 0x0a): the input token and amount come from the
|
||||||
|
// permit rather than from a swap step.
|
||||||
|
function permitData(token, amount) {
|
||||||
|
const input = coder.encode(
|
||||||
|
[
|
||||||
|
"tuple(tuple(address,uint160,uint48,uint48),address,uint256)",
|
||||||
|
"bytes",
|
||||||
|
],
|
||||||
|
[[[token, amount, 0, 0], ROUTER, 9999999999], "0x1234"],
|
||||||
|
);
|
||||||
|
return routerIface.encodeFunctionData("execute", [
|
||||||
|
"0x0a",
|
||||||
|
[input],
|
||||||
|
9999999999n,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("refuses to format a permit on a token of unknown scale", () => {
|
||||||
|
const detail = swapDetail(permitData(NOVEL, THOUSAND_AT_SIX), "Amount");
|
||||||
|
expect(detail.value).toBe("1000000000 base units (decimals unknown)");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an unbounded permit is still named, with or without a scale", () => {
|
||||||
|
const maxUint160 = (1n << 160n) - 1n;
|
||||||
|
expect(swapDetail(permitData(NOVEL, maxUint160), "Amount").value).toBe(
|
||||||
|
"Unlimited",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
97
tests/version.test.js
Normal file
97
tests/version.test.js
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
// One version, three files, and the rule that they agree.
|
||||||
|
//
|
||||||
|
// package.json, manifest/chrome.json and manifest/firefox.json each declare a
|
||||||
|
// version and none is derived from another. Before this, nothing compared
|
||||||
|
// them: the manifests were hardcoded at 0.1.0 and copied to dist/ verbatim
|
||||||
|
// while package.json fed the About screen separately, so the number the
|
||||||
|
// browser reported and the number the extension displayed could drift apart
|
||||||
|
// with no check anywhere failing.
|
||||||
|
//
|
||||||
|
// The build enforces the agreement (build.js calls resolveVersion before it
|
||||||
|
// emits anything) and script/lib/package.js names the artifacts from it. This
|
||||||
|
// asserts both halves: that the tree as committed agrees, and that a tree that
|
||||||
|
// does not is refused rather than resolved to one of the answers.
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
|
const {
|
||||||
|
VERSION_SOURCES,
|
||||||
|
declaredVersions,
|
||||||
|
resolveVersion,
|
||||||
|
} = require("../script/lib/version");
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, "..");
|
||||||
|
|
||||||
|
// A tree containing only the three version files, with the given versions.
|
||||||
|
function fixture(versions) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "autistmask-version-"));
|
||||||
|
fs.mkdirSync(path.join(dir, "manifest"));
|
||||||
|
VERSION_SOURCES.forEach((source, i) => {
|
||||||
|
fs.writeFileSync(
|
||||||
|
path.join(dir, source),
|
||||||
|
JSON.stringify({ version: versions[i] }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("the declared version", () => {
|
||||||
|
test("all three sources agree in this tree", () => {
|
||||||
|
const declared = declaredVersions(ROOT);
|
||||||
|
expect(declared.map((d) => d.source)).toEqual(VERSION_SOURCES);
|
||||||
|
expect([...new Set(declared.map((d) => d.version))]).toHaveLength(1);
|
||||||
|
expect(resolveVersion(ROOT)).toBe(declared[0].version);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Semver-shaped, because it names every release artifact and is what the
|
||||||
|
// browser compares when deciding whether an install is an upgrade.
|
||||||
|
test("is semver-shaped", () => {
|
||||||
|
expect(resolveVersion(ROOT)).toMatch(/^\d+\.\d+\.\d+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The load-bearing case: each of the three, disagreeing on its own, has to
|
||||||
|
// fail. A check that only looked at two of them would pass one of these.
|
||||||
|
test.each([
|
||||||
|
["package.json", ["9.9.9", "0.1.0", "0.1.0"]],
|
||||||
|
["manifest/chrome.json", ["0.1.0", "9.9.9", "0.1.0"]],
|
||||||
|
["manifest/firefox.json", ["0.1.0", "0.1.0", "9.9.9"]],
|
||||||
|
])("a disagreeing %s fails rather than resolving", (source, versions) => {
|
||||||
|
const dir = fixture(versions);
|
||||||
|
try {
|
||||||
|
expect(() => resolveVersion(dir)).toThrow(
|
||||||
|
/the declared versions disagree/,
|
||||||
|
);
|
||||||
|
expect(() => resolveVersion(dir)).toThrow(new RegExp(source));
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("agreeing sources resolve", () => {
|
||||||
|
const dir = fixture(["1.2.3", "1.2.3", "1.2.3"]);
|
||||||
|
try {
|
||||||
|
expect(resolveVersion(dir)).toBe("1.2.3");
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// A missing or empty version is not agreement. Left unchecked, three files
|
||||||
|
// that all declared nothing would "agree" on undefined and the artifacts
|
||||||
|
// would be named after it.
|
||||||
|
test.each([[undefined], [""], [" "], [3]])(
|
||||||
|
"a version of %p is refused",
|
||||||
|
(bad) => {
|
||||||
|
const dir = fixture([bad, bad, bad]);
|
||||||
|
try {
|
||||||
|
expect(() => resolveVersion(dir)).toThrow(
|
||||||
|
/declares no usable "version"/,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user