diff --git a/.github/workflows/webapp.yml b/.github/workflows/webapp.yml index 6abe9931..ab9c7881 100644 --- a/.github/workflows/webapp.yml +++ b/.github/workflows/webapp.yml @@ -36,6 +36,33 @@ jobs: - run: npm test - run: npm run build + pages: + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + needs: unit + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + cache-dependency-path: webapp/package-lock.json + - run: npm ci + - run: npm run build + - uses: actions/upload-pages-artifact@v3 + with: + path: webapp/dist + - id: deploy + uses: actions/deploy-pages@v4 + e2e: runs-on: ubuntu-24.04 timeout-minutes: 150 @@ -85,12 +112,21 @@ jobs: ulimit -c 0 npx playwright test --project=${{ matrix.browser }} - name: Production build tests + if: ${{ !cancelled() }} run: | ulimit -c 0 - npm run build + npx vite build --mode devchain npx vite preview --host 127.0.0.1 & curl -fs -o /dev/null --retry 30 --retry-delay 1 --retry-all-errors http://127.0.0.1:4173/ - BASE_URL=http://127.0.0.1:4173 npx playwright test --project=${{ matrix.browser }} e2e/offline.spec.ts e2e/track.spec.ts e2e/mode-cache.spec.ts + BASE_URL=http://127.0.0.1:4173 npx playwright test --project=${{ matrix.browser }} e2e/offline.spec.ts e2e/track.spec.ts e2e/mode-cache.spec.ts e2e/card.spec.ts e2e/pages.spec.ts + - name: API on its own origin + if: ${{ !cancelled() }} + run: | + ulimit -c 0 + VITE_API_ORIGIN=http://127.0.0.1:8099 npx vite build --mode devchain --outDir dist-api + npx vite preview --host 127.0.0.1 --port 4174 --outDir dist-api & + curl -fs -o /dev/null --retry 30 --retry-delay 1 --retry-all-errors http://127.0.0.1:4174/ + API_ORIGIN=http://127.0.0.1:8099 BASE_URL=http://127.0.0.1:4174 npx playwright test --project=${{ matrix.browser }} e2e/pages.spec.ts - name: Screens id: screens if: ${{ !cancelled() && matrix.browser == 'chromium' }} diff --git a/webapp/.gitignore b/webapp/.gitignore index d88469e2..a11b3556 100644 --- a/webapp/.gitignore +++ b/webapp/.gitignore @@ -1,5 +1,7 @@ node_modules/ dist/ +dist-card/ +dist-api/ test-results/ playwright-report/ dev/local-chain*.json diff --git a/webapp/README.md b/webapp/README.md index f4c6164e..ff6ae30f 100644 --- a/webapp/README.md +++ b/webapp/README.md @@ -2,22 +2,22 @@ The store for SimpleX names on simplex.domains: search a name, pay by card, Bitcoin or Monero (or with a prepaid code), and register it on chain to a wallet made from the buyer's name code. It follows the design in simplex-chat `plans/names-codes/` (spec, sequence diagrams and mockups). -The page talks only to the names service under `/api`. In development that service is `dev/mock.ts`, which drives the real contracts on a local chain and reads names from them directly, as the service does over its Ethereum RPC. +The page talks only to the names service's `/api`, at `SITE.apiOrigin`, and to the card page it frames for a card payment. In development that service is `dev/mock.ts`, which drives the real contracts on a local chain and reads names from them directly, as the service does over its Ethereum RPC. ## Layout -- `src/crypto/`: owner and prepaid codes, the wallet, the commitment and the signed messages, the sealed order. +- `src/crypto/`: owner and prepaid codes, the wallet, the commitment and the signed messages, the sealed order, the payment addresses' proofs. - `src/flow.ts`: building an order, revealing it, a name selected for an order whose name was taken first, finding a name code's order, link edits. - `src/api.ts`, `src/store.ts`, `src/session.ts`: the service's API, what this browser keeps, and the tab's checkout and active prepaid code. -- `src/config.ts`: what differs between deployments, the service's mode, `open` or `codes` (`src/mode.ts`, see Codes only), and the Stripe publishable key, read from `GET /api/config` before the page draws; `index.html` preloads it while the modules load. +- `src/config.ts`: the deployment the page holds, `SITE`: the chain, the contracts, the TLD, the term's start, the paid and community years, the years a code may give, the prices and their currency, the terms, the keys payments go to (Bitcoin receiving keys and Monero primary addresses, with their networks' prefixes) and the mode, `open` or `codes` (`src/mode.ts`, see Codes only). A production build holds `MAINNET` alone; any other build and the dev server hold `LOCAL`, the dev chain's, which `dev/deploy.ts` checks its deployment against and takes its prices from. The page signs and draws with these values, whatever the service answers. It offers a name for an order only when its search answer has these terms of the name's kind and these years and, unless a code registers it, this price; it signs an order or a reveal only for this name policy and the terms the buyer agreed to, which are these terms, and a reveal only for the order's own term; it takes a code only for these years, and a refusal for changed terms or a changed price only with these terms or this price. From `GET /api/config` it reads only the service's downtime, before it draws, for at most 5 seconds; `index.html` preloads it while the modules load. - `src/screens/`: each view's state and the reducer that moves it, with no clock, DOM, storage or network. - `src/views/`: `shell.ts`, the frame between `index.html`'s header and its invest note and footer (`draw` puts a screen in, `kept` keeps a node a reader types into across redraws, `screen` and `outcome` build the two kinds of screen, `asStep` gives a screen the steps' frame); `chrome.ts`, the phone's menu and the header's active code; and the views: `search.ts` (the home), `checkout.ts` (the Links, name code, Community terms and Check your order steps), `order.ts` (payment, registration and every ending) and `names.ts` (Your names, Check your code and Edit links). `chats.ts` draws the chats a name opens, as the app's default pictures, and their popup after the app's connection alert; `links.ts` holds the link field that the Links step and Edit links share; `codes.ts` the code field of Check your code and of Check your order. -- `src/stripe.ts`: Stripe's Payment Element, mounted when the page carries a publishable key. +- `src/stripe.ts`, `card/` and `src/card-frame.ts`: Stripe's Payment Element, mounted by the card page on its own origin after its PaymentIntent check, and the frame the order's page holds it in. - `src/scan.ts` and `src/views/scan.ts`: a phone's camera reading a link's QR code into the Link field, by the browser's `BarcodeDetector` where it reads QR codes, otherwise by jsQR (Apache-2.0), which is served from the page's own origin and runs only when it first reads a frame; the service worker caches it with the rest of the build, so a page opened before a deploy still reads codes after it. The scan button shows only on a phone with a camera; a camera refused or missing says so, and Paste stays. -- `dev/`: the local chain deployment, its dummy terms (`dev/fixtures/terms/`), the server of their texts, the mock service and `start.sh`. +- `dev/`: the local chain deployment, its dummy terms (`dev/fixtures/terms/`), the server of their texts, the mock service, `start.sh`, and `check-mainnet.ts`, which compares `MAINNET` with the chain (Hosting). - `test/`: unit tests (vitest). `e2e/`: browser tests (Playwright) against the dev backend. -The window holds the header, the screen and the invest note; the footer is below the fold, as on the badges store. The purchase steps (search, Links, name code, Community terms for a community name, Check your order, payment) follow one another. Each step, and each screen like one (an order's outcome, Check your code, Edit links), is a frame of one height, 540 px on a laptop and 640 px on a phone, as the mockup draws it, so Back, the heading, the main button and the link under it stand at the same place on every step, for a name of any length; a step without a main button keeps its link at the link's place, and on a laptop a step's last link stays at least 48 px above the invest note. The content runs down from under the heading, so nothing above a change moves. The home keeps its answer's room from the start, so its headline and field never move. A plain name's order waits for its buyer to agree to the general terms on Check your order, whose words link the terms' page at the commit the name policy links; a community name's order waits for its buyer to accept its community terms, which include the general terms, on their own step, which shows their text as the service fetches it by the name policy's link and, for a link to git.simplex.chat or GitHub, links that commit's page. While the terms of a name's kind cannot be read, its search answer says that names can't be ordered right now. A community name is registered for 2 years, even with a code for more, which Check your order then says. On Check your order, I have a code, under the payment choices, opens a code field in their place: a prepaid code that covers the name makes the order free, as the tab's code does, and Remove code, under the main button, brings the payment choices back. A pay page checks its name as it opens and every 5 minutes; when someone has registered it meanwhile, its note turns red and the payment's details are turned off. The page signs each order's registration over the dispute days of its payment, by its own table: 120 for a card, and 14 for Bitcoin, Monero or a prepaid code. An order is signed so when it is placed, a closed order's new invoice over the days of that invoice's payment, and a name selected for a taken order over the days of the order's payment. A registration signed again later, by the order's page or by Continue, is signed over the days of the payment in this browser's record of the order. In a record made in this browser, the payment is kept when the order is reopened with its code. In a record of an order made in another browser, the payment is the one the service reported. A service that expects other days refuses the signature: Check your order then says, for an order or a selection, that the order could not be placed, a closed order's page says so of its new invoice, the order's page says, after three refusals, that the name could not be signed, and Continue says that it did not work. Once the order is ended in the service's view, which the service sets at its hourly check of the chain, or at its check of a mined register when the name was unregistered before the register was confirmed, the order's page says so: at once while it follows the registration, and when it is next opened once it has stopped reading a registered order. Your names marks its row Cancelled, and Edit links says that the registration was cancelled. Until that check, Your names shows a name unregistered on chain with its expiry date and the Name code button alone, and Edit links says that the name could not be loaded now and reads it again every 5 seconds. A prepaid code entered in Check your code registers the names the tab finds for free until it is taken off in the header; a name code entered there finds its order and adds it to Your names, or, reached from an order's page, opens the order it found. Every screen replaces the whole page between the header and the invest note and rises into place (220 ms); the old screen goes at once, so two never show together. What a step adds, such as a search's answer, a notice or a link's profile, fades in (180 ms); a change of theme eases its colours (200 ms). A reader who asks for reduced motion gets none of it. +The window holds the header, the screen and the invest note; the footer is below the fold, as on the badges store. The purchase steps (search, Links, name code, Community terms for a community name, Check your order, payment) follow one another. Each step, and each screen like one (an order's outcome, Check your code, Edit links), is a frame of one height, 540 px on a laptop and 640 px on a phone, as the mockup draws it, so Back, the heading, the main button and the link under it stand at the same place on every step, for a name of any length; a step without a main button keeps its link at the link's place, and on a laptop a step's last link stays at least 48 px above the invest note. The content runs down from under the heading, so nothing above a change moves. The home keeps its answer's room from the start, so its headline and field never move. A plain name's order waits for its buyer to agree to the general terms on Check your order, whose words link the terms' page at the commit the name policy links; a community name's order waits for its buyer to accept its community terms, which include the general terms, on their own step, which shows their text as the service fetches it by the name policy's link and, for a link to git.simplex.chat or GitHub, links that commit's page. While the terms of a name's kind cannot be read, its search answer says that names can't be ordered right now. A community name is registered for 2 years, even with a code for more, which Check your order then says. On Check your order, I have a code, under the payment choices, opens a code field in their place: a prepaid code that covers the name makes the order free, as the tab's code does, and Remove code, under the main button, brings the payment choices back. A pay page checks its name as it opens and every 5 minutes; when someone has registered it meanwhile, its note turns red and the payment's details are turned off. The page signs each order's registration over the dispute days of its payment, by its own table: 120 for a card, and 14 for Bitcoin, Monero or a prepaid code. An order is signed so when it is placed, a closed order's new invoice over the days of that invoice's payment, and a name selected for a taken order over the days of the order's payment. A registration signed again later, by the order's page or by Continue, is signed over the days of the payment in this browser's record of the order. A record is given the payment asked for, which the order seals beside its name and links, so an order reopened with its code, in this browser or another, keeps it; for an order sealed before its payment was, a record made in this browser keeps its own, and one of another browser takes the payment the service reported. The order seals the terms its buyer agreed to too, which an order reopened in another browser signs; one sealed before its terms were takes the terms the service reports. An open invoice of another payment than its order asked for, of another amount than the price the page holds for its name, in another currency than dollars, or to an address that its proof does not derive from the page's keys (`src/crypto/payees.ts`: a Bitcoin address from one of `SITE.bitcoinReceiveKeys` and the invoice's key tweak, a Monero subaddress from one of `SITE.moneroPrimaryAddresses`, its spend tweak and a proof that its view key is the wallet's), or to an address other than the one the order's record keeps for it, is drawn without its payment details, saying that they could not be checked. The record keeps each invoice's address and address proof as the service first sent them; beside the reference line of every screen of an order's page, and in its refund, Copy for support copies the reference of an invoice paid to an address and that proof; the payment screen shows the reference in its payment card alone. A record restored with the name code takes the invoice's address and proof as the service gives them then. A service that expects other days refuses the signature: Check your order then says, for an order or a selection, that the order could not be placed, a closed order's page says so of its new invoice, the order's page says, after three refusals, that the name could not be signed, and Continue says that it did not work. Continue on an order whose terms of the name's kind changed since it was placed asks its buyer to accept them first, as the order's page does before a reveal. Once the order is ended in the service's view, which the service sets at its hourly check of the chain, or at its check of a mined register when the name was unregistered before the register was confirmed, the order's page says so: at once while it follows the registration, and when it is next opened once it has stopped reading a registered order. Your names marks its row Cancelled, and Edit links says that the registration was cancelled. Until that check, Your names shows a name unregistered on chain with its expiry date and the Name code button alone, and Edit links says that the name could not be loaded now and reads it again every 5 seconds. A prepaid code entered in Check your code registers the names the tab finds for free until it is taken off in the header; a name code entered there finds its order and adds it to Your names, or, reached from an order's page, opens the order it found. The name address, the checksummed address of the name code's wallet, which the buyer sends with support requests, stands beside the name code wherever it is shown: on the name code step, in Check your code, and, with a link to the SimpleX Names app's page of that address (`SITE.appOrigin/`), under "Registered until …" on the registered order's page, with the code hidden, and in a registered row's name code in Your names. On a phone, the registered order's page grows past the window under a name of more than about 25 letters, and on a laptop under one of 63. Every screen replaces the whole page between the header and the invest note and rises into place (220 ms); the old screen goes at once, so two never show together. What a step adds, such as a search's answer, a notice or a link's profile, fades in (180 ms); a change of theme eases its colours (200 ms). A reader who asks for reduced motion gets none of it. ## Run everything with Docker @@ -27,7 +27,7 @@ From this directory, with Docker Compose: docker compose up --build ``` -The first build compiles the contracts (a few minutes). Each start deploys them to a fresh local chain, which takes about 2 minutes; the page is then on http://localhost:5173. The mock's controls are on http://localhost:8099/control/… (see below), the chain's RPC on http://localhost:8545 and the terms' texts, which the page links, on http://localhost:8098. `docker compose --profile prod up --build preview` serves the production build on http://localhost:4173. +The first build compiles the contracts (a few minutes). Each start deploys them to a fresh local chain, which takes about 2 minutes; the page is then on http://localhost:5173. The mock's controls are on http://localhost:8099/control/… (see below), the chain's RPC on http://localhost:8545 and the terms' texts, which the page links, on http://localhost:8098. `docker compose --profile prod up --build preview` serves a build for the dev chain, `vite build --mode devchain`, on http://localhost:4173. Open the page on `localhost`: the browser gives its crypto API only to a secure context, which plain http on any other address is not. @@ -62,13 +62,15 @@ ENS_CONTRACTS_DIR= ANVIL= MIN_COMMITMENT_AGE=10 dev/start. npm run dev ``` -`start.sh` starts anvil (one block a second) and `dev/serve-terms.ts`, which serves the files of `dev/terms/` (gitignored) on http://127.0.0.1:8098/terms/, each named by the sha256 of its bytes, so a link set earlier keeps its text. It deploys the contracts with `dev/deploy.ts`, seeds the price oracle with the launch prices ($100, $200 and $400 for 2 years at 8 or more, 7 and 6 letters), wires the name policy, which reserves `support`, `simplex` and `official`, links the dummy terms `dev/fixtures/terms/general-terms.md` and `community-terms.md`, written to `dev/terms/`, as its general terms and community terms, and lists the community names `bakers` and `bakehouse`, registers `bakery` (with links) and `harbour` (without) under the general terms and `bakehouse` (with links) under the community terms, which their holder accepts, then starts the mock on 127.0.0.1:8099. The deployment file records both links and their hashes. It prints three prepaid codes. The mock follows the store API contract (simplex-chat `plans/names-codes/2026-10-21-store-api.md`): it quotes prices from the oracle, starts every term on 1 January 2027, checks each order's owner signature and that each order and each selection of a name signs the hash of the terms of its name's kind (after `community/` for a name on the name policy's community list), refusing it with `terms_unavailable` while their text cannot be fetched, that each reveal includes its owner's acceptance of those terms, which it relays to the name policy before the register, answers the text of either current terms, fetched by the name policy's link, at `/api/terms/`, which the page shows, and gives each invoice a Bitcoin regtest or Monero stagenet address. A link's data, in a name's answer and a link's preview, is the service's: its type and read state, and of a profile read its names and picture, an address's peer type and business flag, and a channel's group type and member count, from which the page tells the app's kinds (contact, channel, business or bot) and a channel's subscribers; the mock makes a contact link whose fragment starts with `Biz` a business, `Bot` a bot, `Pic` one with a picture, `Off` one whose host it does not fetch (no profile, `unavailable`), and a contact or channel link whose fragment starts with `Unr` one whose data could not be read now (no profile, `unread`). A link the chat core cannot parse, as one whose key does not decode as base64url and encode back to itself, or a `simplex:/` link without `h`, is refused with `invalid_link` and left out of a name's answer. Of the service's rate limits the mock keeps the code limit: 10 code checks and code orders a minute per client, a client being the last address in `X-Forwarded-For` (as the service with `trust_forwarded_for` takes it), else the connection's; the browser tests give each test an address of its own. Vite serves the page on http://127.0.0.1:5173 and proxies `/api` and `/control` to the mock. +`start.sh` starts anvil (one block a second) and `dev/serve-terms.ts`, which serves the files of `dev/terms/` (gitignored) on http://127.0.0.1:8098/terms/, each named by the sha256 of its bytes, so a link set earlier keeps its text. It deploys the contracts with `dev/deploy.ts`, seeds the price oracle with the launch prices ($100, $200 and $400 for 2 years at 8 or more, 7 and 6 letters), wires the name policy, which reserves `support`, `simplex` and `official`, links the dummy terms `dev/fixtures/terms/general-terms.md` and `community-terms.md`, written to `dev/terms/`, as its general terms and community terms, and lists the community names `bakers` and `bakehouse`, registers `bakery` (with links) and `harbour` (without) under the general terms and `bakehouse` (with links) under the community terms, which their holder accepts, then starts the mock on 127.0.0.1:8099. The deployment file records both links and their hashes. It prints three prepaid codes. The mock follows the store API contract (simplex-chat `plans/names-codes/2026-10-21-store-api.md`): it quotes prices from the oracle, starts every term on 1 January 2027, checks each order's owner signature and that each order and each selection of a name signs the hash of the terms of its name's kind (after `community/` for a name on the name policy's community list), refusing it with `terms_unavailable` while their text cannot be fetched, that each reveal includes its owner's acceptance of those terms, which it relays to the name policy before the register, answers the text of either current terms, fetched by the name policy's link, at `/api/terms/`, which the page shows, and gives each invoice a Bitcoin regtest address or a Monero stagenet subaddress, at an index drawn from the invoice's id, with its address proof, from the dev keys of the store service's recorded fixtures, which `LOCAL` holds (`dev/mock/addresses.ts`). A link's data, in a name's answer and a link's preview, is the service's: its type and read state, and of a profile read its names and picture, an address's peer type and business flag, and a channel's group type and member count, from which the page tells the app's kinds (contact, channel, business or bot) and a channel's subscribers; the mock makes a contact link whose fragment starts with `Biz` a business, `Bot` a bot, `Pic` one with a picture, `Off` one whose host it does not fetch (no profile, `unavailable`), and a contact or channel link whose fragment starts with `Unr` one whose data could not be read now (no profile, `unread`). A link the chat core cannot parse, as one whose key does not decode as base64url and encode back to itself, or a `simplex:/` link without `h`, is refused with `invalid_link` and left out of a name's answer. Of the service's rate limits the mock keeps the code limit: 10 code checks and code orders a minute per client, a client being the last address in `X-Forwarded-For` (as the service with `trust_forwarded_for` takes it), else the connection's; the browser tests give each test an address of its own. Vite serves the page on http://127.0.0.1:5173 and proxies `/api` and `/control` to the mock. `MIN_COMMITMENT_AGE` is the seconds a registration waits after its commit; the contracts' deploy scripts use 60. +`dev/deploy.ts` stops with an error when the chain id, the TLD, an address or a terms link it deploys differs from `LOCAL` in `src/config.ts`, as the page signs over `LOCAL`'s values. The anvil accounts deploy the contracts in a fixed order, so each fresh chain has the same addresses. + Each order's view in the mock contains the dispute days of its payment, 120 for a card and 14 for Bitcoin, Monero or a prepaid code, over which the mock checks the order's signed registration; for a name selected for a taken order, they are those of the order's payment. Once the name is registered, the view's `registered` phase contains the registrar's dispute end. -Without a Stripe key the dev server shows a stand-in card form, labelled as a test, whose Pay button acts as a submitted card; the production build never has the stand-in, and shows that the card form did not load. The page reads the key from `GET /api/config`, which the mock answers with none. To see Stripe's own form in development, make the mock's answer carry a test publishable key (`pk_test_…`, from the Stripe dashboard in test mode) and keep it out of commits; the mock's client secrets are not Stripe's, so no card can be confirmed against it: that needs the service, with the account's test secret key (`sk_test_…`). +The card form is the card page's, `card/`, on its own origin, `SITE.cardOrigin` (`http://127.0.0.1:5180` in development, `npm run dev:card`; Playwright and Docker Compose start it), which the order's page frames, so Stripe.js never runs beside the names codes' storage. The two pages talk by `postMessage`, each taking messages only from the other's origin and frame: the order's page sends `mount` (the client secret, the invoice's amount, the theme), `theme` and `confirm`; the card page answers `mounted`, `height`, `paid`, `invalid`, `declined` and `failed`. Before it mounts Stripe's form, the card page reads the PaymentIntent with its own key, `SITE.stripeKey`, and mounts nothing unless the intent has the invoice's amount, dollars, the key's mode (`SITE.stripeLive`) and the card alone; the order's page then withholds the payment's details, saying that they could not be checked. Without a Stripe key the card page's development server shows a stand-in card form, labelled as a test, whose Pay button acts as a submitted card; a production build never has the stand-in, and shows that the card form did not load. To see Stripe's own form in development, start the card page with `VITE_STRIPE_KEY` set to a test publishable key (`pk_test_…`, from the Stripe dashboard in test mode); the browser tests give the card page `pk_test_e2e` in `window.stripeTestKey`, which no production build reads. The mock's client secrets are not Stripe's, so no card can be confirmed against it: that needs the service, with the account's test secret key (`sk_test_…`). `npm run build:card` builds the card page into `dist-card/`, which its own repository deploys to `pay.simplex.domains`. ### Mock controls @@ -89,18 +91,22 @@ Tests and manual checks advance orders with `POST` requests to the mock: | `/control/credit/` `{"cents"}` | the order's balance grows by the cents, as a later credit (a late payment) grows it | | `/control/late/` `{"waiting"}` | a late payment's credit waits (`crediting`, `support`), as the view's `latePayment` then says; `null` lets it go, crediting what is confirmed | | `/control/rate` `{"btc", "xmr"}` | the coin's current rate in whole dollars; a late payment is credited at the lower of it and its invoice's rate (`null` goes back to the invoice's) | -| `/control/search` `{"chainDown", "limitSeconds", "invoiceError", "findLimitSeconds", "unsentSeconds", "unreadSeconds", "writeDelayMs", "fetchDelays"}` | the chain cannot be read, search is rate limited, the next paid order is refused (`provider_unavailable`, `rate_limited` with a wait of `MOCK_RETRY_AFTER_SECONDS`, 30 s, `catalog_changed`, `internal`; `null` clears it), finding a code's orders is rate limited, no transaction goes out for that many seconds (each is tried again every `MOCK_RESEND_MS`, 5 s, until it goes out), the registration view's own chain reads fail for that many seconds (the view names them in `unread`), every write to a registration waits that long before its check (to race two requests), or each fetch of a link's data, in a search or a preview, takes the milliseconds given for that link (`{link: ms}`, `{}` clears them; a profile that was read is kept 10 minutes and answered at once, as the service caches it, while one not read is fetched again) | +| `/control/search` `{"chainDown", "limitSeconds", "invoiceError", "findLimitSeconds", "unsentSeconds", "unreadSeconds", "writeDelayMs", "fetchDelays"}` | the chain cannot be read, search is rate limited, the next paid order is refused (`provider_unavailable`, `rate_limited` with a wait of `MOCK_RETRY_AFTER_SECONDS`, 30 s, `catalog_changed` with the name's price now, `internal`; `null` clears it), finding a code's orders is rate limited, no transaction goes out for that many seconds (each is tried again every `MOCK_RESEND_MS`, 5 s, until it goes out), the registration view's own chain reads fail for that many seconds (the view names them in `unread`), every write to a registration waits that long before its check (to race two requests), or each fetch of a link's data, in a search or a preview, takes the milliseconds given for that link (`{link: ms}`, `{}` clears them; a profile that was read is kept 10 minutes and answered at once, as the service caches it, while one not read is fetched again) | +| `/control/mismatch` `{"price", "policy", "termsHash", "method", "address", "amount"}` | answers that differ from the values the page holds, until the next call, which sets the mismatches it names and clears the others: each search answers `price` in cents, each sign answer and order view asks for the acceptance under another policy (`policy: true`) or of another terms hash (`termsHash: true`), and the next invoice, and its order's view, has another payment method than the order asked for (`method: true`), its order keeping the dispute days of the method asked for; the next invoice of the coin given in `address` (`btc` or `xmr`) has an address of another wallet, with that wallet's proof, which the page's keys do not prove, and the next invoice an amount a dollar over its name's price (`amount: true`) | | `/control/general-terms` `{"text"}` or `{"link"}` | the owner sets the name policy's general terms to the link of this text, written to `dev/terms/`, to this link as it is, or back to the deployed link with a `null` text; an order or a selection of a name signing the old terms is refused with `terms_changed`, and the buyer of an order signed under them is asked to agree again before its reveal | | `/control/community` `{"label", "for"}` | the name goes on the name policy's community list with what it is for, or comes off it with `null`; a registered name cannot be listed | | `/control/community-terms` `{"text"}` or `{"link"}` | as `/control/general-terms`, for the community terms | | `/control/edits` `{"limit"}` or `{"label", "count", "at"}` | the link edits a name gets in any 365 days, 1 to 100, as a restart with a new `[names] record_edits_per_year` would (3 at the start); or the name's counted edits, `count` of them made at `at` (unix seconds, now when left out), in place of those it has. As the service, a name with none left is refused with `409 {"type": "edit_limit", "nextAt"}` and its search answer's `found.records.edits` says when the next one returns; an edit counts once it goes out, however it ends on chain: mined, reverted or expired | | `/control/code` `{"minLength", "years", "state"}` | issues a prepaid code | | `/control/code/state` `{"code", "state"}` | sets a prepaid code's state, as an order elsewhere taking it or letting it go | -| `/control/mode` `{"mode"}` | `codes` refuses every name invoice with `403 {"error": "codes_only"}`, as the service with `[names] codes_only` on; `open`, the mock's mode at its start, takes them again. `GET /control/mode` answers it, and `GET /api/config` carries it to the page, as the service's does | +| `/control/mode` `{"mode"}` | `codes` refuses every name invoice with `403 {"error": "codes_only"}`, as the service with `[names] codes_only` on; `open`, the mock's mode at its start, takes them again. `GET /control/mode` answers it, and `GET /api/config` carries it, as the service's does; the page's own mode is its build's (Codes only) | +| `/control/downtime` `{"on"}` | the service's downtime, as a restart with `[names] downtime` on or off sets it: `GET /api/config` answers it in `names.downtime`, and a name invoice, a code order and a selection are refused with `503 {"type": "downtime"}` | | `/control/clock` `{"now"}` | the mock's clock is set to `now` (unix seconds), from where it runs on, and the chain is moved forward to it; a chain already past it is refused with `409 {"error": "chain_ahead"}`. The mock's answers carry its clock in their `Date` header | | `/control/seed` `{"seed"}` | the mock's ids, references, addresses and codes are drawn from this text from now on, the same each time, or at random again with `null` | -`GET /control/state` dumps the mock's registrations, invoices and balances. +`GET /control/state` dumps the mock's registrations, invoices and balances, and counts the order requests it answered signed and those it refused; `GET /control/invoice/` and `GET /control/registration/` answer an order's views to the tests without a signature. + +The page signs every request for an order with the order's name key, as the service asks: each read of an invoice or a registration, long polls included, a cancel, a retry and a reveal sign `simplex.domains order ` (`read`, `cancel`, `retry` or `reveal`), in the query of a `GET`, in the body of a `POST`, and in a reveal's body as `request: {timestamp, signature}` beside its reveal fields; the reveal inside a new order's `POST /api/invoice` carries none. The mock answers an unsigned request, one of another signer and one for an unknown id alike, `404 not_found`, and a timestamp outside its window `400 bad_request` before it looks the id up; the page then signs once more at the clock that answer's `Date` gave. A selection and a reveal of another signer are answered as an unknown id too: a selection whose message the order's owner did not sign, and a reveal without its order request signed by the owner. A reveal whose `RegisterName` the order's owner did not sign over its term and dispute days is refused `400 bad_request`. The order's page counts either answer to a reveal as a refusal. A browser without the order's name code sends no request for the order, and the order's link says "The name code is not in this browser" and "Please enter the name code you saved for this order." ## Test @@ -118,7 +124,7 @@ SLOTS=3 npx playwright test FIREFOX_158= SLOTS=3 npx playwright test --project=firefox158 ``` -`ulimit -c 0`, in each shell, keeps a browser or chain that crashes from leaving a core file. Slot i has its chain on port 8545+i, its deployment in `dev/local-chain-i.json` and its mock on 8099+i; Playwright starts its page server on 5173+i, or uses one already there. `SLOTS` sets the workers too (4 by default; WebKit's at most 2, as its frames are drawn on the CPU); against a single backend, such as Docker Compose's, run with `SLOTS=1`. A slot takes about 1 GB of memory with its browser. A long run grows each chain's memory, so restart `start.sh` between full runs. +`ulimit -c 0`, in each shell, keeps a browser or chain that crashes from leaving a core file. Slot i has its chain on port 8545+i, its deployment in `dev/local-chain-i.json` and its mock on 8099+i; Playwright starts its page server on 5173+i, and a codes-only page server, with `VITE_CODES_ONLY=true`, on 5273+i, or uses ones already there. `SLOTS` sets the workers too (4 by default; WebKit's at most 2, as its frames are drawn on the CPU); against a single backend, such as Docker Compose's, run with `SLOTS=1`. A slot takes about 1 GB of memory with its browser. A long run grows each chain's memory, so restart `start.sh` between full runs. `npx playwright test` runs the `chromium`, `firefox` and `webkit` projects in one pool; `--project=chromium` (or `firefox`, `webkit`) runs one browser. Where memory is short, run the three one after another. @@ -128,47 +134,89 @@ The tests run with reduced motion, so screens swap at once, except one test in ` With `SHOTS=1` the tests write every screen they reach to `screenshots/` (or `SCREENSHOTS_DIR`), on a desktop and a phone, light and dark; Firefox's and WebKit's go to `screenshots/firefox/` and `screenshots/webkit/`, WebKit's in light only. -The service worker is in the production build only, so `e2e/offline.spec.ts` runs only against it and is skipped otherwise. `vite preview` sends the Content-Security-Policy given under Hosting, from its copy in `vite.config.ts`, and a test fails on any violation a page reports. With slot 0 of the backend up, serve the build, which proxies `/api` to slot 0's mock, and point the tests at it from another shell; they then run in one worker: +The service worker is in a built page only, so `e2e/offline.spec.ts` runs only against one and is skipped otherwise. A built page holds the policy given under Hosting, which `vite.config.ts` writes into its head, and a test fails on any violation a page reports. With slot 0 of the backend up, serve a build for the dev chain, which proxies `/api` to slot 0's mock, and point the tests at it from another shell; they then run in one worker: + +``` +npx vite build --mode devchain && npx vite preview --host 127.0.0.1 +BASE_URL=http://127.0.0.1:4173 npx playwright test e2e/offline.spec.ts e2e/track.spec.ts e2e/mode-cache.spec.ts e2e/card.spec.ts e2e/pages.spec.ts +``` + +A build for an API on its own origin asks slot 0's mock directly, which answers it with CORS headers: ``` -npm run build && npx vite preview --host 127.0.0.1 -BASE_URL=http://127.0.0.1:4173 npx playwright test e2e/offline.spec.ts e2e/track.spec.ts e2e/mode-cache.spec.ts +VITE_API_ORIGIN=http://127.0.0.1:8099 npx vite build --mode devchain --outDir dist-api && npx vite preview --host 127.0.0.1 --port 4174 --outDir dist-api +API_ORIGIN=http://127.0.0.1:8099 BASE_URL=http://127.0.0.1:4174 npx playwright test e2e/pages.spec.ts ``` -`e2e/mode-cache.spec.ts` serves `dist/` itself, as the store service does, and switches its mode, slows it and stops it between loads: a reload shows the mode the service gives, however slowly it answers, and the page opens offline in the last mode it gave. Its other tests follow a page left open across the switch: back in view, restored by Back, holding a name typed and not searched, and against a service whose mode flips with every answer. In Chromium the Back test launches the full Chromium build (Playwright's `chromium` channel) with its back/forward cache on; Playwright keeps that cache off in Firefox and WebKit, where the test fires the restore's `pageshow` itself. Headless browsers keep every tab in view, so the tests fire `visibilitychange` themselves. +`npm run build` builds the production page, which holds `MAINNET`, and `test/build.test.ts` checks that it holds no `LOCAL` value; `--mode devchain` builds with `LOCAL`, as Vite reserves the mode name `local`. + +`e2e/mode-cache.spec.ts` serves `dist/` itself, with the caching headers of the host before GitHub Pages, and puts it in and out of its downtime between loads. Its tests follow a page left open across the downtime's end: back in view, restored by Back, holding a name typed and not searched, and against a service whose downtime flips with every answer. In Chromium the Back test launches the full Chromium build (Playwright's `chromium` channel) with its back/forward cache on; Playwright keeps that cache off in Firefox and WebKit, where the test fires the restore's `pageshow` itself. Headless browsers keep every tab in view, so the tests fire `visibilitychange` themselves. ### CI `.github/workflows/webapp.yml` runs on pull requests and on pushes to master that change the webapp, its fonts or images: - `unit`: `npm test` and `npm run build`. -- `e2e`, one job per browser (Chromium, Firefox, WebKit): the dev image of `dev/Dockerfile` runs `dev/start.sh` with 3 slots, 2 for WebKit, and the browser tests run against it; then the production build's tests run against `vite preview`. +- `pages`, on a push to master after `unit`: `npm run build`, and `webapp/dist` deployed to GitHub Pages (Hosting). +- `e2e`, one job per browser (Chromium, Firefox, WebKit): the dev image of `dev/Dockerfile` runs `dev/start.sh` with 3 slots, 2 for WebKit, and the browser tests run against it; then the built page's tests run against `vite preview` of a build for the dev chain, and, in the step "API on its own origin", `e2e/pages.spec.ts` against a build with `VITE_API_ORIGIN` at slot 0's mock; in the Chromium job, the step "Screens" compares the screenshots. The image's layers are cached between runs, so the contracts compile only when the Dockerfile's commits change. A failed `e2e` job prints the backend's log and uploads `test-results/`. ## Codes only -Until the full launch, names are registered only with prepaid codes. The page is the same build in both modes: it reads the mode from `GET /api/config`, which the service answers `codes` while its `[names] codes_only` is on, and `open` otherwise. The page draws nothing between its header and footer until it has the answer, which `index.html` preloads, so it never shows one mode and then the other; offline, the service worker answers with the service's last answer, and a page with neither draws in `open` mode. In `codes` mode: +Until the full launch, names are registered only with prepaid codes. The mode is the page's own, `SITE.codesOnly`, which a page release changes: `MAINNET` holds codes mode, `LOCAL` open mode, and a dev server or build with `VITE_CODES_ONLY=true` codes mode; the browser tests of codes mode run against such a server. The service's `[names] codes_only` refuses payments on its side, and its `GET /api/config` still says it, which the page does not read. In `codes` mode: - The home's search field and its button are off, greyed with a not-allowed pointer, and take no focus or Enter, until the tab holds a prepaid code; one line says names can be registered only with a code right now, and the screen's one action, Register with code, opens Check your code (`/#/code`). - With a code, the search answers a name shorter than the code covers at once, without asking the service, and Check your order has no payment choices and no Pay with ETH: the tab's code pays, or, once it is taken off, a code entered in the field that takes the choices' place. - Nothing offers a payment: a closed invoice offers no new one; refunds, Your names, restoring, link edits and order pages work as in `open` mode. -- The service answers `403 {"error": "codes_only"}` to `POST /api/invoice` for a name. A page opened before the switch meets it: Check your order then says registration is by code only for now, and a closed invoice's page says so under its button, each with a way to enter a code. The screen after it is a fresh load of the page, in codes mode. -- A page follows the service's mode while it is open (`src/views/served-mode.ts`). A load reads the mode before it draws, so the page checks it again, from `GET /api/config` past the HTTP cache, only each time the tab comes back into view, and when Back or Forward restores it from the browser's cache. When the mode differs, the page loads again at once if that loses nothing: no order or change on its way, no card form, no field typed into and not kept, no terms ticked on an order's page, a tick only the page holds, and storage holding everything the tab keeps. Otherwise it loads again at its next screen. The checkout, the tab's code and the orders are in storage, so a reload keeps them. A load checks nothing after it draws, so a service whose mode flips with every answer reloads the page at most once per return to the tab. +- The service answers `403 {"error": "codes_only"}` to `POST /api/invoice` for a name. A page of an open release meets it while the service is in codes mode: Check your order then says registration is by code only for now, and a closed invoice's page says so under its button, each with a way to enter a code. The screen after it is a fresh load of the page, which a newer release may have replaced. + +## Downtime + +A page that read the service in its downtime loads again once it reads that the downtime is over, so that a tab loaded before a page release signs with the released values (`src/views/served-mode.ts`). A load reads `GET /api/config` before it draws, and the page reads it again, past the HTTP cache, at each search, at each read of an order it follows, each time the tab comes back into view, and when Back or Forward restores it from the browser's cache. Once the downtime is over, the page loads again at once if that loses nothing: no order or change on its way, no card form, no field typed into and not kept, no terms ticked on an order's page, a tick only the page holds, and storage holding everything the tab keeps. Otherwise it loads again at its next screen. The checkout, the tab's code and the orders are in storage, so a reload keeps them. A service whose downtime flips with every answer reloads the page at most once per return to the tab. A tab that reads no answer in the whole downtime, as one hidden through it, keeps the values it loaded with: the service refuses what it signs with values the release changed, and its next load takes the released ones. + +While a value the page holds changes, the service is in its downtime (`[names] downtime`): it refuses a name invoice, a code order and a selection with `503 {"type": "downtime"}`, and answers reveals, retries, reads and cancels. While the page last read the downtime: + +- The home says "You will be able to order names again soon." under the search, and an available name's row has no Register. +- A checkout opened, or its order sent, says the same; so does a closed invoice's page when it asks for a new invoice. +- An open invoice's page shows its status without its payment details: no address, amount or QR code, and no card form unless one is mounted already; it says "You will be able to pay again soon." +- A committed order's page signs no reveal, and says that the registration is not signed yet. +- The page of an order failed while it was not read has Continue off, and says "You will be able to continue the registration soon." +- Registered orders, Your names and Check your code are as outside the downtime. ## Hosting -`npm run build` writes a static site to `dist/`. The host it is served from needs: +`npm run build` writes a static site to `dist/`, which the workflow's `pages` job deploys to GitHub Pages at `simplex.domains` on each push to master, after `unit` passes. The page asks the service at `SITE.apiOrigin`, `https://api.simplex.domains`, which answers it with CORS headers; a build for the dev chain asks its own origin, through Vite's proxy, unless `VITE_API_ORIGIN` names another, as CI's step "API on its own origin" does with the mock. GitHub Pages sends a fixed set of headers, so the page's policy is a ``, the first element of its head, that the build writes with the hashes of its inline scripts: `default-src 'self'; script-src 'self' ; frame-src ; connect-src 'self' ; img-src 'self' data:; style-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'`, with ``. A meta policy cannot forbid framing, so a page loaded in another page's frame draws only "This page can be used only in its own tab. Please open it in a new tab.", with a link to itself. GitHub Pages sends none of `Strict-Transport-Security`, `X-Content-Type-Options: nosniff` and `Cross-Origin-Opener-Policy`, which the Caddy block that served the page sent, and serves every file with `Cache-Control: max-age=600`: a release reaches a returning reader within 600 seconds, which step 6 of a held value's change waits for, and the page registers its worker past the HTTP cache. The page and its host rely on: -- `Cache-Control: public, max-age=31536000, immutable` on `/assets/*` (file names carry a content hash), `no-cache` on `index.html` and `/sw.js`, and a day or so on `/fonts/*` and `/img/*`; `no-store` on the service's `/api/*`. -- `/sw.js` served from the site's root, as JavaScript. It is the service worker `sw/plugin.ts` writes into the build: it keeps this build's shell and files in one cache per build, so the page and Your names open offline. The shell is network first, with no deadline, as it decides the build: the cached shell is served only when the network fails or the server answers an error, and each fresh shell that names this build's entry module replaces it. `GET /api/config` is network first too, each answer kept, so the page opens offline in the last mode the service gave; the build's files are cache first; the rest of `/api/*`, a request for `/` that is not a page load, other origins and anything else go to the network untouched. The page registers it in the production build only, past the HTTP cache. To take it out, serve a `sw.js` whose install deletes every cache and calls `self.registration.unregister()`. +- The repository's settings: Pages built by GitHub Actions, with the custom domain `simplex.domains` and Enforce HTTPS; the environment `github-pages` deployable from master alone; a required review on master; branches up to date before merging, so a pull request's `e2e` ran on the tree the `pages` job deploys. +- The organization's settings: `simplex.domains` verified for GitHub Pages. +- The card page's repository with the same settings and the custom domain `pay.simplex.domains`. +- File names under `/assets/` carrying a content hash; `no-store` on the service's `/api/*`. +- `/sw.js` served from the site's root, as JavaScript. It is the service worker `sw/plugin.ts` writes into the build: it keeps this build's shell and files in one cache per build, so the page and Your names open offline. The shell is network first, with no deadline, as it decides the build: the cached shell is served only when the network fails or the server answers an error, and each fresh shell that names this build's entry module replaces it. `GET /api/config`, on the page's origin or at `SITE.apiOrigin`, is network first too, each answer kept, so the page opens offline with the downtime the service last gave; the build's files are cache first; the rest of `/api/*`, a request for `/` that is not a page load, the rest of other origins and anything else go to the network untouched. The page registers it in the production build only, past the HTTP cache. To take it out, serve a `sw.js` whose install deletes every cache and calls `self.registration.unregister()`. - Brotli or gzip for HTML, JS, CSS and `favicon.ico`. - A 404 for unknown paths: the app's routes live in the hash and the query, never in the path. -- Security headers. `e2e/offline.spec.ts`, `e2e/track.spec.ts` and `e2e/paid.spec.ts` run with `BASE_URL` at `vite preview` report no violation in Chromium, Firefox and WebKit, without Stripe.js. Stripe.js loaded with a test key and a mock client secret mounts its frames with no violation in the three; a live Stripe key and 3-D Secure are still to be checked: `Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-i5ar+ITNdQiucbmin4/AN6DAY5LbAWeq3at+RiFoUoY=' 'sha256-lxURZtAGLIPkeIfIfFjl4UIJp4ElJWSbFqE1ktKB8hk=' 'sha256-djvAKNENifE9sLU9+NrLdzdGftMgCwpvCvH/MAbkElY=' https://js.stripe.com https://*.js.stripe.com; frame-src https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com; connect-src 'self' https://api.stripe.com; img-src 'self' data:; style-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'` (the hashes are index.html's inline theme, font preload and first frame scripts, and change with them), `Strict-Transport-Security: max-age=63072000; includeSubDomains`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, `Cross-Origin-Opener-Policy: same-origin-allow-popups`. -- Stripe.js runs on the page's own origin, which keeps the owner codes and prepaid codes in `localStorage`; the CSP admits scripts only from this origin and Stripe's script hosts, and the page loads Stripe.js only on the card screen. The owner accepted this on 2026-10-20, rather than a Checkout redirect or a separate card origin. -- The Stripe publishable key at `GET /api/config`, beside the mode. The service must create each PaymentIntent with `payment_method_types: ["card"]`: the page mounts the Payment Element with Apple Pay, Google Pay and Link off and keeps room for the card form alone, and a form that Stripe cannot load, or that has not loaded after 20 s, leads to the card-not-confirmed page. +- The page's own policy. `e2e/offline.spec.ts`, `e2e/track.spec.ts`, `e2e/mode-cache.spec.ts`, `e2e/card.spec.ts` and `e2e/pages.spec.ts` run with `BASE_URL` at `vite preview` of a build for the dev chain, and report no violation of its meta policy in Chromium, Firefox and WebKit, with the card page framed; a live Stripe key and 3-D Secure in the card page are still to be checked. +- Stripe.js runs only in the card page, on its own origin, away from the owner codes and prepaid codes this origin keeps in `localStorage`; the names page's CSP admits no Stripe host and frames the card page's origin alone. +- The Stripe publishable key in `SITE.stripeKey`, which the card page holds. The service must create each PaymentIntent with `payment_method_types: ["card"]`: the card page mounts the Payment Element with Apple Pay, Google Pay and Link off and keeps room for the card form alone, and a form that Stripe cannot load, or that has not loaded after 20 s, leads to the card-not-confirmed page. - `/manifest.webmanifest` as `application/manifest+json`. With the service worker it makes the site installable as an app; its icons in `img/` are rendered from the SimpleX symbol by `node dev/app-icons.mjs ../img/simplex-symbol-light.svg ../img`. +### Changing a value the page holds + +A value of `MAINNET` other than a payee key changes in the service's downtime, in this order: + +1. The operator restarts the service with `[names] downtime = on`. +2. The operator drains the queue: the worker registers the orders queued with their reveals, and the providers settle the payments in progress, until no order the service moves on is left, or for 15 minutes at most. +3. The owner and the Safe's signers change the chain: the terms by `setGeneralTerms` or `setCommunityTerms`, the prices by the price oracle. +4. The operator releases the service with the new values, still in its downtime, with the payee keys in BTCPay and the ini. +5. The owner merges the pull request of this repository with the new `MAINNET`, which the `pages` job deploys; with a new Stripe key, the card page's repository moves to that merge. Before the merge, `RPC_URL= npm run check:mainnet` reads the controller's sponsor, resolver, name policy and TLD, the price oracle's base and exceptions, and the policy's terms links and hashes, and compares them with `MAINNET`. +6. The operator restarts the service with `downtime = off`, once the `pages` jobs of step 5 have completed and 600 seconds, the `max-age` GitHub Pages serves with, have passed. +7. The page of each open order signs it again with the new values, its buyer accepting changed terms first; an order failed while its page was not read is signed again by Continue. +8. The owner moves `apps/simplex-domains` in simplex-chat to the merge of step 5. + +The service's ini holds these values too: `[names]` `term_start`, `years`, `codes_only` and `tld`; `[chain]` `chain_id` and the contract addresses; the payee keys; `[stripe] publishable_key`. A change of the resolver or the TLD changes the commitment of every open order, so the drain of step 2 runs without its cap, and support closes an order still open after it. + +A payee key changes in three steps: a page release adds the new Bitcoin key or Monero primary address to `MAINNET`; BTCPay and the service's ini switch to the new wallet; a page release removes the old key once its last invoice has expired. + ## Not decided or not built - The mock is a development fixture, not the service: it keeps everything in memory and moves no money. diff --git a/webapp/TODO.md b/webapp/TODO.md index d7df569e..fe867022 100644 --- a/webapp/TODO.md +++ b/webapp/TODO.md @@ -14,7 +14,7 @@ All screens: how each one makes people feel, the criterion the language audit ap | # | Screen | Issue | |---|---|---| -| 1 | checkout-code-no-storage | Show the public address the name is stored at, and recommend checking on Etherscan that the name landed there. The link opens the page where the person sees the name owned by their address. The private key alone is not enough. | +| 1 | checkout-code-no-storage | Done: the name address is shown beside each name code, and the registered order's page and each registered row's name code link the SimpleX Names app's page of the address, asking to check that the name is listed. | | 2 | checkout-community-accepted | The community terms shown make no sense. In the screenshots they are the dummy terms in dev/fixtures/terms/ (community-terms.md and general-terms.md), which dev/deploy.ts publishes; the deployed page shows the terms linked on chain. Make the screenshots show the real terms texts, and rewrite the community terms page where its own text is wrong. | | 3 | checkout-community-unreadable | The screen says the terms cannot be shown; find why it reaches that state, and change what the person sees. | | 4 | checkout-links-scan-dialog (phone), checkout-review-code-scan-dialog (phone) | The screenshots show no QR code; find whether the scan dialogs are broken or only the screenshots. | diff --git a/webapp/card/card.css b/webapp/card/card.css new file mode 100644 index 00000000..55a9386e --- /dev/null +++ b/webapp/card/card.css @@ -0,0 +1,11 @@ +html, body { margin: 0; padding: 0; background: transparent; } +body { font: 16px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #0D1B3A; } +html.dark body { color: #EAF2FF; } +.stand-in { padding: 18px; border: 1px dashed rgba(0, 83, 208, .14); border-radius: 16px; } +html.dark .stand-in { border-color: rgba(112, 240, 249, .18); } +.stand-in .label { margin: 0 0 4px; font-size: 14px; color: #8a5a00; } +html.dark .stand-in .label { color: #ffd38a; } +.stand-in .f { display: block; margin-top: 12px; } +.stand-in .f span { display: block; font-size: 13px; font-weight: 700; margin-bottom: 6px; opacity: .75; } +.stand-in .box { padding: 13px 14px; border-radius: 12px; border: 1px solid rgba(0, 83, 208, .14); font-weight: 600; } +.stand-in .cols { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; } diff --git a/webapp/card/index.html b/webapp/card/index.html new file mode 100644 index 00000000..04b5616d --- /dev/null +++ b/webapp/card/index.html @@ -0,0 +1,14 @@ + + + + + + +SimpleX names: card form + + + + +
+ + diff --git a/webapp/card/main.ts b/webapp/card/main.ts new file mode 100644 index 00000000..a29618b1 --- /dev/null +++ b/webapp/card/main.ts @@ -0,0 +1,88 @@ +import { SITE } from "../src/config.ts" +import { type FromCard, type MountedCard, mountCard, type Theme, type ToCard, MISMATCHED } from "../src/stripe.ts" + +declare const __MAINNET__: boolean +declare global { + interface Window { stripeTestKey?: string } +} + +const STAND_IN = "Test card form: no Stripe key is set, so Pay simulates a payment." +const form = document.getElementById("form")! +const fromPage = (origin: string) => SITE.pageOrigins.some((page) => origin === page || (!(typeof __MAINNET__ !== "undefined" && __MAINNET__) && origin.startsWith(`${page}:`))) +const keyOf = () => SITE.stripeKey || (typeof __MAINNET__ !== "undefined" && __MAINNET__ ? "" : window.stripeTestKey ?? "") + +let page: string | null = null +let card: MountedCard | null = null +let dark = false +const followers = new Set<(dark: boolean) => void>() +const theme: Theme = { + dark: () => dark, + watch: (follow) => { + followers.add(follow) + return () => { followers.delete(follow) } + }, +} + +const send = (message: FromCard) => { if (page) parent.postMessage(message, page) } + +function shade(next: boolean): void { + dark = next + document.documentElement.classList.toggle("dark", dark) + document.documentElement.style.colorScheme = dark ? "dark" : "light" + for (const follow of followers) follow(dark) +} + +function standIn(): MountedCard { + const field = (text: string, value: string) => { + const label = document.createElement("label") + label.className = "f" + label.append(Object.assign(document.createElement("span"), { textContent: text }), Object.assign(document.createElement("div"), { className: "box", textContent: value })) + return label + } + const cols = Object.assign(document.createElement("div"), { className: "cols" }) + cols.append(field("Expiry", "12 / 30"), field("CVC", "123"), field("Country", "Portugal")) + const box = Object.assign(document.createElement("div"), { className: "stand-in" }) + box.append(Object.assign(document.createElement("p"), { className: "label", textContent: STAND_IN }), field("Card number", "4242 4242 4242 4242"), cols) + form.append(box) + return { confirm: async () => ({ kind: "submitted", id: "pi_stand_in" }), destroy: () => box.remove() } +} + +async function mount(clientSecret: string, amount: number): Promise { + const key = keyOf() + if (!key) { + if (!import.meta.env.DEV) return send({ type: "failed", reason: "unloaded" }) + card = standIn() + return send({ type: "mounted" }) + } + const mounted = await mountCard(key, clientSecret, { amount, currency: SITE.currency, live: SITE.stripeLive }, form, theme) + if (mounted === null || mounted === MISMATCHED) return send({ type: "failed", reason: mounted ?? "unloaded" }) + card = mounted + send({ type: "mounted" }) +} + +async function confirm(): Promise { + if (!card) return + const outcome = await card.confirm() + send(outcome.kind === "submitted" ? { type: "paid", id: outcome.id } : outcome.kind === "invalid" ? { type: "invalid" } : { type: "declined", message: outcome.message }) +} + +const isToCard = (m: unknown): m is ToCard => typeof m === "object" && m !== null && "type" in m && ( + (m.type === "mount" && "clientSecret" in m && typeof m.clientSecret === "string" && "amount" in m && Number.isInteger(m.amount) && "dark" in m && typeof m.dark === "boolean") + || (m.type === "theme" && "dark" in m && typeof m.dark === "boolean") || m.type === "confirm") + +addEventListener("message", (e: MessageEvent) => { + const m = e.data + if (e.source !== parent || !fromPage(e.origin) || !isToCard(m)) return + if (m.type === "mount") { + if (page !== null) return + page = e.origin + shade(m.dark) + void mount(m.clientSecret, m.amount) + return + } + if (e.origin !== page) return + if (m.type === "theme") shade(m.dark) + else void confirm() +}) + +new ResizeObserver(() => send({ type: "height", px: Math.ceil(form.getBoundingClientRect().height) })).observe(form) diff --git a/webapp/card/vite.config.ts b/webapp/card/vite.config.ts new file mode 100644 index 00000000..f7dbba24 --- /dev/null +++ b/webapp/card/vite.config.ts @@ -0,0 +1,14 @@ +import { fileURLToPath } from "node:url" +import { defineConfig } from "vite" +import { LOCAL } from "../src/config.ts" + +const PORT = Number(new URL(LOCAL.cardOrigin).port) + +export default defineConfig(({ mode }) => ({ + root: fileURLToPath(new URL(".", import.meta.url)), + envDir: fileURLToPath(new URL("..", import.meta.url)), + define: { __MAINNET__: JSON.stringify(mode === "production") }, + server: { host: "127.0.0.1", port: PORT, strictPort: true }, + preview: { host: "127.0.0.1", port: PORT, strictPort: true }, + build: { target: "es2022", outDir: fileURLToPath(new URL("../dist-card", import.meta.url)), emptyOutDir: true }, +})) diff --git a/webapp/compose.yaml b/webapp/compose.yaml index 14749c7f..3b10ccc1 100644 --- a/webapp/compose.yaml +++ b/webapp/compose.yaml @@ -1,7 +1,7 @@ # The names webapp with everything it needs, on a fresh local chain at each start: # docker compose up --build then open http://localhost:5173 (the chain deploys in about 2 minutes) # The page's source is mounted, so it follows the host's files; the mock and the production build need --build. -# docker compose --profile prod up --build preview the production build on http://localhost:4173 +# docker compose --profile prod up --build preview the dev chain's build on http://localhost:4173 # The mock's controls (README) are on http://localhost:8099/control/..., the chain's RPC on http://localhost:8545, and the # terms' texts, which the page links, on http://localhost:8098. # Open the page on localhost: plain http on another address is no secure context, and the page's crypto needs one. @@ -44,10 +44,20 @@ services: depends_on: backend: { condition: service_healthy } + card: + <<: *app + command: npx vite --config card/vite.config.ts --host 0.0.0.0 + environment: + CHOKIDAR_USEPOLLING: "1" + volumes: + - ./src:/repo/webapp/src:ro + - ./card:/repo/webapp/card:ro + ports: ["127.0.0.1:5180:5180"] + preview: <<: *app profiles: [prod] - command: sh -c "npm run build && npx vite preview --host 0.0.0.0" + command: sh -c "npx vite build --mode devchain && npx vite preview --host 0.0.0.0" environment: MOCK_URL: http://backend:8099 ports: ["127.0.0.1:4173:4173"] diff --git a/webapp/dev/check-mainnet.ts b/webapp/dev/check-mainnet.ts new file mode 100644 index 00000000..6b3f0c14 --- /dev/null +++ b/webapp/dev/check-mainnet.ts @@ -0,0 +1,65 @@ +import { createPublicClient, getAddress, http, keccak256, parseAbi, toHex, type Hex } from "viem" +import { mainnet } from "viem/chains" +import { type Deployment, MAINNET, type PriceException } from "../src/config.ts" + +const RPC_URL = process.env.RPC_URL +if (!RPC_URL) throw new Error("set RPC_URL to an Ethereum mainnet RPC") + +const client = createPublicClient({ chain: mainnet, transport: http(RPC_URL) }) +const SPONSOR = parseAbi(["function controller() view returns (address)"]) +const CONTROLLER = parseAbi([ + "function sponsor() view returns (address)", + "function defaultResolver() view returns (address)", + "function namePolicy() view returns (address)", + "function tldSuffix() view returns (string)", + "function prices() view returns (address)", +]) +const ORACLE = parseAbi([ + "struct LabelPrice { uint256 labelLength; uint256 priceCentsPerYear; }", + "function prices() view returns (uint256 base, LabelPrice[] exceptions)", +]) +const POLICY = parseAbi([ + "function generalTermsLink() view returns (string)", + "function generalTermsHash() view returns (bytes32)", + "function communityTermsLink() view returns (string)", + "function communityTermsHash() view returns (bytes32)", +]) + +const controller = await client.readContract({ address: getAddress(MAINNET.sponsor), abi: SPONSOR, functionName: "controller" }) +const [chainId, sponsor, resolver, namePolicy, tldSuffix, oracle] = await Promise.all([ + client.getChainId(), + client.readContract({ address: controller, abi: CONTROLLER, functionName: "sponsor" }), + client.readContract({ address: controller, abi: CONTROLLER, functionName: "defaultResolver" }), + client.readContract({ address: controller, abi: CONTROLLER, functionName: "namePolicy" }), + client.readContract({ address: controller, abi: CONTROLLER, functionName: "tldSuffix" }), + client.readContract({ address: controller, abi: CONTROLLER, functionName: "prices" }), +]) +const [base, exceptions] = await client.readContract({ address: oracle, abi: ORACLE, functionName: "prices" }) +const [generalLink, generalHash, communityLink, communityHash] = await Promise.all([ + client.readContract({ address: namePolicy, abi: POLICY, functionName: "generalTermsLink" }), + client.readContract({ address: namePolicy, abi: POLICY, functionName: "generalTermsHash" }), + client.readContract({ address: namePolicy, abi: POLICY, functionName: "communityTermsLink" }), + client.readContract({ address: namePolicy, abi: POLICY, functionName: "communityTermsHash" }), +]) +const general = { link: generalLink, hash: generalHash } +const community = { link: communityLink, hash: communityHash } + +const priced = (list: readonly PriceException[]) => JSON.stringify([...list].sort((a, b) => a.labelLength - b.labelLength)) +const chainTermsHeld = (held: Deployment["generalTerms"], terms: { link: string; hash: Hex }) => + keccak256(toHex(terms.link)) === terms.hash && held.some((t) => t.link === terms.link && t.hash.toLowerCase() === terms.hash.toLowerCase()) + +const checks: [string, unknown, unknown][] = [ + ["chain id", chainId, MAINNET.chainId], + ["sponsor", sponsor, getAddress(MAINNET.sponsor)], + ["resolver", resolver, getAddress(MAINNET.resolver)], + ["name policy", namePolicy, getAddress(MAINNET.namePolicy)], + ["TLD", tldSuffix, `.${MAINNET.tld}`], + ["base price", base, BigInt(MAINNET.priceBaseCentsPerYear)], + ["price exceptions", priced(exceptions.map((e) => ({ labelLength: Number(e.labelLength), centsPerYear: Number(e.priceCentsPerYear) }))), priced(MAINNET.priceExceptions)], + [`general terms ${general.link} ${general.hash}`, chainTermsHeld(MAINNET.generalTerms, general), true], + [`community terms ${community.link} ${community.hash}`, chainTermsHeld(MAINNET.communityTerms, community), true], +] +const differs = checks.filter(([, chain, held]) => chain !== held) +for (const [what, chain, held] of differs) console.error(`${what}: the chain has ${String(chain)}, MAINNET ${String(held)}`) +if (differs.length) process.exit(1) +console.log(`MAINNET matches chain ${chainId}: controller ${controller}, sponsor ${sponsor}, resolver ${resolver}, name policy ${namePolicy}, price oracle ${oracle}`) diff --git a/webapp/dev/deploy.ts b/webapp/dev/deploy.ts index 9a426886..ee87478c 100644 --- a/webapp/dev/deploy.ts +++ b/webapp/dev/deploy.ts @@ -8,6 +8,7 @@ import { } from "viem" import { mnemonicToAccount, privateKeyToAccount } from "viem/accounts" import { foundry } from "viem/chains" +import { LOCAL } from "../src/config.ts" import { durationFor } from "../src/crypto/registration.ts" import { BLOCK_POLL_MS, TERM_START_S, untilChainTime } from "./chain-time.ts" import { registerNameTypedData } from "./register-name.ts" @@ -27,8 +28,8 @@ const MAX_LABEL_LENGTH = 63n const FEED_DECIMALS = 8 const FEED_PRICE = 100_000_000n // the launch prices in cents a year (owner, 2026-10-21): $100, $200 and $400 for 2 years at 8 or more, 7 and 6 letters -const PRICE_BASE = 5000n -const PRICE_EXCEPTIONS = [{ labelLength: 7n, priceCentsPerYear: 10000n }, { labelLength: 6n, priceCentsPerYear: 20000n }] +const PRICE_BASE = BigInt(LOCAL.priceBaseCentsPerYear) +const PRICE_EXCEPTIONS = LOCAL.priceExceptions.map((e) => ({ labelLength: BigInt(e.labelLength), priceCentsPerYear: BigInt(e.centsPerYear) })) // the seeded names are registered as a paid order is, for paid years from the term start const SEED_YEARS = 2 const SEED_DISPUTE_DAYS = 120n @@ -116,6 +117,12 @@ await write(owner, namePolicy, "setCommunityTerms", [COMMUNITY_TERMS_LINK]) await write(owner, namePolicy, "addCommunityNames", [COMMUNITY_NAMES]) const chainId = await publicClient.getChainId() +const differs = ([ + ["chainId", chainId, LOCAL.chainId], ["tld", TLD, LOCAL.tld], ["sponsor", sponsor.address, LOCAL.sponsor], ["resolver", resolver.address, LOCAL.resolver], + ["namePolicy", namePolicy.address, LOCAL.namePolicy], ["baseRegistrar", baseRegistrar.address, LOCAL.baseRegistrar], ["general terms", GENERAL_TERMS_LINK, LOCAL.generalTerms[0].link], + ["community terms", COMMUNITY_TERMS_LINK, LOCAL.communityTerms[0].link], +] as const).filter(([, deployed, held]) => deployed !== held) +if (differs.length) throw new Error(`the deployment differs from LOCAL in src/config.ts: ${differs.map(([what, deployed, held]) => `${what} ${deployed}, not ${held}`).join("; ")}`) const holderAccount = privateKeyToAccount(holderKey) // A name registered to the holder through the sponsor, as the store's service registers names. diff --git a/webapp/dev/mock.ts b/webapp/dev/mock.ts index 95602116..6d1886c3 100644 --- a/webapp/dev/mock.ts +++ b/webapp/dev/mock.ts @@ -3,8 +3,8 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht import { isIP } from "node:net" import { takeCodeToken } from "./mock/limits.ts" import { - cancelInvoice, checkCode, controlClock, controlCommunity, controlCommunityTerms, controlCredit, controlEdits, controlGeneralTerms, controlInvoice, controlLate, controlMode, controlRate, controlRefund, controlRegistration, controlSearch, controlSeed, controlTake, controlUnregister, createInvoice, currentTerms, dump, editRecords, find, findLimited, - HttpError, issueCode, modeNow, oneOrderAtATime, setCodeState, previewLink, readInvoice, readRegistration, registerWithCode, retry, reveal, search, selectName, signFor, siteConfig, + cancelInvoice, checkCode, controlClock, controlCommunity, controlCommunityTerms, controlCredit, controlDowntime, controlEdits, controlGeneralTerms, controlInvoice, controlLate, controlMismatch, controlMode, controlRate, controlRefund, controlRegistration, controlSearch, controlSeed, controlTake, controlUnregister, createInvoice, currentTerms, dump, editRecords, find, findLimited, + HttpError, invoiceOf, issueCode, modeNow, oneOrderAtATime, setCodeState, previewLink, readInvoice, readRegistration, registerWithCode, registrationOf, retry, reveal, search, selectName, signFor, siteConfig, } from "./mock/service.ts" const PORT = Number(process.env.MOCK_PORT ?? "8099") @@ -15,6 +15,7 @@ const KEEP_ALIVE_MS = 75_000 // a seenVersion that is not a whole number is no version, so the poll answers at once const versionOf = (q: URLSearchParams) => /^\d+$/.test(q.get("seenVersion") ?? "") ? Number(q.get("seenVersion")) : null +const querySignature = (q: URLSearchParams) => ({ timestamp: /^\d+$/.test(q.get("timestamp") ?? "") ? Number(q.get("timestamp")) : q.get("timestamp"), signature: q.get("signature") }) // A client is the last address in X-Forwarded-For, as the service with trust_forwarded_for takes it, else the peer. function clientOf(req: IncomingMessage): string { @@ -38,15 +39,17 @@ const routes: [string, RegExp, Handler, Limit?][] = [ ["GET", /^\/api\/terms\/([^/]+)$/, (m) => currentTerms(m[1])], ["POST", /^\/api\/code\/check$/, (_, b) => checkCode(b), codeLimited], ["POST", /^\/api\/invoice$/, (_, b) => oneOrderAtATime(() => createInvoice(b))], - ["GET", /^\/api\/invoice\/([^/]+)$/, (m, _, q) => readInvoice(m[1], q.get("wait"), versionOf(q), q.get("seenPaid"), q.get("seenFull") === "1")], - ["POST", /^\/api\/invoice\/([^/]+)\/cancel$/, (m) => cancelInvoice(m[1])], + ["GET", /^\/api\/invoice\/([^/]+)$/, (m, _, q) => readInvoice(m[1], querySignature(q), q.get("wait"), versionOf(q), q.get("seenPaid"), q.get("seenFull") === "1")], + ["POST", /^\/api\/invoice\/([^/]+)\/cancel$/, (m, b) => cancelInvoice(m[1], b)], + ["GET", /^\/control\/invoice\/([^/]+)$/, (m) => invoiceOf(m[1])], + ["GET", /^\/control\/registration\/([^/]+)$/, (m) => registrationOf(m[1])], ["POST", /^\/api\/name\/register$/, (_, b) => oneOrderAtATime(() => registerWithCode(b)), codeLimited], ["POST", /^\/api\/name\/records$/, (_, b) => editRecords(b)], ["POST", /^\/api\/registration\/find$/, (_, b) => find(b), findLimited], - ["GET", /^\/api\/registration\/([^/]+)$/, (m, _, q) => readRegistration(m[1], versionOf(q))], + ["GET", /^\/api\/registration\/([^/]+)$/, (m, _, q) => readRegistration(m[1], querySignature(q), versionOf(q))], ["POST", /^\/api\/registration\/([^/]+)\/reveal$/, (m, b) => reveal(m[1], b)], ["POST", /^\/api\/registration\/([^/]+)\/name$/, (m, b) => oneOrderAtATime(() => selectName(m[1], b))], - ["POST", /^\/api\/registration\/([^/]+)\/retry$/, (m) => retry(m[1])], + ["POST", /^\/api\/registration\/([^/]+)\/retry$/, (m, b) => retry(m[1], b)], ["POST", /^\/control\/(settle|partial|confirming|expire|overdue)\/([^/]+)$/, (m, b) => controlInvoice(m[1], m[2], b)], ["POST", /^\/control\/(fail|stale|unread|lapse)\/([^/]+)$/, (m) => controlRegistration(m[1], m[2])], ["POST", /^\/control\/unregister\/([^/]+)$/, (m) => controlUnregister(m[1])], @@ -56,8 +59,10 @@ const routes: [string, RegExp, Handler, Limit?][] = [ ["POST", /^\/control\/refund\/([^/]+)$/, (m, b) => controlRefund(m[1], b.cents)], ["POST", /^\/control\/rate$/, (_, b) => controlRate(b)], ["POST", /^\/control\/search$/, (_, b) => controlSearch(b)], + ["POST", /^\/control\/mismatch$/, (_, b) => controlMismatch(b)], ["POST", /^\/control\/general-terms$/, (_, b) => controlGeneralTerms(b)], ["POST", /^\/control\/mode$/, (_, b) => controlMode(b)], + ["POST", /^\/control\/downtime$/, (_, b) => controlDowntime(b)], ["GET", /^\/control\/mode$/, () => modeNow()], ["GET", /^\/api\/config$/, () => siteConfig()], ["POST", /^\/control\/community$/, (_, b) => controlCommunity(b)], @@ -87,6 +92,9 @@ async function readBody(req: IncomingMessage): Promise> } } +const CORS = { "access-control-allow-origin": "*", "access-control-expose-headers": "*" } +const PREFLIGHT = { "access-control-allow-origin": "*", "access-control-allow-methods": "GET, POST, OPTIONS", "access-control-allow-headers": "*", "access-control-max-age": "86400" } + function reply(res: ServerResponse, status: number, body: unknown, retryAfter: number | null = null): void { res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", date: new Date().toUTCString(), ...(retryAfter ? { "retry-after": String(retryAfter) } : {}) }) res.end(JSON.stringify(body, (_, v) => (typeof v === "bigint" ? v.toString() : v))) @@ -98,6 +106,10 @@ function refused(res: ServerResponse, e: HttpError): void { const server = createServer(async (req, res) => { const url = new URL(req.url ?? "/", "http://mock") + if (url.pathname.startsWith("/api/")) { + if (req.method === "OPTIONS") return void res.writeHead(200, PREFLIGHT).end() + for (const [name, value] of Object.entries(CORS)) res.setHeader(name, value) + } const route = routes.find(([method, path]) => method === req.method && path.test(url.pathname)) if (!route) return reply(res, 404, { type: "not_found" }) try { diff --git a/webapp/dev/mock/addresses.ts b/webapp/dev/mock/addresses.ts index ea252227..8dff9d0a 100644 --- a/webapp/dev/mock/addresses.ts +++ b/webapp/dev/mock/addresses.ts @@ -1,90 +1,66 @@ -// Each invoice its own address, as BTCPay gives one: a Bitcoin regtest or a Monero stagenet address with a valid checksum, -// so a wallet on those test networks takes it, derived from the invoice id and payable by nobody here. +// Each invoice its own address, as the service gives one, with the proof the page checks it by: derived from the dev keys +// of the store service's recorded fixtures (simplex-chat tests/fixtures/store-service/rest-api/deployment.json), which +// LOCAL in src/config.ts holds. import { createHash } from "node:crypto" import { ed25519 } from "@noble/curves/ed25519" +import { bytesToNumberLE, numberToBytesBE, numberToBytesLE } from "@noble/curves/utils" +import { hmac } from "@noble/hashes/hmac" +import { sha256, sha512 } from "@noble/hashes/sha2" import { keccak_256 } from "@noble/hashes/sha3" +import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from "@noble/hashes/utils" +import { base58xmr } from "@scure/base" +import { HDKey } from "@scure/bip32" +import type { AddressProof } from "../../src/api.ts" +import { hashToScalar, moneroKeys, p2wpkh } from "../../src/crypto/payees.ts" -// BIP-173: the regtest prefix, and bech32's alphabet and checksum generator -const REGTEST_HRP = "bcrt" -const WITNESS_V0 = 0 -const BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" -const BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] -const P2WPKH_BYTES = 20 - -function polymod(values: number[]): number { - let chk = 1 - for (const v of values) { - const top = chk >>> 25 - chk = ((chk & 0x1ffffff) << 5) ^ v - BECH32_GENERATOR.forEach((g, i) => { if ((top >>> i) & 1) chk ^= g }) - } - return chk -} - -const hrpExpand = (hrp: string) => [...[...hrp].map((c) => c.charCodeAt(0) >>> 5), 0, ...[...hrp].map((c) => c.charCodeAt(0) & 31)] - -function toFiveBits(bytes: Uint8Array): number[] { - const out: number[] = [] - let acc = 0 - let bits = 0 - for (const b of bytes) { - acc = (acc << 8) | b - bits += 8 - while (bits >= 5) { - bits -= 5 - out.push((acc >>> bits) & 31) - } - } - if (bits > 0) out.push((acc << (5 - bits)) & 31) - return out -} - -function regtestAddress(program: Uint8Array): string { - const data = [WITNESS_V0, ...toFiveBits(program)] - const mod = polymod([...hrpExpand(REGTEST_HRP), ...data, 0, 0, 0, 0, 0, 0]) ^ 1 - const checksum = Array.from({ length: 6 }, (_, i) => (mod >>> (5 * (5 - i))) & 31) - return `${REGTEST_HRP}1${[...data, ...checksum].map((v) => BECH32[v]).join("")}` -} - -// Monero's stagenet standard address: network byte 24, the public spend and view keys, and 4 bytes of keccak-256 checksum, -// in Monero's base58, which encodes each 8-byte block alone -const STAGENET_STANDARD = 24 -const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" -const FULL_BLOCK = 8 -// the characters a block of n bytes takes -const BLOCK_CHARS = [0, 2, 3, 5, 6, 7, 9, 10, 11] +export const DEV_XPUB = "tpubDC8msFGeGuwnKG9Upg7DM2b4DaRqg3CUZa5g8v2SRQ6K4NSkxUgd7HsL2XVWbVm39yBA4LAxysQAm397zwQSQoQgewGiYZqrA9DsP4zbQ1M" +export const TESTNET_VERSIONS = { private: 0x04358394, public: 0x043587cf } +const DEV_HRP = "bcrt" +export const DEV_MONERO_PRIMARY = "52jzuBBUMty3xPL3JsQxGP74LDuV6E1LS8Zda1PbdqQjGzFmH6N9ep9McbFKMALujVT9S5mKpbEgC5VPhfoAiVj8LdAqbp6" +const DEV_VIEW_KEY = hexToBytes("fd5c0d25f8f994268079a4f7844274dc870a7c2b88fbfc24ba318375e1d9430f") +const STAGENET_SUBADDRESS = 36 +const INDEX_BYTES = 4 +const KEY_BYTES = 32 const CHECKSUM_BYTES = 4 +const NON_HARDENED = 2 ** 31 +const G = ed25519.Point.BASE -function base58Block(block: Uint8Array): string { - let n = block.reduce((acc, b) => acc * 256n + BigInt(b), 0n) - let text = "" - for (let i = 0; i < BLOCK_CHARS[block.length]; i++) { - text = BASE58[Number(n % 58n)] + text - n /= 58n - } - return text -} +type BitcoinProof = Extract +type MoneroProof = Extract +export interface Payee

{ address: string; addressProof: P } -function moneroBase58(bytes: Uint8Array): string { - let text = "" - for (let at = 0; at < bytes.length; at += FULL_BLOCK) text += base58Block(bytes.slice(at, at + FULL_BLOCK)) - return text +export function bitcoinPayee(branch: HDKey, hrp: string, index: number): Payee { + const il = hmac(sha512, branch.chainCode!, concatBytes(branch.publicKey!, numberToBytesBE(index, INDEX_BYTES))).slice(0, KEY_BYTES) + return { address: p2wpkh(hrp, branch.deriveChild(index).publicKey!), addressProof: { type: "btc", keyTweak: bytesToHex(il) } } } -// a private key is a scalar below the group order; its public key is that multiple of the base point -function publicKey(seed: Uint8Array): Uint8Array { - const scalar = seed.reduceRight((acc, b) => acc * 256n + BigInt(b), 0n) % ed25519.Point.Fn.ORDER - return ed25519.Point.BASE.multiply(scalar).toBytes() +export const devReceiving = HDKey.fromExtendedKey(DEV_XPUB, TESTNET_VERSIONS).deriveChild(0) +const otherReceiving = HDKey.fromMasterSeed(sha256(utf8ToBytes("another Bitcoin wallet")), TESTNET_VERSIONS).deriveChild(0) + +const scalarHex = (v: bigint) => bytesToHex(numberToBytesLE(v, KEY_BYTES)) +interface MoneroWallet { spendKey: typeof G; viewKey: Uint8Array } +const devWallet: MoneroWallet = { spendKey: ed25519.Point.fromBytes(moneroKeys(DEV_MONERO_PRIMARY)!.spend), viewKey: DEV_VIEW_KEY } +const otherMonero: MoneroWallet = { + spendKey: G.multiply(hashToScalar(utf8ToBytes("another Monero wallet's spend key"))), + viewKey: numberToBytesLE(hashToScalar(utf8ToBytes("another Monero wallet's view key")), KEY_BYTES), } -function stagenetAddress(seed: Uint8Array): string { - const spend = publicKey(seed.slice(0, 32)) - const view = publicKey(keccak_256(seed.slice(0, 32))) - const body = new Uint8Array([STAGENET_STANDARD, ...spend, ...view]) - return moneroBase58(new Uint8Array([...body, ...keccak_256(body).slice(0, CHECKSUM_BYTES)])) +export function moneroPayee(account: number, index: number, { spendKey, viewKey } = devWallet): Payee { + const viewSecret = bytesToNumberLE(viewKey) + const m = hashToScalar(utf8ToBytes("SubAddr\0"), viewKey, numberToBytesLE(account, INDEX_BYTES), numberToBytesLE(index, INDEX_BYTES)) + const D = spendKey.add(G.multiply(m)) + const C = D.multiply(viewSecret) + const k = hashToScalar(utf8ToBytes("simplex.domains view proof nonce"), viewKey, D.toBytes()) + const c = hashToScalar(utf8ToBytes("simplex.domains view proof"), G.multiply(viewSecret).toBytes(), D.toBytes(), C.toBytes(), G.multiply(k).toBytes(), D.multiply(k).toBytes()) + const s = ed25519.Point.Fn.create(k - c * viewSecret) + const body = concatBytes(new Uint8Array([STAGENET_SUBADDRESS]), D.toBytes(), C.toBytes()) + return { + address: base58xmr.encode(concatBytes(body, keccak_256(body).slice(0, CHECKSUM_BYTES))), + addressProof: { type: "xmr", spendTweak: scalarHex(m), viewProof: { challenge: scalarHex(c), response: scalarHex(s) } }, + } } -export function addressFor(method: "btc" | "xmr", invoiceId: string): string { - const seed = createHash("sha512").update(`${method} ${invoiceId}`).digest() - return method === "btc" ? regtestAddress(seed.subarray(0, P2WPKH_BYTES)) : stagenetAddress(seed) +export function payeeFor(method: "btc" | "xmr", invoiceId: string, otherWallet = false): Payee { + const index = createHash("sha256").update(invoiceId).digest().readUInt32BE(0) % (NON_HARDENED - 1) + 1 + return method === "btc" ? bitcoinPayee(otherWallet ? otherReceiving : devReceiving, DEV_HRP, index) : moneroPayee(0, index, otherWallet ? otherMonero : devWallet) } diff --git a/webapp/dev/mock/service.ts b/webapp/dev/mock/service.ts index 1ecddece..cdd98c7f 100644 --- a/webapp/dev/mock/service.ts +++ b/webapp/dev/mock/service.ts @@ -2,14 +2,13 @@ // A development fixture: memory only, no money, and not a specification of the real service. import { createHash } from "node:crypto" import { - encodeFunctionData, getAddress, hashTypedData, isAddress, keccak256, namehash, recoverAddress, recoverMessageAddress, recoverTypedDataAddress, toHex, + encodeFunctionData, getAddress, hashTypedData, isAddress, isHex, keccak256, namehash, recoverAddress, recoverMessageAddress, recoverTypedDataAddress, toHex, zeroHash, type Address, type Hex, } from "viem" import { communityAgreed, type FailReason, type Preview, signedHash, termsLink } from "../../src/api.ts" -import type { NamesSite } from "../../src/config.ts" import { codeHash, parseNameCode } from "../../src/crypto/code.ts" import { CHANNEL_KEY, CONTACT_KEY, durationFor, YEAR_S } from "../../src/crypto/registration.ts" -import { CODES_ONLY, type Mode } from "../../src/mode.ts" +import { CODES_ONLY } from "../../src/mode.ts" import { labelProblem, LINK_MAX_BYTES, linkKind, type LinkKind, linkProblem, MAX_LABEL_LENGTH, MIN_LABEL_LENGTH } from "../../src/names.ts" import { baseRegistrar, chainNow, contractsOwner, controller, deployment, holder, mined, moveChainTo, namePolicy, NotSent, ownerOf, read, registry, resolver, Reverted, send, sponsor, @@ -17,7 +16,7 @@ import { import { TERM_START_S, untilChainTime } from "../chain-time.ts" import { registerNameTypedData } from "../register-name.ts" import { savedTerms } from "../serve-terms.ts" -import { addressFor } from "./addresses.ts" +import { type Payee, payeeFor } from "./addresses.ts" import { setClock } from "./clock.ts" import { coreLink, deepLinkOf } from "./links.ts" import { randomBytes, seedRandom } from "./random.ts" @@ -138,6 +137,7 @@ interface Invoice { // what a credit of confirmed late money waits on, set by the tests: the service's next pass, or support lateWait: "crediting" | "support" | null closedBy: "expired" | "cancelled" | null + payee: Payee | null } // An order's balance, in cents. @@ -169,14 +169,18 @@ const taking = new Map>() // a fetch of a link in fetchDelays takes that many milliseconds; // a late payment is credited at the lower of its invoice's rate and the coin's current rate in cents, when one is set; // in codes mode, as the service's [names] codes_only, names are registered only with prepaid codes -const control: { mode: Mode; chainDown: boolean; limitedUntil: number; invoiceError: string | null; findLimitedUntil: number; unsentUntil: number; unreadUntil: number; writeDelayMs: number; fetchDelays: Record; rates: Record } = - { mode: "open", chainDown: false, limitedUntil: 0, invoiceError: null, findLimitedUntil: 0, unsentUntil: 0, unreadUntil: 0, writeDelayMs: 0, fetchDelays: {}, rates: { btc: null, xmr: null } } +const control: { mode: "open" | "codes"; downtime: boolean; chainDown: boolean; limitedUntil: number; invoiceError: string | null; findLimitedUntil: number; unsentUntil: number; unreadUntil: number; writeDelayMs: number; fetchDelays: Record; rates: Record } = + { mode: "open", downtime: false, chainDown: false, limitedUntil: 0, invoiceError: null, findLimitedUntil: 0, unsentUntil: 0, unreadUntil: 0, writeDelayMs: 0, fetchDelays: {}, rates: { btc: null, xmr: null } } const sendTx: typeof send = (...args) => Date.now() < control.unsentUntil ? Promise.reject(new NotSent()) : send(...args) +const mismatch: { price: number | null; policy: boolean; termsHash: boolean; method: boolean; address: Coin | null; amount: boolean } = + { price: null, policy: false, termsHash: false, method: false, address: null, amount: false } +const OTHER_METHOD: Record = { card: "btc", btc: "xmr", xmr: "btc" } +const OTHER_AMOUNT_CENTS = 100 +const OTHER_TERMS_HASH = keccak256(toHex("other terms")) + const INVOICE_ERRORS: Record = { provider_unavailable: 503, rate_limited: 429, catalog_changed: 409, internal: 500 } -// the raised price an injected catalog_changed reports, in cents -const RAISED_PRICE_CENTS = 5000 const RETRY_AFTER_SECONDS = wholeEnv("MOCK_RETRY_AFTER_SECONDS", 30) export class HttpError extends Error { @@ -359,7 +363,7 @@ async function answerFor(hash: Hex, length: number, terms: Terms | null, listed: const years = listed ? COMMUNITY_YEARS : YEARS const price = await priceOf(length, years).catch(unavailable) const readable = terms && await termsText(terms).catch(() => null) !== null ? terms : null - return { type: "available", price, years, ...readable ? { terms: readable } : {} } + return { type: "available", price: mismatch.price ?? price, years, ...readable ? { terms: readable } : {} } } const registered = { type: "registered", owner: found.owner, resolver: found.resolver, expiresAt: found.expires, gracePeriod: found.grace } // Records are read only from the store's own resolver: calling whatever contract a name points at would let anyone @@ -442,7 +446,10 @@ async function acceptanceOf(reg: Pick): Pro const { listed, terms } = await nameTerms(reg.labelHash) // before the policy has these terms there are none to accept: the view reads unread, and a reveal waits if (!terms) throw new Error("the name policy has not set these terms yet") - return { community: listed, policy: deployment.namePolicy, termsHash: terms.hash, nonce: Number(await read(namePolicy, "nonces", [reg.owner])) } + return { + community: listed, policy: mismatch.policy ? deployment.sponsor : deployment.namePolicy, termsHash: mismatch.termsHash ? OTHER_TERMS_HASH : terms.hash, + nonce: Number(await read(namePolicy, "nonces", [reg.owner])), + } } // the chain reads the owner signs with, unread when either fails: the view still answers @@ -571,7 +578,7 @@ async function invoiceView(inv: Invoice): Promise> { } for (const k of ["amountPaid", "cryptoAmountPaid", "cryptoAmountDue", "paidInFull", "settledAt"] as const) if (inv[k] !== null) view[k] = inv[k] if (inv.method === "card") view.clientSecret = inv.clientSecret - else Object.assign(view, { address: addressFor(inv.method, inv.id), cryptoAmount: inv.cryptoAmount, cryptoCurrency: inv.method, requiredConfirmations: 1 }) + else Object.assign(view, { ...inv.payee, cryptoAmount: inv.cryptoAmount, cryptoCurrency: inv.method, requiredConfirmations: 1 }) return view } @@ -685,7 +692,7 @@ async function injectedRefusal(length: number): Promise { const injected = control.invoiceError if (!injected) return control.invoiceError = null - const extra = injected === "catalog_changed" ? { price: await chainPrice(length, YEARS) + RAISED_PRICE_CENTS } : {} + const extra = injected === "catalog_changed" ? { price: await chainPrice(length, YEARS) } : {} throw new HttpError(INVOICE_ERRORS[injected], injected, extra, injected === "rate_limited" ? RETRY_AFTER_SECONDS : null) } @@ -694,8 +701,11 @@ function refuseWhenCodesOnly(): void { if (control.mode === "codes") throw new HttpError(403, CODES_ONLY) } +const refuseInDowntime = () => { if (control.downtime) throw new HttpError(503, "downtime") } + export async function createInvoice(body: Record): Promise> { if (body.kind !== "name") throw badRequest() + refuseInDowntime() refuseWhenCodesOnly() const sent = flatOrder(body.order) const order = orderBody(sent) @@ -714,13 +724,17 @@ export async function createInvoice(body: Record): Promise +type NewRegistration = Pick const DISPUTE_DAYS: Record = { card: 120, btc: 14, xmr: 14, code: 14 } @@ -739,15 +753,60 @@ function newRegistration(order: OrderBody, extra: NewRegistration, rv: Reveal): const reg: Registration = { id: id(), invoiceId: null, ...order, ...extra, ...rv, commitTx: null, registerTx: null, revealAfter: null, revealBefore: null, expiresAt: null, error: null, createdAt: iso(nowSeconds()), failNext: false, staleNext: false, version: 1, - paidAt: extra.phase === "queued" ? nowSeconds() : null, takenAt: null, disputeDays: DISPUTE_DAYS[extra.method], disputeUntil: null, + paidAt: extra.phase === "queued" ? nowSeconds() : null, takenAt: null, disputeUntil: null, } registrations.set(reg.id, reg) return reg } -export async function readInvoice(invoiceId: string, wait: string | null, seenVersion: number | null, seenPaid: string | null, seenFull: boolean): Promise> { +interface RequestSignature { timestamp?: unknown; signature?: unknown } +const orderRequests = { signed: 0, refused: 0 } +const notFound = () => { + orderRequests.refused += 1 + return new HttpError(404, "not_found") +} + +async function requester(id: string, action: "read" | "cancel" | "retry" | "reveal", { timestamp, signature }: RequestSignature): Promise

{ + if (!Number.isInteger(timestamp)) throw notFound() + freshTimestamp(timestamp) + if (typeof signature !== "string" || !isHex(signature)) throw notFound() + try { + return await recoverMessageAddress({ message: `simplex.domains order ${id} ${action} ${timestamp}`, signature }) + } catch { + throw notFound() + } +} + +async function ownInvoice(invoiceId: string, action: "read" | "cancel", signed: RequestSignature): Promise { + const signer = await requester(invoiceId, action, signed) + const inv = invoices.get(invoiceId) + if (!inv || registrations.get(inv.registrationId)!.owner !== signer) throw notFound() + orderRequests.signed += 1 + return inv +} + +async function ownRegistration(registrationId: string, action: "read" | "retry", signed: RequestSignature): Promise { + const signer = await requester(registrationId, action, signed) + const reg = registrations.get(registrationId) + if (!reg || reg.owner !== signer) throw notFound() + orderRequests.signed += 1 + return reg +} + +export async function invoiceOf(invoiceId: string): Promise> { const inv = invoices.get(invoiceId) if (!inv) throw new HttpError(404, "not_found") + return invoiceView(inv) +} + +export async function registrationOf(registrationId: string): Promise> { + const reg = registrations.get(registrationId) + if (!reg) throw new HttpError(404, "not_found") + return registrationView(reg) +} + +export async function readInvoice(invoiceId: string, signed: RequestSignature, wait: string | null, seenVersion: number | null, seenPaid: string | null, seenFull: boolean): Promise> { + const inv = await ownInvoice(invoiceId, "read", signed) expireIfDue(inv) const reg = registrations.get(inv.registrationId)! if (wait !== null) { @@ -757,9 +816,8 @@ export async function readInvoice(invoiceId: string, wait: string | null, seenVe return invoiceView(inv) } -export async function readRegistration(registrationId: string, seenVersion: number | null): Promise> { - const reg = registrations.get(registrationId) - if (!reg) throw new HttpError(404, "not_found") +export async function readRegistration(registrationId: string, signed: RequestSignature, seenVersion: number | null): Promise> { + const reg = await ownRegistration(registrationId, "read", signed) if (seenVersion !== null) await hold(reg.id, () => reg.version === seenVersion) return registrationView(reg) } @@ -770,9 +828,8 @@ function expireIfDue(inv: Invoice): void { if (overdue(inv)) close(inv) } -export async function cancelInvoice(invoiceId: string): Promise> { - const inv = invoices.get(invoiceId) - if (!inv) throw new HttpError(404, "not_found") +export async function cancelInvoice(invoiceId: string, signed: RequestSignature): Promise> { + const inv = await ownInvoice(invoiceId, "cancel", signed) expireIfDue(inv) if (inv.status !== "open") throw new HttpError(409, "not_open") if (inv.amountPaid) throw new HttpError(409, "funded") @@ -801,6 +858,7 @@ const stateOf = (row: PrepaidCode) => row.registrationId !== null && row.state = const CODE_ERRORS: Partial> = { used: "code_used", reserved: "code_reserved", expired: "code_expired", unpaid: "payment_pending", revoked: "code_invalid" } export async function registerWithCode(body: Record): Promise> { + refuseInDowntime() if (typeof body.code !== "string") throw badRequest() const sent = flatOrder(body.order) const order = orderBody(sent) @@ -818,7 +876,7 @@ export async function registerWithCode(body: Record): Promise { } export async function reveal(registrationId: string, body: Record): Promise> { + const requested = await requester(registrationId, "reveal", typeof body.request === "object" && body.request !== null ? body.request as RequestSignature : {}) const reg = registrations.get(registrationId) - if (!reg) throw new HttpError(404, "not_found") + if (!reg || reg.owner !== requested) throw notFound() + orderRequests.signed += 1 const signature = checkSignature(body.signature) if (reg.label !== null) { if (reg.label === body.label && reg.intent?.signature === signature) return {} @@ -1135,12 +1195,17 @@ async function checkSigned(owner: Address, message: string, timestamp: unknown, const sha256Hex = (text: string) => "0x" + createHash("sha256").update(text, "ascii").digest("hex") export async function selectName(registrationId: string, body: Record): Promise> { - const reg = registrations.get(registrationId) - if (!reg) throw new HttpError(404, "not_found") + refuseInDowntime() const sent = flatSigned(body) - const order = orderBody({ ...sent, owner: reg.owner }) + const fields = orderFields(sent) const revealBody = objectOf(body.reveal) - await checkSigner(reg.owner, `simplex.domains name ${reg.id} ${order.labelHash} ${order.length} ${order.duration} ${order.commitment} ${sha256Hex(order.sealed)} ${order.terms} ${sent.timestamp}`, sent.timestamp, sent.signature) + if (!Number.isInteger(sent.timestamp)) throw badRequest() + const signature = checkSignature(sent.signature) + const reg = registrations.get(registrationId) + if (!reg) throw new HttpError(404, "not_found") + const order: OrderBody = { ...fields, owner: reg.owner } + const message = `simplex.domains name ${reg.id} ${order.labelHash} ${order.length} ${order.duration} ${order.commitment} ${sha256Hex(order.sealed)} ${order.terms} ${sent.timestamp}` + if (await recoverMessageAddress({ message, signature }) !== reg.owner) throw new HttpError(404, "not_found") const current = reg.labelHash === order.labelHash && reg.length === order.length && reg.duration === order.duration && reg.commitment === order.commitment && reg.sealed === order.sealed && reg.terms === order.terms // a repeat is answered however old its signature, as the service answers it before the age @@ -1183,9 +1248,8 @@ function codeReservable(row: PrepaidCode, reg: Registration, length: number): vo if (length < row.minLength) throw new HttpError(409, "code_not_covering") } -export async function retry(registrationId: string): Promise> { - const reg = registrations.get(registrationId) - if (!reg) throw new HttpError(404, "not_found") +export async function retry(registrationId: string, signed: RequestSignature): Promise> { + const reg = await ownRegistration(registrationId, "retry", signed) // only a commitment that lapsed unsigned is committed again if (control.writeDelayMs) await sleep(control.writeDelayMs) if (!lapsed(reg)) throw badRequest() @@ -1538,7 +1602,15 @@ export function controlSearch(body: Record): Record): Record { + const { price = null, policy = false, termsHash = false, method = false, address = null, amount = false } = body + if ((price !== null && !(Number.isInteger(price) && (price as number) >= 0)) || [policy, termsHash, method, amount].some((flag) => typeof flag !== "boolean") + || (address !== null && address !== "btc" && address !== "xmr")) throw badRequest() + Object.assign(mismatch, { price, policy, termsHash, method, address, amount }) + return { ...mismatch } +} + +// The service's mode as a restart with codes_only on or off sets it. export function controlMode(body: Record): Record { if (body.mode !== "open" && body.mode !== "codes") throw badRequest() control.mode = body.mode @@ -1547,9 +1619,15 @@ export function controlMode(body: Record): Record ({ mode: control.mode }) -export const siteConfig = (): { stripePublishableKey: null; names: NamesSite } => ({ +export function controlDowntime(body: Record): Record { + if (typeof body.on !== "boolean") throw badRequest() + control.downtime = body.on + return { downtime: control.downtime } +} + +export const siteConfig = () => ({ stripePublishableKey: null, - names: { codesOnly: control.mode === "codes", chainId: deployment.chainId, resolver: deployment.resolver, sponsor: deployment.sponsor, tld: deployment.tld, termStart: TERM_START_S }, + names: { codesOnly: control.mode === "codes", chainId: deployment.chainId, resolver: deployment.resolver, sponsor: deployment.sponsor, tld: deployment.tld, termStart: TERM_START_S, downtime: control.downtime }, }) export async function controlClock(body: Record): Promise> { @@ -1623,7 +1701,7 @@ export async function currentTerms(hash: string): Promise ({ ...r, intent: r.intent && { ...r.intent, nonce: String(r.intent.nonce), deadline: String(r.intent.deadline) } })), - invoices: [...invoices.values()], balances: Object.fromEntries(balances), + invoices: [...invoices.values()], balances: Object.fromEntries(balances), orderRequests, } } diff --git a/webapp/e2e/README.md b/webapp/e2e/README.md index 207492ac..1e4f7909 100644 --- a/webapp/e2e/README.md +++ b/webapp/e2e/README.md @@ -35,4 +35,4 @@ docker run --rm --network host --ipc host -v "$PWD/..:/work" -w /work/webapp -e mcr.microsoft.com/playwright:v1.64.1-noble npx playwright test --project=screens --update-snapshots ``` -A new state takes the next free time slot in `screens.spec.ts`; states run in the order of their slots. +A new state takes the next free time slot in `screens.spec.ts`; states run in the order of their slots. The state of a term already started runs last, at a slot past `SITE.termStart`, which the page holds. diff --git a/webapp/e2e/balance.spec.ts b/webapp/e2e/balance.spec.ts index b79b89e7..cff641df 100644 --- a/webapp/e2e/balance.spec.ts +++ b/webapp/e2e/balance.spec.ts @@ -5,6 +5,7 @@ import { } from "./helpers.ts" const balanceRow = (page: Page) => onStep(page).locator(".list-row[data-key^='balance-']") +const WITH_PROOF = "Copy the order reference and address proof for support" // Your names, its rows read async function yourNames(page: Page): Promise { @@ -36,6 +37,7 @@ const ROW_GAP = 14 test("a paid order taken first keeps its price as its balance, which support refunds", async ({ page, request }) => { const label = sevenLetters() const { invoiceId } = await takenOrder(page, request, label) + await expect(onStep(page).getByRole("button", { name: WITH_PROOF }), "the taken order's page gives support its address proof").toBeVisible() await yourNames(page) await expect(balanceRow(page)).toHaveCount(1) await expect(balanceRow(page).locator(".main")).toHaveText(`$200From ${label}.simplex, someone has taken this name`) @@ -54,7 +56,7 @@ test("a paid order taken first keeps its price as its balance, which support ref const popup = page.getByRole("dialog", { name: "Refund" }) await expect(popup).toContainText(`Please contact support via chat@simplex.chat or SimpleX, with the name and the order reference ${invoiceId}. Support refunds what is left of your balance.`) await expect(popup.locator(".code-text")).toHaveText(invoiceId) - await expect(popup.getByRole("button", { name: "Copy reference" })).toBeFocused() + await expect(popup.getByRole("button", { name: WITH_PROOF }), "a Bitcoin order's copy holds its address proof").toBeFocused() await shot(page, "B2-refund") await popup.getByRole("button", { name: "Close" }).click() await expect(balanceRow(page).getByRole("button", { name: "Refund" })).toBeFocused() diff --git a/webapp/e2e/card.spec.ts b/webapp/e2e/card.spec.ts new file mode 100644 index 00000000..2ecb3a20 --- /dev/null +++ b/webapp/e2e/card.spec.ts @@ -0,0 +1,69 @@ +import { expect, type Page } from "@playwright/test" +import { heldPrice, LOCAL } from "../src/config.ts" +import { cardFrame, cardFrameOf, fakeIntent, onStep, payButton, startOrder, test, uniqueLabel, withStripeKey } from "./helpers.ts" + +const UNCHECKED = "Sorry, the payment details of this order could not be checked, so they are not shown. Please contact support with the order reference." +const OTHER_ORIGIN = "http://127.0.0.2:5999" +const SETTLE_MS = 2000 + +// a page of another origin that frames the card page and sends it a mount +async function framedElsewhere(page: Page, browserName: string): Promise { + if (browserName === "chromium") await page.context().grantPermissions(["local-network-access"]) + await page.route(`${OTHER_ORIGIN}/**`, (route) => route.fulfill({ contentType: "text/html", body: `` })) + await page.goto(`${OTHER_ORIGIN}/`) + const frame = page.frames().find((f) => f.url().startsWith(LOCAL.cardOrigin))! + await frame.waitForLoadState() + await page.evaluate((card) => document.querySelector("iframe")!.contentWindow!.postMessage({ type: "mount", clientSecret: "pi_x_secret_y", amount: 10000, dark: false }, card), LOCAL.cardOrigin) +} + +test("the card page takes a mount only from the names page's origin", async ({ page, browserName }) => { + await framedElsewhere(page, browserName) + await page.waitForTimeout(SETTLE_MS) + const frame = page.frames().find((f) => f.url().startsWith(LOCAL.cardOrigin))! + expect(await frame.locator("#form > *").count(), "nothing drawn for another origin").toBe(0) +}) + +test("a PaymentIntent of another amount than the invoice's is not mounted, and the order's page withholds the card form", async ({ page }) => { + const label = uniqueLabel("intent") + await startOrder(page, label, { method: "card" }) + await withStripeKey(page) + const mounts: number[] = [] + await page.exposeFunction("cardMounted", () => mounts.push(1)) + await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: `window.Stripe = () => ({ + retrievePaymentIntent: async () => (${fakeIntent(heldPrice(label.length) + 100)}), + elements: () => ({ update: () => undefined, create: () => ({ on: () => undefined, destroy: () => undefined, mount: () => window.cardMounted?.() }) }), + })` })) + await page.reload() + await expect(onStep(page).getByText(UNCHECKED)).toBeVisible() + await expect(onStep(page).locator(".stripe")).toHaveCount(0) + expect(mounts).toEqual([]) +}) + +test("a message from another origin, or from the names page itself, is ignored, and the card page's own paid moves the order on", async ({ page }) => { + test.skip(!!process.env.BASE_URL, "frames another origin, which the built page's policy refuses") + await startOrder(page, uniqueLabel("paidmsg"), { method: "card" }) + await expect(cardFrame(page).locator(".stand-in")).toBeVisible() + const forged = "parent.postMessage({ type: \"paid\", id: \"pi_forged\" }, \"*\"); parent.postMessage({ type: \"height\", px: 4321 }, \"*\")" + await page.route(`${OTHER_ORIGIN}/**`, (route) => route.fulfill({ contentType: "text/html", body: `` })) + await page.evaluate((other) => { + document.body.append(Object.assign(document.createElement("iframe"), { src: `${other}/` })) + postMessage({ type: "paid", id: "pi_forged" }, "*") + postMessage({ type: "height", px: 4321 }, "*") + }, OTHER_ORIGIN) + await page.waitForTimeout(SETTLE_MS) + await expect(onStep(page).getByRole("heading", { name: "Pay by card" })).toBeVisible() + expect(await page.locator("iframe.card-frame").evaluate((f) => (f as HTMLElement).style.height), "the frame's height from the card page alone").not.toBe("4321px") + await (await cardFrameOf(page)).evaluate(() => parent.postMessage({ type: "paid", id: "pi_forged" }, "*")) + await page.waitForTimeout(SETTLE_MS) + await expect(onStep(page).getByRole("heading", { name: "Pay by card" }), "a paid the page did not ask for").toBeVisible() + await payButton(page).click() + await expect(page.getByText("Waiting for Stripe to confirm")).toBeVisible() +}) + +test("the names page admits the card page's origin alone among the frames, and no Stripe host", async ({ page }) => { + test.skip(!process.env.BASE_URL, "the policy is the built page's") + await page.goto("/") + const policy = await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute("content") + expect(policy).toContain(`frame-src ${LOCAL.cardOrigin};`) + expect(policy).not.toContain("stripe") +}) diff --git a/webapp/e2e/codes-only.spec.ts b/webapp/e2e/codes-only.spec.ts index 15f3b253..511de8a0 100644 --- a/webapp/e2e/codes-only.spec.ts +++ b/webapp/e2e/codes-only.spec.ts @@ -2,8 +2,8 @@ import { type APIRequestContext, expect, type Page } from "@playwright/test" import { labelHash } from "../src/crypto/registration.ts" import { hex } from "../src/crypto/wallet.ts" import { - AGREE, agreeToTerms, CHECKOUT_KEY, codeField, control, keepOrder, MOCK, onStep, payButton, recordedFrames, recordFrames, registrationView, savedToReview, search, shot, startOrder, takenOrder, test, toCodeStep, toFullReview, toReview, - uniqueLabel, useCode, waitRegistered, + CODES_PAGE, codeField, codesPageHolds, codesTest, control, keepOrder, loads, MOCK, onStep, payButton, recordedFrames, recordFrames, registrationView, savedToReview, search, shot, startOrder, takenOrder, test, + toCodeStep, toReview, uniqueLabel, useCode, waitRegistered, } from "./helpers.ts" const CODES_ONLY_LINE = "Names can be registered only with a code right now." @@ -15,26 +15,9 @@ const nameField = (page: Page) => page.getByLabel("Name", { exact: true }) const lens = (page: Page) => page.getByRole("button", { name: "Search", exact: true }) const setMode = (request: APIRequestContext, mode: "open" | "codes") => control(request, "mode", { mode }) -// the tab coming back into view, as a reader switching back to it; headless browsers keep every tab in view -const becomeVisible = (page: Page) => page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))) -// the page loaded again, in the mode the service gives, as the tab comes back into view -const reloadedOnView = (page: Page) => Promise.all([page.waitForEvent("load"), becomeVisible(page)]) -// the page's own check of the service's mode, answered -const modeChecked = (page: Page) => page.waitForResponse((r) => new URL(r.url()).pathname === "/api/config") -// Every document the page loads from now on, counted as it fires load: a page loaded again runs the service's mode. -function loads(page: Page): { count: number } { - const seen = { count: 0 } - page.on("load", () => { seen.count += 1 }) - return seen -} // long enough for a load the check started to have finished const RELOAD_MS = 1000 -// long enough for several frames to paint before the page knows its mode const SLOW_CONFIG_MS = 400 -const checkoutKept = (page: Page) => page.evaluate((key) => { - const { label, contact, channel, ownerCode, saved, agreed, step } = JSON.parse(sessionStorage.getItem(key)!) - return { label, contact, channel, ownerCode, saved, agreed, step } -}, CHECKOUT_KEY) // the mock of this worker's slot goes back to open, whatever a test left, for the specs after it test.afterEach(async ({ request }) => { @@ -89,11 +72,11 @@ test("each mode's home is drawn from its first frame, never the other mode's fir const field = document.querySelector("body > main input") return { header: document.querySelector("body > header .brand") !== null, field: field === null ? "none" : field.disabled ? "codes" : "open" } }, true) - for (const mode of ["codes", "open"] as const) { + for (const [mode, origin] of [["codes", CODES_PAGE], ["open", ""]] as const) { await setMode(request, mode) for (const route of ["/", "/#/?name=bakery"]) { await page.goto("about:blank") - await page.goto(route) + await page.goto(`${origin}${route}`) await expect(nameField(page)).toBeVisible() await page.evaluate(() => new Promise((drawn) => requestAnimationFrame(() => requestAnimationFrame(drawn)))) const frames = await recordedFrames<{ header: boolean; field: string }>(page) @@ -106,7 +89,7 @@ test("each mode's home is drawn from its first frame, never the other mode's fir } }) -test("a load asks the service's mode once, as the preload's answer is the one the page reads", async ({ page, request, browserName }) => { +codesTest("a load asks the service's config once, as the preload's answer is the one the page reads", async ({ page, request, browserName }) => { test.skip(browserName === "webkit", "WebKit asks the service again rather than hand the preloaded answer to the page") await setMode(request, "codes") const asked: string[] = [] @@ -117,7 +100,7 @@ test("a load asks the service's mode once, as the preload's answer is the one th expect(asked, "one request, the preload's").toHaveLength(1) }) -test("without a code, the home's search is greyed, takes no pointer, focus or Enter, and Register with code leads on", async ({ page, request }) => { +codesTest("without a code, the home's search is greyed, takes no pointer, focus or Enter, and Register with code leads on", async ({ page, request }) => { await setMode(request, "codes") const calls = apiCalls(page) // a link naming a name searches nothing either @@ -165,7 +148,7 @@ test("without a code, the home's search is greyed, takes no pointer, focus or En await expect(page).toHaveURL(/#\/code$/) }) -test("#/code opens Check your code from a cold load, its field ready for the code", async ({ page, request }) => { +codesTest("#/code opens Check your code from a cold load, its field ready for the code", async ({ page, request }) => { await setMode(request, "codes") await page.goto("/#/code") await expect(onStep(page).getByRole("heading", { name: "Check your code" })).toBeVisible() @@ -175,7 +158,7 @@ test("#/code opens Check your code from a cold load, its field ready for the cod await shot(page, "C2-codes-only-check-code") }) -test("a valid prepaid code opens the search for the names it covers and registers one as a free code order", async ({ page, request }) => { +codesTest("a valid prepaid code opens the search for the names it covers and registers one as a free code order", async ({ page, request }) => { await setMode(request, "codes") const { code } = await control(request, "code", { minLength: 7, years: 2 }) as { code: string } const calls = apiCalls(page) @@ -210,7 +193,7 @@ test("a valid prepaid code opens the search for the names it covers and register expect(calls).toContain("POST /api/name/register") }) -test("a code taken off on Check your order leaves the code field in place of payment, and a code there registers", async ({ page, request }) => { +codesTest("a code taken off on Check your order leaves the code field in place of payment, and a code there registers", async ({ page, request }) => { await setMode(request, "codes") const { code } = await control(request, "code", { minLength: 6 }) as { code: string } await useCode(page, code) @@ -240,7 +223,8 @@ test("an order paid before codes only shows no new invoice or other name, only R await expect(page.getByRole("heading", { name: "Invoice closed" })).toBeVisible() await setMode(request, "codes") - await page.goto(`/?order=${invoiceId}`) + await codesPageHolds(page) + await page.goto(`${CODES_PAGE}/?order=${invoiceId}`) await expect(page.getByRole("heading", { name: `${label}.simplex is no longer available` })).toBeVisible() await expect(onStep(page).getByText("What you paid is in your balance. You can ask for a refund.")).toBeVisible() await expect(onStep(page).getByRole("button", { name: REGISTER_WITH_CODE })).toBeVisible() @@ -249,14 +233,14 @@ test("an order paid before codes only shows no new invoice or other name, only R await noPaymentUi(page) await shot(page, "C7-codes-only-taken") - await page.goto(`/?order=${expired.invoiceId}`) + await page.goto(`${CODES_PAGE}/?order=${expired.invoiceId}`) await expect(page.getByRole("heading", { name: "Invoice closed" })).toBeVisible() await expect(onStep(page).getByRole("checkbox")).toHaveCount(0) await noPaymentUi(page) await onStep(page).getByRole("button", { name: REGISTER_WITH_CODE }).click() await expect(onStep(page).getByRole("heading", { name: "Check your code" })).toBeVisible() - await page.goto("/#/names") + await page.goto(`${CODES_PAGE}/#/names`) const balance = page.locator(".balance-row") await expect(balance).toBeVisible() await expect(balance.getByRole("button", { name: "Refund" })).toBeVisible() @@ -264,7 +248,7 @@ test("an order paid before codes only shows no new invoice or other name, only R await shot(page, "C8-codes-only-names") }) -test("a registration ended in its dispute period is shown with Register with code alone, as the other endings are", async ({ page, request }) => { +codesTest("a registration ended in its dispute period is shown with Register with code alone, as the other endings are", async ({ page, request }) => { await setMode(request, "codes") const label = uniqueLabel("endc") const order = await keepOrder(page, `reg-${label}`, null, label) @@ -304,68 +288,14 @@ test("a closed invoice's page opened before codes only, refused a new invoice, s await expect(note).toContainText(`${CODES_ONLY_LINE} Enter a code.`) await expect(page).toHaveURL(new RegExp(`order=${invoiceId}`)) expect(seen.count, "the refusal stays in view, in the page as it was").toBe(0) + await Promise.all([ + page.waitForResponse((r) => new URL(r.url()).pathname === "/api/config"), + page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))), + ]) + await page.waitForTimeout(RELOAD_MS) + expect(seen.count, "the refusal stays in view as the page reads the service again").toBe(0) + await expect(note).toBeVisible() await note.getByRole("link", { name: "Enter a code" }).click() await expect(onStep(page).getByRole("heading", { name: "Check your code" })).toBeVisible() expect(seen.count, "the screen after the refusal is the service's page again").toBe(1) }) - -test("a checkout open as the service takes codes only loads again in codes mode with its name, links, name code and terms", async ({ page, request }) => { - const label = uniqueLabel("keep") - await toFullReview(page, label) - await page.getByRole("radio", { name: "Bitcoin" }).click() - const before = await checkoutKept(page) - expect(before.agreed && before.saved && before.contact && before.channel).toBeTruthy() - await setMode(request, "codes") - await reloadedOnView(page) - await expect(onStep(page).getByRole("heading", { name: "Check your order" })).toBeVisible() - expect(await checkoutKept(page)).toEqual(before) - await expect(onStep(page).getByRole("checkbox", { name: AGREE })).toBeChecked() - await expect(codeField(page), "a code pays in place of the payment choices").toBeVisible() - await noPaymentUi(page) -}) - -test("an order paid as the service takes codes only loads again with its invoice, and registers", async ({ page, request }) => { - const label = uniqueLabel("paid") - const { invoiceId } = await startOrder(page, label, { method: "btc" }) - await setMode(request, "codes") - await reloadedOnView(page) - await expect(page).toHaveURL(new RegExp(`order=${invoiceId}`)) - await control(request, `settle/${invoiceId}`) - await waitRegistered(page, label) -}) - -test("a codes-only page open as the service opens loads again with the search on", async ({ page, request }) => { - await setMode(request, "codes") - const checked = modeChecked(page) - await page.goto("/") - await checked - await expect(nameField(page)).toBeDisabled() - await setMode(request, "open") - await reloadedOnView(page) - await expect(nameField(page)).toBeEnabled() -}) - -test("a closed invoice's page holding changed terms ticked again stays as the service takes codes only, until the reader leaves it", async ({ page, request }) => { - const label = uniqueLabel("tick") - const { invoiceId } = await startOrder(page, label, { method: "btc" }) - await control(request, `expire/${invoiceId}`) - await expect(onStep(page).getByRole("heading", { name: "Invoice closed" })).toBeVisible() - await control(request, "general-terms", { text: `the general terms, changed for ${label}` }) - try { - await onStep(page).getByRole("button", { name: "Get a new invoice" }).click() - await agreeToTerms(page) - await setMode(request, "codes") - const seen = loads(page) - const checked = modeChecked(page) - await becomeVisible(page) - await checked - await page.waitForTimeout(RELOAD_MS) - expect(seen.count, "the tick is in the page only, so the page stays").toBe(0) - await expect(onStep(page).getByRole("checkbox", { name: AGREE })).toBeChecked() - await page.locator("body > header").getByRole("link", { name: "Check your code" }).click() - await expect(onStep(page).getByRole("heading", { name: "Check your code" })).toBeVisible() - expect(seen.count, "the next screen is the service's page again").toBe(1) - } finally { - await control(request, "general-terms", { text: null }) - } -}) diff --git a/webapp/e2e/codes.spec.ts b/webapp/e2e/codes.spec.ts index 543042c4..f2edafac 100644 --- a/webapp/e2e/codes.spec.ts +++ b/webapp/e2e/codes.spec.ts @@ -113,7 +113,7 @@ test("a prepaid code from Check your code shows a name as Free and registers it expect(registered.type).toBe("registered") await expect(page.locator("body > main .lead")).toHaveText(`Registered until ${dateOf(registered.expiresAt as number)}.`) // the code's term, its 5 years and the free days, sent as the duration, counted on chain from the register's block - const view = await (await request.get(`${MOCK}/api/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as + const view = await (await request.get(`${MOCK}/control/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as { years: number; duration: number; registerTx: string; phase: { disputeUntil: number } } expect(view.years).toBe(5) expect(await chainExpiry(label)).toBe(await blockTimeOf(view.registerTx) + view.duration) @@ -151,7 +151,7 @@ test("a registration ended in its dispute period is shown as ended on its order' const { registrationId, label } = await registerWithCode(page, request, "ended") await waitRegistered(page, label) await control(request, `unregister/${registrationId}`) - expect((await (await request.get(`${MOCK}/api/registration/${registrationId}`)).json()).phase, "the view the service gives an ended order").toEqual({ type: "ended" }) + expect((await (await request.get(`${MOCK}/control/registration/${registrationId}`)).json()).phase, "the view the service gives an ended order").toEqual({ type: "ended" }) await page.reload() await expect(onStep(page).getByRole("heading", { name: "Registration cancelled" })).toBeVisible() await expect(onStep(page).locator(".notice")).toHaveText(`The registration of ${label}.simplex was cancelled because its payment was disputed or refunded.`) @@ -175,7 +175,7 @@ test("a prepaid code registers a name with its links, which its records on chain expect(answer.records).toMatchObject(links) const owner = checksumAddress(walletOf(await ownerCodeOf(page, registrationId))!.address) expect(answer.owner, "the name code's wallet owns the name").toBe(owner) - const { registerTx } = await (await request.get(`${MOCK}/api/registration/${registrationId}`)).json() as { registerTx: string } + const { registerTx } = await (await request.get(`${MOCK}/control/registration/${registrationId}`)).json() as { registerTx: string } expect(await acceptedOnChain(registerTx)).toEqual({ kind: "general", name: label, holder: owner, termsHash: GENERAL_TERMS_HASH }) await page.goto(`/#/?name=${label}`) await expect(page.locator(".answer .row .chat"), "the name's answer opens both chats").toHaveCount(2) @@ -187,7 +187,7 @@ test("a prepaid code registers a name the contracts' owner listed on chain, its await contractsOwnerLists(label) await payWithCode(page, label, code) await waitRegistered(page, label) - const view = await (await request.get(`${MOCK}/api/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as { owner: string; registerTx: string } + const view = await (await request.get(`${MOCK}/control/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as { owner: string; registerTx: string } expect(await acceptedOnChain(view.registerTx)).toEqual({ kind: "community", name: label, holder: view.owner, termsHash: COMMUNITY_TERMS_HASH }) }) @@ -204,7 +204,7 @@ test("a prepaid code for 5 years registers a community name for its 2 years and await onStep(page).getByRole("button", { name: REGISTER_WITH_CODE }).click() await page.waitForURL(/\?registration=/) await waitRegistered(page, label) - const view = await (await request.get(`${MOCK}/api/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as { duration: number; registerTx: string } + const view = await (await request.get(`${MOCK}/control/registration/${new URL(page.url()).searchParams.get("registration")}`)).json() as { duration: number; registerTx: string } expect(Math.floor(view.duration / YEAR_S), "2 years and the free days").toBe(2) expect(await chainExpiry(label)).toBe(await blockTimeOf(view.registerTx) + view.duration) }) @@ -899,14 +899,13 @@ test("Your names words a code order before its registration as a free name with await page.unrouteAll({ behavior: "ignoreErrors" }) }) -test("a code order opened in a browser without its name code asks for the name code saved for it", async ({ page }) => { - const order = { registrationId: "reg-code-elsewhere", invoiceId: null, label: uniqueLabel("ce"), ownerCode: "", owner: "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", - request: { labelHash: `0x${"ab".repeat(32)}`, commitment: `0x${"01".repeat(32)}` } } - await page.route(`**/api/registration/${order.registrationId}*`, (route) => route.fulfill({ json: registrationView(order, { label: null, phase: { type: "queued" }, payment: { type: "code" }, price: 0 }) })) - await page.goto(`/?registration=${order.registrationId}`) +test("a code order's link in a browser without its name code asks for the code, reading nothing", async ({ page }) => { + const asked: string[] = [] + page.on("request", (r) => { if (new URL(r.url()).pathname.startsWith("/api/registration/")) asked.push(r.url()) }) + await page.goto("/?registration=reg-code-elsewhere") await expect(onStep(page).getByRole("heading", { name: "The name code is not in this browser" })).toBeVisible() - await expect(onStep(page).locator(".notice")).toContainText("Please enter the name code you saved for this order.") - await page.unrouteAll({ behavior: "ignoreErrors" }) + await expect(onStep(page).locator(".notice")).toHaveText("Please enter the name code you saved for this order.") + expect(asked).toEqual([]) }) test("a code order whose name was reserved meanwhile says so, and offers selecting another name", async ({ page, request }) => { @@ -930,11 +929,8 @@ test("a code order taken first asks a browser without its name code for the code const other = await browser.newContext() const stranger = await other.newPage() await stranger.goto(`/?registration=${registrationId}`) - await expect(stranger.getByRole("heading", { name: takenHeading(label) })).toBeVisible() - await expect(onStep(stranger).locator(".notice", { hasText: "The name code is not in this browser" })) - .toHaveText("The name code is not in this browserAdd it in Check your code to choose another name.") - await expect(onStep(stranger).getByRole("button", { name: "Choose another name" })).toBeDisabled() - await expect(onStep(stranger).getByRole("button", { name: "Search another name" })).toHaveCount(0) + await expect(stranger.getByRole("heading", { name: "The name code is not in this browser" })).toBeVisible() + await expect(onStep(stranger).getByRole("button", { name: "Enter your name code" })).toBeVisible() await other.close() await page.goto("/#/names") await expect(page.locator(".list-row", { hasText: code }).locator(".chip")).toHaveText("In use") diff --git a/webapp/e2e/community.spec.ts b/webapp/e2e/community.spec.ts index d2fbbff5..0d7530eb 100644 --- a/webapp/e2e/community.spec.ts +++ b/webapp/e2e/community.spec.ts @@ -4,13 +4,11 @@ import { createHash } from "node:crypto" import { expect, type APIRequestContext, type Locator, type Page } from "@playwright/test" import { - ACCEPT, acceptCommunityTerms, AGREE, agreeToTerms, COMMUNITY_HEADING, control, MOCK, onStep, payButton, REGISTRATION_MS, registrationOf, restoreOrder, search, + ACCEPT, acceptCommunityTerms, AGREE, agreeToTerms, ALTERNATE_COMMUNITY_TERMS, ALTERNATE_GENERAL_TERMS, COMMUNITY_HEADING, control, MOCK, onStep, orderedAtMock, payButton, REGISTRATION_MS, registrationOf, restoreOrder, search, SAVED, startOrder, takenOrder, test, toCodeStep, toReview, uniqueLabel, waitRegistered, withStripeKey, acceptedOnChain, COMMUNITY_TERMS, COMMUNITY_TERMS_HASH, PLAIN_TERMS, } from "./helpers.ts" import { keccak256, toHex } from "viem" import * as api from "../src/api.ts" -import { labelHash } from "../src/crypto/registration.ts" -import { hex } from "../src/crypto/wallet.ts" import { RETRY_MS } from "../src/screens/order.ts" const COMMUNITY_LABEL = "bakers" @@ -41,8 +39,8 @@ async function withTerms(request: APIRequestContext, kind: "general-terms" | await control(request, kind, { text: null }) } } -const withGeneralTerms = (request: APIRequestContext, text: string, f: (hash: string) => Promise) => withTerms(request, "general-terms", text, f) -const withCommunityTerms = (request: APIRequestContext, text: string, f: (hash: string) => Promise) => withTerms(request, "community-terms", text, f) +const withGeneralTerms = (request: APIRequestContext, f: (hash: string) => Promise) => withTerms(request, "general-terms", ALTERNATE_GENERAL_TERMS, f) +const withCommunityTerms = (request: APIRequestContext, f: (hash: string) => Promise) => withTerms(request, "community-terms", ALTERNATE_COMMUNITY_TERMS, f) // The names on the chain's community list, with the ini's words, while `f` runs. async function listed(request: APIRequestContext, labels: string[], f: () => Promise): Promise { @@ -59,12 +57,12 @@ async function orderBeforeTermsChange(page: Page, request: APIRequestContext, pr const label = uniqueLabel(prefix) await listed(request, [label], async () => { const { invoiceId } = await startOrder(page, label) - await withCommunityTerms(request, `the community terms, changed for ${label}`, (hash) => f(label, invoiceId, hash)) + await withCommunityTerms(request, (hash) => f(label, invoiceId, hash)) }) } -const viewOf = async (request: APIRequestContext, registrationId: string) => (await request.get(`${MOCK}/api/registration/${registrationId}`)).json() as Promise -const invoiceViewOf = async (request: APIRequestContext, invoiceId: string) => (await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as { registration: api.RegistrationView }).registration +const viewOf = async (request: APIRequestContext, registrationId: string) => (await request.get(`${MOCK}/control/registration/${registrationId}`)).json() as Promise +const invoiceViewOf = async (request: APIRequestContext, invoiceId: string) => (await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { registration: api.RegistrationView }).registration const revealAfterOf = async (request: APIRequestContext, invoiceId: string) => api.committedOf(await invoiceViewOf(request, invoiceId))!.revealAfter // Where a community name's marker stands: its baseline against the name's, its gap after the name's TLD, its gap to the @@ -132,7 +130,7 @@ test("a community name's order shows its community terms on their own step befor await toCodeStep(page) await onStep(page).getByText(SAVED).click() await onStep(page).getByRole("button", { name: "Continue" }).click() - await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING })).toBeVisible() + await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 })).toBeVisible() const text = onStep(page).locator(".terms-text") const onChain = await termsOnChain(page) expect(keccak256(toHex(onChain.link)), "the service answers the text of the link whose hash the order signs").toBe(COMMUNITY_TERMS_HASH) @@ -156,7 +154,7 @@ test("a community name's order shows its community terms on their own step befor await expect(onStep(page).locator(".check.terms"), "the community terms include the general terms, accepted once").toHaveCount(0) await expect(payButton(page)).toBeEnabled() await onStep(page).getByRole("link", { name: "Back" }).click() - await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING })).toBeVisible() + await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 })).toBeVisible() await expect(onStep(page).getByRole("checkbox", { name: ACCEPT }), "the step gone back to keeps its tick").toBeChecked() }) @@ -203,7 +201,7 @@ test("an order refused for terms changed meanwhile unticks the box and says so i await expect(onStep(page).locator(".check.terms")).toHaveText(PLAIN_WORDS) const parts = [".card.order", ".check.terms .box", ".actions-row .btn"] const before = await places(page, parts) - await withGeneralTerms(request, `the general terms, changed for ${label}`, async (hash) => { + await withGeneralTerms(request, async (hash) => { await payButton(page).click() const notice = onStep(page).locator(".line", { hasText: TERMS_CHANGED }) await expect(notice).toBeVisible() @@ -239,8 +237,7 @@ test("a name whose terms can't be read now can't be ordered: its search says so, } finally { await control(request, "general-terms", { text: null }) } - const { registrations } = await (await request.get(`${MOCK}/control/state`)).json() as { registrations: { labelHash: string }[] } - expect(registrations.some((r) => r.labelHash === hex(labelHash(label))), "no order made").toBe(false) + expect(await orderedAtMock(request, label), "no order made").toBe(false) }) test("a name put on the list meanwhile is refused for the community terms, which their step then asks for, the review showing its marker, and Your names marks the name", async ({ page, request }) => { @@ -249,7 +246,7 @@ test("a name put on the list meanwhile is refused for the community terms, which await toReview(page) await listed(request, [label], async () => { await payButton(page).click() - await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING })).toBeVisible() + await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 })).toBeVisible() await expect(onStep(page).getByText(TERMS_CHANGED)).toBeVisible() await acceptCommunityTerms(page) await expect(onStep(page).locator(".check.terms"), "the community terms include the general terms").toHaveCount(0) @@ -275,14 +272,14 @@ test("a name selected for a taken order asks for that name's terms first, a comm await expect(page.locator(".answer .row .name").getByRole("button", { name: MARKER })).toBeVisible() await onStep(page).getByRole("button", { name: "Register", exact: true }).click() await onStep(page).getByRole("button", { name: "Skip for now" }).click() - await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING })).toBeVisible() + await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 })).toBeVisible() await expect(onStep(page).locator(".terms-text h3"), "the terms of the hash the selection signs").toHaveText(headingOf((await termsOnChain(page)).text)) await acceptCommunityTerms(page) await expect(onStep(page).locator(".check.terms"), "the community terms include the general terms").toHaveCount(0) const select = onStep(page).getByRole("button", { name: "Register with your payment" }) - await withCommunityTerms(request, `the community terms, changed for the selection of ${target}`, async (hash) => { + await withCommunityTerms(request, async (hash) => { await select.click() - await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING })).toBeVisible() + await expect(onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 })).toBeVisible() await expect(onStep(page).getByText(TERMS_CHANGED)).toBeVisible() await acceptCommunityTerms(page) await select.click() @@ -314,7 +311,7 @@ test("a new invoice for the same name signs the order's own terms without asking const again = onStep(page).getByRole("button", { name: "Get a new invoice" }) const parts = [".notice", ".ref", ".actions-row .btn"] const before = await places(page, parts) - await withGeneralTerms(request, `the general terms, changed for ${label}`, async (hash) => { + await withGeneralTerms(request, async (hash) => { await again.click() await expect(onStep(page).locator(".check.terms")).toHaveText(PLAIN_WORDS) await expect(onStep(page).getByRole("checkbox", { name: AGREE }), "the box takes focus as it comes").toBeFocused() @@ -335,15 +332,15 @@ test("a card form that did not load asks for changed terms before cancelling its await page.reload() await expect(page.getByText("The card form did not load, so your card was not charged. Please reload the page.")).toBeVisible() const again = onStep(page).getByRole("button", { name: "Get a new invoice" }) - await withGeneralTerms(request, "the general terms, changed for a card order", async (hash) => { + await withGeneralTerms(request, async (hash) => { await again.click() await expect(onStep(page).locator(".check.terms")).toHaveText(PLAIN_WORDS) await expect(again).toBeDisabled() - expect((await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json()).status, "nothing cancelled before the tick").toBe("open") + expect((await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json()).status, "nothing cancelled before the tick").toBe("open") await agreeToTerms(page) await again.click() await page.waitForURL((url) => url.searchParams.get("order") !== invoiceId) - expect((await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json()).status).toBe("expired") + expect((await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json()).status).toBe("expired") expect(api.signedTermsOf((await invoiceViewOf(request, new URL(page.url()).searchParams.get("order")!)).terms)).toBe(hash.slice(2)) }) }) @@ -411,19 +408,11 @@ test("changed community terms whose searches fail for now are asked for once a s }) }) -test("changed community terms are asked for by the hash the order's view asks to accept, the view read again while the service has no terms of that hash", async ({ page, request }) => { +test("changed community terms are asked for by the hash the order's view asks to accept, as the page holds them, whatever the service answers for that hash", async ({ page, request }) => { await orderBeforeTermsChange(page, request, "cr", async (_, invoiceId, hash) => { - let refused = false - await page.route(`**/api/terms/${hash}`, async (route) => { - if (refused) return route.fallback() - refused = true - await route.fulfill({ status: 404, json: { type: "not_found" } }) - }) - let reads = 0 - page.on("request", (r) => { if (refused && r.url().endsWith(`/api/invoice/${invoiceId}`)) reads++ }) + await page.route(`**/api/terms/${hash}`, (route) => route.fulfill({ status: 404, json: { type: "not_found" } })) await control(request, `settle/${invoiceId}`) await expect(onStep(page).locator(".line", { hasText: TERMS_CHANGED })).toBeVisible({ timeout: REGISTRATION_MS }) - expect([refused, reads > 0], "the view is read again after its terms were not found").toEqual([true, true]) }) }) @@ -449,7 +438,7 @@ test("community terms changed after the reveal, before its relay, are agreed to // the relay is held back while the reveal is stored and the terms change, then refused for the old terms await control(request, "search", { unsentSeconds: REGISTRATION_MS / 1000 }) await expect.poll(async () => (await invoiceViewOf(request, invoiceId)).label, { timeout: REGISTRATION_MS }).toBe(label) - await withCommunityTerms(request, `the community terms, changed after the reveal of ${label}`, async (hash) => { + await withCommunityTerms(request, async (hash) => { await control(request, "search", { unsentSeconds: 0 }) await expect(onStep(page).locator(".line", { hasText: TERMS_CHANGED })).toBeVisible({ timeout: REGISTRATION_MS }) await agreeToTerms(page) diff --git a/webapp/e2e/contract.spec.ts b/webapp/e2e/contract.spec.ts index 74fbe6f2..c5683ba4 100644 --- a/webapp/e2e/contract.spec.ts +++ b/webapp/e2e/contract.spec.ts @@ -4,13 +4,13 @@ import { expect, type APIRequestContext } from "@playwright/test" import type { Hex } from "viem" import { CODE_LIMIT } from "../dev/mock/limits.ts" import * as api from "../src/api.ts" -import { namesSite, readSite } from "../src/config.ts" +import { LOCAL } from "../src/config.ts" import { CHANNEL_KEY, CONTACT_KEY, labelHash, namehash, setTextDigest, YEAR_S } from "../src/crypto/registration.ts" import { checksumAddress, fromHex, hex, personalDigest, signDigest } from "../src/crypto/wallet.ts" import * as flow from "../src/flow.ts" import * as store from "../src/store.ts" import { - acceptedOnChain, channelLink, COMMUNITY_TERMS, COMMUNITY_TERMS_HASH, contactLink, control, GENERAL_TERMS_HASH, LISTED_TERMS, MOCK, NAME_POLICY, newClient, oracleQuote, ownerSetsResolver, ownerSetsText, + acceptedOnChain, ALTERNATE_COMMUNITY_TERMS, ALTERNATE_GENERAL_TERMS, channelLink, COMMUNITY_TERMS, COMMUNITY_TERMS_HASH, contactLink, control, GENERAL_TERMS_HASH, LISTED_TERMS, MOCK, NAME_POLICY, newClient, oracleQuote, ownerSetsResolver, ownerSetsText, PLAIN_TERMS, relayedAhead, TERMS, test, textChangesOf, uniqueLabel, } from "./helpers.ts" @@ -34,9 +34,35 @@ async function send(method: string, path: string, body?: unknown): Promise() +const orderOwners = new Map() +const ORDER_ROUTE = /^\/api\/(invoice|registration)\/([^/?]+)(?:\/(cancel|retry|reveal))?(?:\?|$)/ + +function noteOrders(json: Json, body: unknown): void { + const sent = (body as { order?: { owner?: unknown } } | undefined)?.order?.owner + if (typeof json.registrationId === "string" && typeof sent === "string") orderOwners.set(json.registrationId, sent) + const reg = (json.registration ?? json) as Json + if (typeof reg.id !== "string" || typeof reg.owner !== "string") return + orderOwners.set(reg.id, reg.owner) + if (typeof json.invoiceId === "string") orderOwners.set(json.invoiceId, reg.owner) +} + +function signed(method: string, path: string, body: unknown): { path: string; body: unknown } { + const m = ORDER_ROUTE.exec(path) + const kept = m ? store.orderByInvoice(m[2]) ?? store.orderByRegistration(m[2]) : undefined + const code = m && m[2] !== "find" ? ownerCodes.get(orderOwners.get(m[2]) ?? "") ?? kept?.ownerCode : undefined + if (!m || !code) return { path, body } + const proof = flow.orderSigner({ ownerCode: code })(m[2], (m[3] ?? "read") as api.OrderAction) + if (method === "GET") return { path: `${path}${path.includes("?") ? "&" : "?"}timestamp=${proof.timestamp}&signature=${proof.signature}`, body } + return { path, body: m[3] === "reveal" ? { ...body as Json, request: proof } : { ...body as Json, ...proof } } +} + async function call(method: string, path: string, body?: unknown): Promise<{ status: number; json: Json }> { - const res = await send(method, path, body) - return { status: res.status, json: await res.json() as Json } + const request = signed(method, path, body) + const res = await send(method, request.path, request.body) + const json = await res.json() as Json + noteOrders(json, body) + return { status: res.status, json } } const TERM_START = Date.UTC(2027, 0, 1) / 1000 @@ -58,13 +84,15 @@ async function quote(label: string): Promise { async function draftOf(label: string, links = { contact: "", channel: "" }, method: flow.Draft["method"] = "btc"): Promise { const q = await quote(label) - return { label, links, chain: flow.chainOf(readSite()), years: q.years, termStart: readSite().termStart, ownerCode: flow.newOwnerCode(), terms: api.currentTerms(q), method } + const ownerCode = flow.newOwnerCode() + ownerCodes.set(checksumAddress(flow.walletOf(ownerCode)!.address), ownerCode) + return { label, links, years: q.years, ownerCode, terms: api.currentTerms(q), method } } // a name selected for the order, under the terms the service has for that name now or `terms` async function selectionOf(record: store.OrderRecord, to: string, terms?: string, method = record.method): Promise { const q = await quote(to) - const draft: flow.Draft = { label: to, links: NO_LINKS, chain: flow.chainOf(readSite()), years: api.termYears(q.community, record.years), termStart: readSite().termStart, ownerCode: record.ownerCode, + const draft: flow.Draft = { label: to, links: NO_LINKS, years: api.termYears(q.community, record.years), ownerCode: record.ownerCode, terms: terms ?? api.currentTerms(q), method } return flow.selectName(record, draft, await flow.orderRequest(draft)) } @@ -132,7 +160,7 @@ function withAcceptance(view: api.RegistrationView, acceptance: api.Acceptance): return { ...view, phase: { ...committed, signature: { type: "awaiting", toSign: { ...toSign, acceptance } } } } } -async function unacceptedReveal(view: api.RegistrationView, record: store.OrderRecord): Promise { +async function revealBodyOf(view: api.RegistrationView, record: store.OrderRecord): Promise { const sending = globalThis.fetch let body: Json = {} globalThis.fetch = async (_, init) => { @@ -140,14 +168,21 @@ async function unacceptedReveal(view: api.RegistrationView, record: store.OrderR return new Response("{}", { status: 200 }) } try { - await flow.revealOrder(view, record) + await flow.revealOrder(view, record, record.terms) } finally { globalThis.fetch = sending } + return body +} + +async function unacceptedReveal(view: api.RegistrationView, record: store.OrderRecord): Promise { + const body = await revealBodyOf(view, record) delete body.acceptance return body } +const acceptedAs = (acceptance: api.Acceptance) => api.signedTermsOf({ communityName: acceptance.community, termsHash: acceptance.termsHash }) + // The order with a register the service then fails. async function failAtRegister(request: APIRequestContext, id: string): Promise { await control(request, `fail/${id}`) @@ -220,7 +255,7 @@ test("an order refuses a wrong signer, a stale timestamp, free days off the term const q = await quote(label) const { request } = await flow.orderRequest(draft) const stranger = flow.newOwnerCode() - const off = (await flow.orderRequest({ ...draft, termStart: draft.termStart + TERM_SLACK_S + 100 })).request + const off = await signedAt(draft.ownerCode, { ...request, duration: request.duration + TERM_SLACK_S + 100 }, request.timestamp) const refusals: [string, api.SignedOrder, number, Json][] = [ ["another key's signature", await signedAt(stranger, request, request.timestamp), 400, { type: "bad_request" }], ["a timestamp past the window", await signedAt(draft.ownerCode, request, request.timestamp - SIGNED_WINDOW_S - 100), 400, { type: "bad_request" }], @@ -326,7 +361,7 @@ test("a code order closes an overdue invoice of its wallet and name with nothing test("search quotes the oracle with the term's start, and a registered name carries its grace period", async () => { const label = uniqueLabel("cq") const answer = await quote(label) - expect([answer.price, answer.years, (await namesSite()).termStart]).toEqual([await oracleQuote(label, 2), 2, TERM_START]) + expect([answer.price, answer.years, LOCAL.termStart]).toEqual([await oracleQuote(label, 2), 2, TERM_START]) for (const [length, cents] of [[6, 40000], [7, 20000], [12, 10000]]) { const res = await call("GET", `/api/name/${hex(labelHash("x".repeat(length)))}?length=${length}`) expect((res.json.found as Json).price, `${length} letters`).toBe(cents) @@ -439,7 +474,8 @@ test("a name is selected only for a paid order taken first, at its own price, ag await untilPhase(id, ["committed"]) await expect(select(shortLabel(7)), "a committed order").rejects.toMatchObject({ code: "bad_request" }) await control(request, "take", { label }) - await flow.revealOrder(await untilRevealable(id), store.orderByRegistration(id)!) + const record = store.orderByRegistration(id)! + await flow.revealOrder(await untilRevealable(id), record, record.terms) await untilPhase(id, ["taken"]) await expect(select(shortLabel(6)), "a dearer name").rejects.toMatchObject({ code: "catalog_changed", body: { price: PRICE.six } }) await expect(select(uniqueLabel("cm")), "a cheaper name").rejects.toMatchObject({ code: "catalog_changed", body: { price: PRICE.long } }) @@ -490,7 +526,8 @@ async function nameBody(record: store.OrderRecord, view: api.RegistrationView, t const sealedHash = hex(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(view.sealed)))) const length = record.label.length const message = `simplex.domains name ${view.id} ${view.labelHash} ${length} ${view.duration} ${view.commitment} ${sealedHash} ${terms} ${timestamp}` - const reveal = await flow.revealFor(record, view.duration, await api.signFor(view.labelHash, view.owner)) + const toSign = await api.signFor(view.labelHash, view.owner) + const reveal = flow.revealFor(record, view, toSign, acceptedAs(toSign.acceptance)) return { ...api.signedFields({ labelHash: view.labelHash, length, duration: view.duration, commitment: view.commitment, sealed: view.sealed, terms, timestamp, signature: hex(signDigest(flow.walletOf(record.ownerCode)!.privateKey, personalDigest(message))) }), reveal } as unknown as Json } @@ -509,7 +546,7 @@ type LinkEdit = { key: "contact" | "channel"; value: string; nonce: number; dead // one edit of a link of the name, signed by its key at this records nonce function linkEdit(name: RegisteredName, key: LinkEdit["key"], value: string, nonce: number): LinkEdit { const deadline = Math.floor(Date.now() / 1000) + 3600 - const digest = setTextDigest(BigInt(name.draft.chain.chainId), fromHex(name.draft.chain.resolver), namehash("simplex", name.label), flow.KEYS[key], value, BigInt(nonce), BigInt(deadline)) + const digest = setTextDigest(BigInt(LOCAL.chainId), fromHex(LOCAL.resolver), namehash("simplex", name.label), flow.KEYS[key], value, BigInt(nonce), BigInt(deadline)) return { key, value, nonce, deadline, signature: hex(signDigest(flow.walletOf(name.draft.ownerCode)!.privateKey, digest)) } } @@ -578,7 +615,7 @@ test("a link edit of a name pointed at another resolver is bad_request, and goes const edit = await contactEdit(name, contactLink("Cg")) await ownerSetsResolver(name.draft.ownerCode, name.label, ELSEWHERE) expect(await call("POST", "/api/name/records", edit)).toEqual({ status: 400, json: { type: "bad_request" } }) - await ownerSetsResolver(name.draft.ownerCode, name.label, name.draft.chain.resolver as Hex) + await ownerSetsResolver(name.draft.ownerCode, name.label, LOCAL.resolver as Hex) const sent = await call("POST", "/api/name/records", edit) expect(sent.status, JSON.stringify(sent.json)).toBe(200) }) @@ -869,7 +906,7 @@ test("an order signs the terms of its name's kind: the other kind or other terms const res = await call("POST", "/api/invoice", { ...body, order: { ...body.order, fields: { ...body.order.fields, terms } } }) expect([res.status, res.json], JSON.stringify(terms)).toEqual([400, { type: "bad_request" }]) } - await withTerms(request, "general-terms", `the general terms, changed for ${label}`, async (terms) => { + await withTerms(request, "general-terms", ALTERNATE_GENERAL_TERMS, async (terms) => { // a stale timestamp is checked before the terms const stale = await signedAt(draft.ownerCode, signed, signed.timestamp - SIGNED_WINDOW_S - 100) expect((await call("POST", "/api/invoice", invoiceBody(stale, "btc", q.price))).json, "a stale timestamp").toEqual({ type: "bad_request" }) @@ -888,7 +925,7 @@ test("an exact resend is answered after the terms changed, and two orders differ const built = await flow.orderRequest(draft) const first = await call("POST", "/api/invoice", invoiceBody(built.request, "btc", q.price)) expect(first.status).toBe(200) - await withTerms(request, "general-terms", `the general terms, changed for ${label}`, async (terms) => { + await withTerms(request, "general-terms", ALTERNATE_GENERAL_TERMS, async (terms) => { const again = await call("POST", "/api/invoice", invoiceBody(built.request, "btc", q.price)) expect([again.status, again.json.invoiceId]).toEqual([200, first.json.invoiceId]) const other = await signedAt(draft.ownerCode, { ...built.request, terms: terms.hash.slice(2) }, built.request.timestamp) @@ -919,7 +956,7 @@ test("a selection signs the new name's terms: a community name needs the communi const repeat = await call("POST", `/api/registration/${id}/name`, await nameBody(record, selected)) expect([repeat.status, repeat.json.version], "a repeat answers the view unchanged").toEqual([200, (await viewOf(id)).version]) const taken = await untilPhase(id, ["taken"]) - await withTerms(request, "community-terms", `the community terms, changed for ${label}`, async () => { + await withTerms(request, "community-terms", ALTERNATE_COMMUNITY_TERMS, async () => { // the current fields under the terms they were signed with are still a repeat, answered before the terms const again = await call("POST", `/api/registration/${id}/name`, await nameBody(record, taken)) expect([again.status, (again.json.phase as Json).type]).toEqual([200, "taken"]) @@ -927,7 +964,7 @@ test("a selection signs the new name's terms: a community name needs the communi }) }) -test("a committed community name's view asks for the owner's acceptance of the community terms on chain; its reveal without one, or with one for another nonce, terms, kind or policy, is bad_request, and with it the register records it", async ({ request }) => { +test("a committed community name's view asks for the owner's acceptance of the community terms on chain; its reveal without one, or with one for another nonce, terms or kind, is bad_request, and with it the register records it", async ({ request }) => { const label = uniqueLabel("tk") await listed(request, label, async () => { const { draft, built, id } = await codeOrder(request, label) @@ -937,11 +974,11 @@ test("a committed community name's view asks for the owner's acceptance of the c const accept = acceptanceOf(view) expect(accept).toEqual({ community: true, policy: NAME_POLICY, termsHash: COMMUNITY_TERMS_HASH, nonce: 0 }) expect(await call("POST", `/api/registration/${id}/reveal`, await unacceptedReveal(view, record)), "none").toEqual({ status: 400, json: { type: "bad_request" } }) - for (const [what, acceptance] of [["another nonce", { ...accept, nonce: accept.nonce + 1 }], ["other terms", { ...accept, termsHash: `0x${"d8".repeat(32)}` }], - ["the other kind", { ...accept, community: false }], ["another policy", { ...accept, policy: readSite().sponsor }]] as const) { - await expect(flow.revealOrder(withAcceptance(view, acceptance), record), what).rejects.toMatchObject({ code: "bad_request" }) + for (const [what, acceptance] of [["another nonce", { ...accept, nonce: accept.nonce + 1 }], ["other terms", { ...accept, termsHash: LOCAL.communityTerms[1].hash }], + ["the other kind", { ...accept, community: false, termsHash: GENERAL_TERMS_HASH }]] as const) { + await expect(flow.revealOrder(withAcceptance(view, acceptance), record, acceptedAs(acceptance)), what).rejects.toMatchObject({ code: "bad_request" }) } - await flow.revealOrder(view, record) + await flow.revealOrder(view, record, record.terms) const done = await untilPhase(id, ["registered"]) expect(api.toSignOf(done), "no acceptance asked once registered").toBeNull() expect(await acceptedOnChain(done.registerTx!)).toEqual({ kind: "community", name: label, holder: record.owner, termsHash: COMMUNITY_TERMS_HASH }) @@ -955,8 +992,9 @@ test("a plain name's committed view asks for the owner's acceptance of the gener const view = await signAgain(request, id) expect(acceptanceOf(view)).toEqual({ community: false, policy: NAME_POLICY, termsHash: GENERAL_TERMS_HASH, nonce: 0 }) expect(await call("POST", `/api/registration/${id}/reveal`, await unacceptedReveal(view, record)), "none").toEqual({ status: 400, json: { type: "bad_request" } }) - await expect(flow.revealOrder(withAcceptance(view, { ...acceptanceOf(view), community: true }), record), "the other kind").rejects.toMatchObject({ code: "bad_request" }) - await flow.revealOrder(view, record) + const otherKind = { ...acceptanceOf(view), community: true, termsHash: COMMUNITY_TERMS_HASH } + await expect(flow.revealOrder(withAcceptance(view, otherKind), record, acceptedAs(otherKind)), "the other kind").rejects.toMatchObject({ code: "bad_request" }) + await flow.revealOrder(view, record, record.terms) const done = await untilPhase(id, ["registered"]) expect(await acceptedOnChain(done.registerTx!)).toEqual({ kind: "general", name: label, holder: record.owner, termsHash: GENERAL_TERMS_HASH }) }) @@ -993,8 +1031,25 @@ test("a reveal signed over other dispute days than its order's payment's is bad_ const { draft, built, id } = await codeOrder(request, uniqueLabel("tu")) const recordAs = (method: store.OrderRecord["method"]) => flow.recordFor(draft, built, method, 0, { registrationId: id, invoiceId: null }) const view = await signAgain(request, id) - await expect(flow.revealOrder(view, recordAs("card")), "a card's days for a code order").rejects.toMatchObject({ code: "bad_request" }) - await flow.revealOrder(view, recordAs("code")) + await expect(flow.revealOrder(view, recordAs("card"), draft.terms), "a card's days for a code order").rejects.toMatchObject({ code: "bad_request" }) + await flow.revealOrder(view, recordAs("code"), draft.terms) + await untilPhase(id, ["registered"]) +}) + +test("a reveal without its order request signed by the order's name key, or by another key, is not_found, one signed too long ago bad_request, and the signed one registers the name", async ({ request }) => { + const { draft, built, id } = await codeOrder(request, uniqueLabel("rq")) + const record = flow.recordFor(draft, built, "code", 0, { registrationId: id, invoiceId: null }) + const view = await signAgain(request, id) + const unsigned = await revealBodyOf(view, record) + delete unsigned.request + const path = `/api/registration/${id}/reveal` + expect((await send("POST", path, unsigned)).status, "unsigned").toBe(404) + const other = flow.orderSigner({ ownerCode: flow.newOwnerCode() })(id, "reveal") + expect((await send("POST", path, { ...unsigned, request: other })).status, "another key").toBe(404) + const old = Math.floor(Date.now() / 1000) - 2 * SIGNED_WINDOW_S + const stale = { timestamp: old, signature: hex(signDigest(flow.walletOf(draft.ownerCode)!.privateKey, personalDigest(`simplex.domains order ${id} reveal ${old}`))) } + expect((await send("POST", path, { ...unsigned, request: stale })).status, "signed too long ago").toBe(400) + await flow.revealOrder(view, record, draft.terms) await untilPhase(id, ["registered"]) }) diff --git a/webapp/e2e/deployment.spec.ts b/webapp/e2e/deployment.spec.ts new file mode 100644 index 00000000..172d78bd --- /dev/null +++ b/webapp/e2e/deployment.spec.ts @@ -0,0 +1,142 @@ +import { expect, type APIRequestContext, type Page } from "@playwright/test" +import { heldPrice } from "../src/config.ts" +import { dollars } from "../src/format.ts" +import { REVEAL_ATTEMPTS } from "../src/screens/order.ts" +import { + control, MOCK, mockRegistration, onStep, orderedAtMock, payButton, REGISTRATION_MS, registrationOf, restoreOrder, search, startOrder, test, toReview, uniqueLabel, useCode, waitRegistered, +} from "./helpers.ts" + +const NOT_NOW = "Names can't be ordered right now. Please try again later." +const UNCHECKED = "Sorry, the payment details of this order could not be checked, so they are not shown. Please contact support with the order reference." +const SUPPORT_COPY = "Copy the order reference and address proof for support" +const COIN = { btc: "Bitcoin", xmr: "Monero" } as const +const UNHELD_TERMS = "# SimpleX Names Conditions of Use\n\nNot the terms the page holds.\n" + +async function mismatched(request: APIRequestContext, mismatch: Record, f: () => Promise): Promise { + await control(request, "mismatch", mismatch) + try { + return await f() + } finally { + await control(request, "mismatch", {}) + } +} + +async function notOrderable(page: Page, label: string): Promise { + await search(page, label) + await expect(onStep(page).locator(".answer .line", { hasText: NOT_NOW })).toBeVisible() + await expect(onStep(page).getByRole("button", { name: "Register" })).toBeDisabled() +} + +test("a name whose search answers a price below or above the one the page holds can't be ordered, and shows the held price, unless a code registers it", async ({ page, request }) => { + const label = uniqueLabel("price") + const held = heldPrice(label.length) + for (const price of [held - 5000, held + 5000]) { + await mismatched(request, { price }, async () => { + await notOrderable(page, label) + await expect(onStep(page).locator(".answer .price")).toHaveText(dollars(held)) + }) + } + const { code } = await control(request, "code", { minLength: 6 }) as { code: string } + await useCode(page, code) + await mismatched(request, { price: held + 5000 }, async () => { + await search(page, label) + await expect(onStep(page).locator(".answer .price")).toHaveText("Free") + await expect(onStep(page).getByRole("button", { name: "Register" })).toBeEnabled() + await expect(onStep(page).locator(".answer .line", { hasText: NOT_NOW })).toHaveCount(0) + }) +}) + +test("a name whose terms on chain are not the terms the page holds can't be ordered", async ({ page, request }) => { + await control(request, "general-terms", { text: UNHELD_TERMS }) + try { + await notOrderable(page, uniqueLabel("terms")) + } finally { + await control(request, "general-terms", { text: null }) + } +}) + +for (const [what, mismatch] of [["under another policy", { policy: true }], ["of other terms", { termsHash: true }]] as const) { + test(`an order whose sign answer asks for the acceptance ${what} is not sent, and Check your order says names can't be ordered now`, async ({ page, request }) => { + const label = uniqueLabel("sign") + await search(page, label) + await toReview(page) + await mismatched(request, mismatch, async () => { + await payButton(page).click() + await expect(onStep(page).getByRole("heading", { name: "Names can't be ordered right now" })).toBeVisible() + }) + expect(await orderedAtMock(request, label), "no order made").toBe(false) + }) +} + +test("an open invoice of another payment than its order asked for is drawn without its payment details, which could not be checked", async ({ page, request }) => { + await mismatched(request, { method: true }, () => startOrder(page, uniqueLabel("method"), { method: "btc" })) + await expect(onStep(page).getByText(UNCHECKED)).toBeVisible() + await expect(onStep(page).getByText("Monero address")).toHaveCount(0) + await expect(onStep(page).locator(".qr")).toHaveCount(0) +}) + +for (const [what, mismatch] of [["an address of a key the page does not hold", (method: string) => ({ address: method })], ["an amount other than its name's price", () => ({ amount: true })]] as const) { + for (const method of ["btc", "xmr"] as const) { + test(`an open ${COIN[method]} invoice with ${what} is drawn without its payment details, which could not be checked`, async ({ page, request }) => { + await mismatched(request, mismatch(method), () => startOrder(page, uniqueLabel("payee"), { method })) + await expect(onStep(page).getByText(UNCHECKED)).toBeVisible() + await expect(onStep(page).getByText(`${COIN[method]} address`)).toHaveCount(0) + await expect(onStep(page).locator(".qr")).toHaveCount(0) + }) + } +} + +test("an order's page gives support its address proof with its reference, as the service sent it, also when the address could not be checked", async ({ page, context, request, browserName }) => { + test.skip(browserName !== "chromium", "reads the clipboard, which Playwright grants in Chromium") + await context.grantPermissions(["clipboard-read", "clipboard-write"]) + const { invoiceId } = await mismatched(request, { address: "xmr" }, () => startOrder(page, uniqueLabel("proof"), { method: "xmr" })) + await expect(onStep(page).getByText(UNCHECKED)).toBeVisible() + const { addressProof } = await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { addressProof: unknown } + await onStep(page).getByRole("button", { name: SUPPORT_COPY }).click() + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(`Order reference ${invoiceId}, address proof ${JSON.stringify(addressProof)}`) + await control(request, `expire/${invoiceId}`) + await expect(onStep(page).getByRole("heading", { name: "Invoice closed" })).toBeVisible() + await expect(onStep(page).getByRole("button", { name: SUPPORT_COPY }), "the closed invoice's page").toBeVisible() +}) + +test("a card order reopened with its name code in another browser signs its reveal over a card's dispute days, whatever payment the service reports", async ({ page, browser, request }) => { + const label = uniqueLabel("sealed") + const { invoiceId, ownerCode } = await mismatched(request, { method: true }, () => startOrder(page, label, { method: "card" })) + await page.goto("about:blank") + await control(request, `stale/${await registrationOf(request, invoiceId)}`) + await control(request, `settle/${invoiceId}`) + await expect.poll(async () => { + const { phase, label: revealed } = await mockRegistration(request, invoiceId) + return phase === "committed" && revealed === null + }, { timeout: REGISTRATION_MS }).toBe(true) + const elsewhere = await (await browser.newContext()).newPage() + await restoreOrder(elsewhere, ownerCode, label) + await waitRegistered(elsewhere, label) +}) + +test("a committed order whose view asks for the acceptance under another policy is not signed, and after three tries its page says the name could not be signed", async ({ page, request }) => { + const label = uniqueLabel("reveal") + const { invoiceId } = await startOrder(page, label, { method: "btc" }) + const reveals: string[] = [] + page.on("request", (r) => { if (r.method() === "POST" && /\/api\/registration\/[^/]+\/reveal$/.test(new URL(r.url()).pathname)) reveals.push(r.url()) }) + await control(request, `stale/${await registrationOf(request, invoiceId)}`) + await mismatched(request, { policy: true }, async () => { + await control(request, `settle/${invoiceId}`) + await expect(onStep(page).getByText("The name could not be signed")).toBeVisible({ timeout: REGISTRATION_MS }) + expect(reveals, "no reveal sent").toEqual([]) + expect((await mockRegistration(request, invoiceId)).label, "no reveal recorded").toBeNull() + }) +}) + +test("a committed order whose reveal the service answers as another signer's, not_found, says after three tries that the name could not be signed", async ({ page, request }) => { + const { invoiceId } = await startOrder(page, uniqueLabel("signer"), { method: "btc" }) + let reveals = 0 + await page.route("**/api/registration/*/reveal", (route) => { + reveals += 1 + return route.fulfill({ status: 404, json: { type: "not_found" } }) + }) + await control(request, `stale/${await registrationOf(request, invoiceId)}`) + await control(request, `settle/${invoiceId}`) + await expect(onStep(page).getByText("The name could not be signed")).toBeVisible({ timeout: REGISTRATION_MS }) + expect(reveals).toBe(REVEAL_ATTEMPTS) +}) diff --git a/webapp/e2e/downtime.spec.ts b/webapp/e2e/downtime.spec.ts new file mode 100644 index 00000000..7c0c609f --- /dev/null +++ b/webapp/e2e/downtime.spec.ts @@ -0,0 +1,155 @@ +import { expect, type APIRequestContext, type Page } from "@playwright/test" +import { + AGREE, agreeToTerms, ALTERNATE_GENERAL_TERMS, CHECKOUT_KEY, control, loads, mockRegistration, onStep, orderedAtMock, payButton, REGISTRATION_MS, registrationOf, search, startOrder, takenOrder, + test, toFullReview, toReview, uniqueLabel, waitRegistered, +} from "./helpers.ts" + +const RELOAD_MS = 1000 +const NEW_ORDERS = "You will be able to order names again soon" +const UNSIGNED_MS = 15_000 + +const becomeVisible = (page: Page) => page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))) +const configRead = (page: Page) => page.waitForResponse((r) => new URL(r.url()).pathname === "/api/config") +const readOnView = (page: Page) => Promise.all([configRead(page), becomeVisible(page)]) +const reloadedOnView = (page: Page) => Promise.all([page.waitForEvent("load"), becomeVisible(page)]) + +async function inDowntime(page: Page, downtime: boolean): Promise { + await page.unroute("**/api/config") + await page.route("**/api/config", (route) => route.fulfill({ json: { stripePublishableKey: null, names: { downtime } } })) +} + +async function serviceInDowntime(request: APIRequestContext, f: () => Promise): Promise { + await control(request, "downtime", { on: true }) + try { + return await f() + } finally { + await control(request, "downtime", { on: false }) + } +} + +const checkoutKept = (page: Page) => page.evaluate((key) => { + const { label, contact, channel, ownerCode, saved, agreed, step } = JSON.parse(sessionStorage.getItem(key)!) + return { label, contact, channel, ownerCode, saved, agreed, step } +}, CHECKOUT_KEY) + +test("a checkout open as a downtime ends loads again with its name, links, name code and terms", async ({ page }) => { + await toFullReview(page, uniqueLabel("keep")) + await page.getByRole("radio", { name: "Bitcoin" }).click() + const before = await checkoutKept(page) + expect(before.agreed && before.saved && before.contact && before.channel).toBeTruthy() + await inDowntime(page, true) + await readOnView(page) + await inDowntime(page, false) + await reloadedOnView(page) + await expect(onStep(page).getByRole("heading", { name: "Check your order" })).toBeVisible() + expect(await checkoutKept(page)).toEqual(before) + await expect(onStep(page).getByRole("checkbox", { name: AGREE })).toBeChecked() + await expect(payButton(page)).toBeEnabled() +}) + +test("an order's page open as a downtime ends loads again with its invoice, and registers", async ({ page, request }) => { + const label = uniqueLabel("paid") + const { invoiceId } = await startOrder(page, label, { method: "btc" }) + await inDowntime(page, true) + await readOnView(page) + await inDowntime(page, false) + await reloadedOnView(page) + await expect(page).toHaveURL(new RegExp(`order=${invoiceId}`)) + await control(request, `settle/${invoiceId}`) + await waitRegistered(page, label) +}) + +test("a page loaded in a downtime loads again as it ends, and only then", async ({ page }) => { + await inDowntime(page, true) + await page.goto("/") + await expect(page.getByLabel("Name", { exact: true })).toBeVisible() + const seen = loads(page) + await readOnView(page) + await page.waitForTimeout(RELOAD_MS) + expect(seen.count, "still in the downtime").toBe(0) + await inDowntime(page, false) + await reloadedOnView(page) + await readOnView(page) + await page.waitForTimeout(RELOAD_MS) + expect(seen.count, "loaded once, as the downtime ended").toBe(1) +}) + +test("a closed invoice's page holding changed terms ticked again stays as a downtime ends, until the reader leaves it", async ({ page, request }) => { + const { invoiceId } = await startOrder(page, uniqueLabel("tick"), { method: "btc" }) + await control(request, `expire/${invoiceId}`) + await expect(onStep(page).getByRole("heading", { name: "Invoice closed" })).toBeVisible() + await control(request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) + try { + await onStep(page).getByRole("button", { name: "Get a new invoice" }).click() + await agreeToTerms(page) + await inDowntime(page, true) + await readOnView(page) + await inDowntime(page, false) + const seen = loads(page) + await readOnView(page) + await page.waitForTimeout(RELOAD_MS) + expect(seen.count, "the tick is in the page only, so the page stays").toBe(0) + await expect(onStep(page).getByRole("checkbox", { name: AGREE })).toBeChecked() + await page.locator("body > header").getByRole("link", { name: "Check your code" }).click() + await expect(onStep(page).getByRole("heading", { name: "Check your code" })).toBeVisible() + await expect.poll(() => seen.count, "the next screen is the page loaded again").toBe(1) + } finally { + await control(request, "general-terms", { text: null }) + } +}) + +test("in the service's downtime the home says new orders open again soon and offers no Register, and Check your order says so, with no order made", async ({ page, request }) => { + const label = uniqueLabel("down") + await search(page, label) + await toReview(page) + await serviceInDowntime(request, async () => { + await payButton(page).click() + await expect(onStep(page).getByRole("heading", { name: NEW_ORDERS })).toBeVisible() + await search(page, label) + await expect(onStep(page).locator(".answer .line", { hasText: `${NEW_ORDERS}.` })).toBeVisible() + await expect(onStep(page).locator(".answer .row")).toBeVisible() + await expect(onStep(page).getByRole("button", { name: "Register" })).toHaveCount(0) + }) + expect(await orderedAtMock(request, label), "no order made").toBe(false) +}) + +test("in the service's downtime a taken order's search for another name offers no Register, and the order stays taken", async ({ page, request }) => { + const { invoiceId } = await takenOrder(page, request, uniqueLabel("dtk")) + await serviceInDowntime(request, async () => { + await page.reload() + await onStep(page).getByRole("button", { name: "Choose another name" }).click() + await page.getByLabel("Name", { exact: true }).fill(uniqueLabel("dtn")) + await page.getByLabel("Name", { exact: true }).press("Enter") + await expect(onStep(page).locator(".answer .row")).toBeVisible() + await expect(onStep(page).getByRole("button", { name: "Register" })).toHaveCount(0) + }) + expect((await mockRegistration(request, invoiceId)).phase).toBe("taken") +}) + +test("an open invoice's page in the service's downtime withholds its payment details, and shows them once the downtime is over", async ({ page, request }) => { + await startOrder(page, uniqueLabel("dpay"), { method: "btc" }) + const address = onStep(page).getByText("Bitcoin address") + await expect(address).toBeVisible() + await serviceInDowntime(request, async () => { + await page.reload() + await expect(onStep(page).getByText("You will be able to pay again soon.")).toBeVisible() + await expect(address).toHaveCount(0) + await expect(onStep(page).locator(".qr")).toHaveCount(0) + }) + await expect(address).toBeVisible({ timeout: REGISTRATION_MS }) +}) + +test("a committed order signs no reveal in the service's downtime, and is signed and registered once the downtime is over", async ({ page, request }) => { + const label = uniqueLabel("drev") + const { invoiceId } = await startOrder(page, label, { method: "btc" }) + await control(request, `stale/${await registrationOf(request, invoiceId)}`) + await serviceInDowntime(request, async () => { + await page.reload() + await control(request, `settle/${invoiceId}`) + await expect.poll(async () => (await mockRegistration(request, invoiceId)).phase, { timeout: REGISTRATION_MS }).toBe("committed") + await page.waitForTimeout(UNSIGNED_MS) + expect((await mockRegistration(request, invoiceId)).label, "no reveal in the downtime").toBeNull() + await expect(onStep(page).getByText("The registration is not signed yet.")).toBeVisible() + }) + await waitRegistered(page, label) +}) diff --git a/webapp/e2e/focus.spec.ts b/webapp/e2e/focus.spec.ts index 8ad89ee7..f8a6cc36 100644 --- a/webapp/e2e/focus.spec.ts +++ b/webapp/e2e/focus.spec.ts @@ -12,7 +12,7 @@ const DRAWN_BEFORE = "data-drawn-before" // The screen in view is marked, and the redraw puts a new one in its place. async function drawnAgain(page: Page, invoiceId: string, redraw: () => Promise): Promise { await onStep(page).evaluate((n, mark) => n.setAttribute(mark, ""), DRAWN_BEFORE) - const read = page.waitForResponse((r) => new URL(r.url()).pathname === `/api/invoice/${invoiceId}` && !r.url().includes("?")) + const read = page.waitForResponse((r) => new URL(r.url()).pathname === `/api/invoice/${invoiceId}` && !new URL(r.url()).searchParams.has("wait")) await redraw() await read await expect(page.locator("main[aria-busy]")).toHaveCount(0) diff --git a/webapp/e2e/frames.spec.ts b/webapp/e2e/frames.spec.ts index 38baf3f2..5440be2a 100644 --- a/webapp/e2e/frames.spec.ts +++ b/webapp/e2e/frames.spec.ts @@ -1,6 +1,6 @@ import { expect, type Page } from "@playwright/test" import { - agreeToTerms, CODE_HEADING, contactLink, control, LINKS_HEADING, okPreview, onStep, payButton, recordedFrames, recordFrames, REGISTRATION_MS, SAVED, search, startOrder, + agreeToTerms, ALTERNATE_GENERAL_TERMS, CODE_HEADING, contactLink, control, LINKS_HEADING, okPreview, onStep, payButton, recordedFrames, recordFrames, REGISTRATION_MS, SAVED, search, startOrder, takenHeading, test, toFullReview, toReview, uniqueLabel, } from "./helpers.ts" @@ -143,7 +143,7 @@ test("a name taken first, its search for another name and Your names swap withou test("terms changed while ordering show their notice without a near-empty frame", async ({ page, request }) => { await search(page, uniqueLabel("frterms")) await toReview(page) - await control(request, "general-terms", { text: "# SimpleX general terms\n\nChanged while ordering.\n" }) + await control(request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) try { await expectNoEmptyFrame(page, "review to its terms notice", async () => { await payButton(page).click() diff --git a/webapp/e2e/helpers.ts b/webapp/e2e/helpers.ts index b5bbf5f9..51c1e583 100644 --- a/webapp/e2e/helpers.ts +++ b/webapp/e2e/helpers.ts @@ -1,20 +1,24 @@ -import { expect, test as base, type APIRequestContext, type Browser, type BrowserContext, type BrowserContextOptions, type Locator, type Page } from "@playwright/test" +import { expect, test as base, type APIRequestContext, type Browser, type BrowserContext, type BrowserContextOptions, type Frame, type Locator, type Page } from "@playwright/test" import { randomInt } from "node:crypto" import { mkdirSync, readFileSync } from "node:fs" import { createPublicClient, createTestClient, createWalletClient, encodeFunctionData, http, namehash, parseAbi, parseEventLogs, toFunctionSelector, type Hex } from "viem" import { generatePrivateKey, privateKeyToAccount } from "viem/accounts" import { foundry } from "viem/chains" +import { LOCAL } from "../src/config.ts" import { labelHash, YEAR_S } from "../src/crypto/registration.ts" import { checksumAddress, hex } from "../src/crypto/wallet.ts" import { KEYS, newOwnerCode, walletOf } from "../src/flow.ts" import { readQr } from "../src/scan.ts" import { qrPixels } from "../test/qr-image.ts" -import { mockUrl, pageUrl } from "./slots.ts" +import { codesPageUrl, mockUrl, pageUrl } from "./slots.ts" + +export { ALTERNATE_COMMUNITY_TERMS, ALTERNATE_GENERAL_TERMS } from "./terms.ts" const SCREENSHOTS = process.env.SCREENSHOTS_DIR ?? "screenshots" const TAKE_SHOTS = process.env.SHOTS === "1" const SLOT = Number(process.env.TEST_PARALLEL_INDEX ?? "0") export const MOCK = process.env.MOCK_URL ?? mockUrl(SLOT) +export const CODES_PAGE = codesPageUrl(SLOT) const DESKTOP = { width: 1280, height: 800 } const PHONE = { width: 390, height: 844 } // the sizes a page must fit without scrolling, a laptop's and a phone's @@ -43,7 +47,7 @@ export async function control(request: APIRequestContext, path: string, body: Re } export async function registrationOf(request: APIRequestContext, invoiceId: string): Promise { - const res = await request.get(`${MOCK}/api/invoice/${invoiceId}`) + const res = await request.get(`${MOCK}/control/invoice/${invoiceId}`) return (await res.json()).registration.id } @@ -55,6 +59,11 @@ export async function mockRegistration(request: APIRequestContext, invoiceId: st return registrations.find((r) => r.invoiceId === invoiceId)! } +export async function orderedAtMock(request: APIRequestContext, label: string): Promise { + const { registrations } = await (await request.get(`${MOCK}/control/state`)).json() as { registrations: { labelHash: string }[] } + return registrations.some((r) => r.labelHash === hex(labelHash(label))) +} + // The worker's chain, read directly: the expiry the registrar holds and the price the oracle quotes. const deployment = JSON.parse(readFileSync(new URL(`../dev/local-chain-${SLOT}.json`, import.meta.url), "utf8")) as { rpcUrl: string; chainId: number; tld: string; ens: Hex; resolver: Hex; controller: Hex; baseRegistrar: Hex; namePolicy: Hex; generalTermsLink: string; generalTermsHash: Hex @@ -262,6 +271,25 @@ export const rowFit = (page: Page) => page.evaluate(() => { ownLine: Math.round(name.getBoundingClientRect().bottom) <= Math.round(rest.top) } }) +// Every document the page loads from now on, counted as it fires load. +export function loads(page: Page): { count: number } { + const seen = { count: 0 } + page.on("load", () => { seen.count += 1 }) + return seen +} + +export async function codesPageHolds(page: Page): Promise { + const kept = await page.evaluate(() => ({ ...localStorage })) + await page.goto(`${CODES_PAGE}/#/trademarks`) + await page.evaluate((items) => { for (const [key, value] of Object.entries(items)) localStorage.setItem(key, value) }, kept) +} + +export async function onCodesPage(page: Page): Promise { + const { search } = new URL(page.url()) + await codesPageHolds(page) + await page.goto(`${CODES_PAGE}/${search}`) +} + export async function search(page: Page, label: string): Promise { await page.goto("/") await page.getByLabel("Name", { exact: true }).fill(label) @@ -283,11 +311,18 @@ export const payButton = (page: Page) => onStep(page).getByRole("button", { name export const AVAILABLE_BRIEF = /^Available at \d\d:\d\d\.$/ export const TAKEN_BRIEF = /^Taken at \d\d:\d\d\. Please don't pay: cancel this invoice and choose another name\.$/ -// a configured key makes the order's page load Stripe.js, wherever the page is first opened -export const withStripeKey = (page: Page) => page.route((url) => url.pathname === "/api/config", async (route) => { - const res = await route.fetch() - await route.fulfill({ response: res, json: { ...(await res.json()), stripePublishableKey: "pk_test_e2e" } }) -}) +// a test key makes the card page, in the order page's frame, load Stripe.js +export const withStripeKey = (page: Page) => page.addInitScript((card) => { + if (location.origin === card) (window as { stripeTestKey?: string }).stripeTestKey = "pk_test_e2e" +}, LOCAL.cardOrigin) + +const CARD_FRAME = "body > main .stripe > iframe" +export const cardFrame = (page: Page) => page.frameLocator(CARD_FRAME) +export async function cardFrameOf(page: Page): Promise { + const frame = await page.locator(CARD_FRAME).elementHandle() + return (await frame!.contentFrame())! +} +export const fakeIntent = (amount: number) => `{ paymentIntent: { id: "pi_fake", amount: ${amount}, currency: "usd", livemode: false, payment_method_types: ["card"] } }` // Check your code's field, which takes a prepaid code or a name code export const codeField = (page: Page) => onStep(page).getByRole("textbox", { name: "Code", exact: true }) @@ -360,7 +395,7 @@ export async function savedToReview(page: Page, agree = true): Promise { await expect(box).toBeChecked() await onStep(page).getByRole("button", { name: "Continue" }).click() const review = onStep(page).getByRole("heading", { name: "Check your order" }) - const community = onStep(page).getByRole("heading", { name: COMMUNITY_HEADING }) + const community = onStep(page).getByRole("heading", { name: COMMUNITY_HEADING, level: 1 }) await expect(review.or(community)).toBeVisible() const listed = await community.isVisible() if (listed) await acceptCommunityTerms(page) @@ -520,6 +555,8 @@ export const test = base.extend<{ cspViolations: void }>({ }, { auto: true }], }) +export const codesTest = test.extend({ baseURL: async ({}, use) => use(CODES_PAGE) }) + // a paid order's page once someone registered its name first, which keeps the payment as the order's balance export const takenHeading = (label: string) => `${label}.simplex is no longer available` @@ -550,10 +587,8 @@ export async function waitRegistered(page: Page, label: string): Promise { await expect(page.getByRole("heading", { name: `${label}.simplex is yours` })).toBeVisible({ timeout: REGISTRATION_MS }) } -export const CHAIN = { resolver: "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318", sponsor: "0x0B306BF915C4d645ff596e518fAf3F9669b97016", chainId: 31337, tld: "simplex" } - export const registeredAnswer = (owner: string, expiresAt: number, links: { contact: string; channel: string }, entities: unknown[] = [], nonce = 0, gracePeriod = 90 * 86400) => - ({ found: { type: "registered", owner, resolver: CHAIN.resolver, expiresAt, gracePeriod, entities, records: { type: "own", ...links, nonce, edits: { left: 3 } } } }) + ({ found: { type: "registered", owner, resolver: LOCAL.resolver, expiresAt, gracePeriod, entities, records: { type: "own", ...links, nonce, edits: { left: 3 } } } }) export function okPreview(kind: "contact" | "channel", displayName: string, change: { fullName?: string; image?: string; chat?: "contact" | "business" | "bot"; publicMemberCount?: number } = {}) { const { fullName = "", image, chat = "contact", publicMemberCount = 12 } = change diff --git a/webapp/e2e/mode-cache.spec.ts b/webapp/e2e/mode-cache.spec.ts index 0541531e..bf56d622 100644 --- a/webapp/e2e/mode-cache.spec.ts +++ b/webapp/e2e/mode-cache.spec.ts @@ -3,9 +3,9 @@ import { readFileSync, statSync } from "node:fs" import { createServer, type Server } from "node:http" import type { AddressInfo } from "node:net" import { extname, join, normalize } from "node:path" -import type { Mode } from "../src/mode.ts" +import { loads } from "./helpers.ts" -// The production build, which has the worker, served by this spec as the store service serves it. +// The production build, which has the worker, served by this spec with the caching headers of the host before GitHub Pages. test.skip(!process.env.BASE_URL, "needs the production build in dist/, which runs with BASE_URL") const DIST = new URL("../dist/", import.meta.url).pathname @@ -16,16 +16,15 @@ const SLOW_ANSWER_MS = 4000 const SETTLE_MS = 3000 // long enough for a load the check started to have finished const RELOAD_MS = 1000 -const OTHER: Record = { open: "codes", codes: "open" } // Playwright turns Chromium's back/forward cache off by its flag, and its headless shell has none; Firefox's and WebKit's stay off const CHROMIUM_WITH_BFCACHE = { channel: "chromium", ignoreDefaultArgs: ["--disable-back-forward-cache"] } -// The service's names site: its mode at /api/config, and each file as built with Last-Modified, which Warp's +// The service's names site: its downtime at /api/config, and each file as built with Last-Modified, which Warp's // responseFile answers If-Modified-Since against with a 304. class Service { - mode: Mode = "open" + downtime = false delayMs = 0 - // the mode turns over with each config it answers, as a service restarted again and again + // the downtime turns over with each config it answers, as a service restarted again and again flips = false private server: Server | null = null private port = 0 @@ -38,10 +37,9 @@ class Service { const file = join(DIST, path === "/" ? "index.html" : path) const answer = () => { if (path === "/api/config") { - const mode = this.mode - if (this.flips) this.mode = OTHER[mode] - const names = { codesOnly: mode === "codes", chainId: 31337, resolver: "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318", sponsor: "0x0B306BF915C4d645ff596e518fAf3F9669b97016", tld: "simplex", termStart: 1798761600 } - return void res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end(JSON.stringify({ stripePublishableKey: null, names })) + const downtime = this.downtime + if (this.flips) this.downtime = !downtime + return void res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end(JSON.stringify({ stripePublishableKey: null, names: { downtime } })) } if (path.startsWith("/api/")) return void res.writeHead(404, { "Cache-Control": "no-store" }).end() let stat @@ -71,33 +69,20 @@ class Service { } const nameField = (page: Page) => page.getByLabel("Name", { exact: true }) -// the mode the home was drawn in: in codes mode its search waits for a code -async function pageMode(page: Page): Promise { - await expect(nameField(page)).toBeVisible() - return (await nameField(page).isDisabled()) ? "codes" : "open" -} -const expectMode = (page: Page, mode: Mode) => mode === "codes" ? expect(nameField(page)).toBeDisabled() : expect(nameField(page)).toBeEnabled() // the tab coming back into view, as a reader switching back to it; headless browsers keep every tab in view const becomeVisible = (page: Page) => page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))) // the page's own check of the service's mode, answered const modeChecked = (page: Page) => page.waitForResponse((r) => new URL(r.url()).pathname === "/api/config") -// Every document the page loads from now on, counted as it fires load. -function loads(page: Page): { count: number } { - const seen = { count: 0 } - page.on("load", () => { seen.count += 1 }) - return seen -} - -// A reader's page, opened once the service is in the given mode, and controlled by the worker it installed then. -async function installedIn(page: Page, service: Service, mode: Mode): Promise { - service.mode = mode +// A reader's page, opened once the service is in or out of its downtime, and controlled by the worker it installed then. +async function installedIn(page: Page, service: Service, downtime: boolean): Promise { + service.downtime = downtime await page.goto(service.url) await page.evaluate(() => navigator.serviceWorker.ready) const controlled = await page.reload() expect(controlled?.fromServiceWorker(), "the page loads through its worker").toBe(true) - expect(await pageMode(page)).toBe(mode) + await expect(nameField(page)).toBeVisible() } let service: Service @@ -109,71 +94,73 @@ test.afterEach(async () => { await service.stop() }) -test("a reload shows the mode the service switched to, while the service answers slowly after its restart", async ({ page }) => { +const downtimeShown = (page: Page) => page.getByText("You will be able to order names again soon.") + +test("a reload shows the downtime the service entered, while the service answers slowly after its restart", async ({ page }) => { test.setTimeout(60_000) - await installedIn(page, service, "codes") + await installedIn(page, service, false) await service.stop() - service.mode = "open" + service.downtime = true service.delayMs = SLOW_ANSWER_MS await service.start() await page.reload() - expect(await pageMode(page), "the service's answer, not the one the worker kept").toBe("open") - service.mode = "codes" + await expect(downtimeShown(page), "the service's answer, not the one the worker kept").toBeVisible() + service.downtime = false await page.reload() - expect(await pageMode(page)).toBe("codes") + await expect(nameField(page)).toBeVisible() + await expect(downtimeShown(page)).toHaveCount(0) }) -test("while the service is down, the page opens in the last mode the service gave, not the one it had at install", async ({ page }) => { - await installedIn(page, service, "codes") +test("while the service is down, the page opens in the downtime the service last gave, not as it was at install", async ({ page }) => { + await installedIn(page, service, false) await service.stop() - service.mode = "open" + service.downtime = true await service.start() await page.reload() - expect(await pageMode(page)).toBe("open") + await expect(downtimeShown(page)).toBeVisible() await service.stop() const offline = await page.reload() expect(offline?.fromServiceWorker(), "the kept shell").toBe(true) - expect(await pageMode(page), "the worker's copy of the service's last answer").toBe("open") - await expect(page.getByRole("heading", { name: "Your SimpleX domain" })).toBeVisible() - // the page's check finds no service, so the page offline stays as it opened + await expect(downtimeShown(page), "the worker's copy of the service's last answer").toBeVisible() const seen = loads(page) await becomeVisible(page) await page.waitForTimeout(SETTLE_MS) - expect(seen.count).toBe(0) - await expect(page.getByRole("heading", { name: "Your SimpleX domain" })).toBeVisible() + expect(seen.count, "the page's check finds no service, so the page offline stays as it opened").toBe(0) + await expect(downtimeShown(page)).toBeVisible() }) -test("a tab open across the switch loads again in the service's mode as it comes back into view, both ways", async ({ page }) => { - await installedIn(page, service, "open") - service.mode = "codes" - await becomeVisible(page) - await expect(nameField(page), "the search waits for a code").toBeDisabled() - service.mode = "open" - await becomeVisible(page) - await expect(nameField(page)).toBeEnabled() +test("a tab open across a downtime loads again as it comes back into view once the downtime has ended", async ({ page }) => { + await installedIn(page, service, false) + const seen = loads(page) + service.downtime = true + await Promise.all([modeChecked(page), becomeVisible(page)]) + await page.waitForTimeout(RELOAD_MS) + expect(seen.count, "a downtime begun loads nothing").toBe(0) + service.downtime = false + await Promise.all([page.waitForEvent("load"), becomeVisible(page)]) + await expect(nameField(page)).toBeVisible() + expect(seen.count).toBe(1) }) -test("a page restored by Back loads again in the service's mode", async ({ page, browserName }) => { +test("a page restored by Back loads again once a downtime it read has ended", async ({ page, browserName }) => { if (browserName !== "chromium") { - await installedIn(page, service, "codes") - service.mode = "open" + await installedIn(page, service, true) + service.downtime = false // the restore's own event stands for the cache Playwright keeps off in Firefox and WebKit - await page.evaluate(() => dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true }))) - await expectMode(page, "open") + await Promise.all([page.waitForEvent("load"), page.evaluate(() => dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })))]) return } const browser = await chromium.launch(CHROMIUM_WITH_BFCACHE) try { const restoring = await browser.newPage() - await installedIn(restoring, service, "codes") + await installedIn(restoring, service, true) const restored: boolean[] = [] restoring.on("console", (m) => { if (m.text().startsWith("pageshow ")) restored.push(m.text() === "pageshow true") }) await restoring.evaluate(() => addEventListener("pageshow", (e) => console.log(`pageshow ${e.persisted}`))) - service.mode = "open" + service.downtime = false await restoring.goto(`${service.url}/robots.txt`) // a restored page fires no load - await restoring.goBack({ waitUntil: "commit" }) - await expectMode(restoring, "open") + await Promise.all([restoring.waitForEvent("load"), restoring.goBack({ waitUntil: "commit" })]) expect(restored, "Chromium restored the page from its back/forward cache").toEqual([true]) } finally { await browser.close() @@ -181,25 +168,22 @@ test("a page restored by Back loads again in the service's mode", async ({ page, }) test("a name typed and not searched is kept: the page loads again only as the reader leaves the screen", async ({ page }) => { - await installedIn(page, service, "open") + await installedIn(page, service, true) await nameField(page).fill("halftyped") - service.mode = "codes" + service.downtime = false const checked = modeChecked(page) await becomeVisible(page) await checked await page.waitForTimeout(SETTLE_MS) await expect(nameField(page)).toHaveValue("halftyped") - expect(await pageMode(page)).toBe("open") const seen = loads(page) await page.locator("body > header").getByRole("link", { name: "Check your code" }).click() await expect(page.getByRole("heading", { name: "Check your code" })).toBeVisible() - expect(seen.count, "leaving the screen loads the page again, in the service's mode").toBe(1) - await page.goBack() - await expectMode(page, "codes") + expect(seen.count, "leaving the screen loads the page again").toBe(1) }) -test("no reload loop: a service whose mode flips with every answer loads the page again at most once", async ({ page }) => { - await installedIn(page, service, "open") +test("no reload loop: a service whose downtime flips with every answer loads the page again at most once", async ({ page }) => { + await installedIn(page, service, false) service.flips = true const seen = loads(page) await page.goto(service.url) @@ -213,8 +197,8 @@ test("no reload loop: a service whose mode flips with every answer loads the pag expect(seen.count, "each return to the tab loads it again at most once").toBeLessThanOrEqual(5) }) -test("no reload while the service keeps answering the page's own mode", async ({ page }) => { - await installedIn(page, service, "codes") +test("no reload while the service stays in its downtime", async ({ page }) => { + await installedIn(page, service, true) const seen = loads(page) for (let i = 0; i < 3; i++) { const checked = modeChecked(page) @@ -223,5 +207,4 @@ test("no reload while the service keeps answering the page's own mode", async ({ } await page.waitForTimeout(SETTLE_MS) expect(seen.count).toBe(0) - expect(await pageMode(page)).toBe("codes") }) diff --git a/webapp/e2e/name-address.spec.ts b/webapp/e2e/name-address.spec.ts new file mode 100644 index 00000000..2e944e24 --- /dev/null +++ b/webapp/e2e/name-address.spec.ts @@ -0,0 +1,52 @@ +import { expect, type Page } from "@playwright/test" +import { LOCAL } from "../src/config.ts" +import { checksumAddress } from "../src/crypto/wallet.ts" +import { walletOf } from "../src/flow.ts" +import { checkoutOwnerCode, codeField, control, onStep, search, startOrder, test, toCodeStep, uniqueLabel, waitRegistered } from "./helpers.ts" + +const PUBLIC = "Your name address is public. Please include it in any support request." +const addressOf = (code: string) => checksumAddress(walletOf(code)!.address) +const shownAddress = (page: Page) => onStep(page).locator(".name-address .mono") +const APP_LINK = "open your names in the SimpleX Names app" +const appLink = (page: Page) => onStep(page).getByRole("link", { name: APP_LINK }) + +test("the name address stands beside the name code on its step, on the registered order's page, in Your names and in Check your code", async ({ page, request }) => { + await search(page, uniqueLabel("addrstep")) + await toCodeStep(page) + const stepCode = await checkoutOwnerCode(page) + await expect(onStep(page).locator(".name-address")).toContainText(PUBLIC) + await expect(shownAddress(page)).toHaveText(addressOf(stepCode)) + + const label = uniqueLabel("addr") + const { invoiceId, ownerCode } = await startOrder(page, label, { method: "btc" }) + await control(request, `settle/${invoiceId}`) + await waitRegistered(page, label) + await expect(shownAddress(page), "under the registration's end, with the code hidden").toHaveText(addressOf(ownerCode)) + await expect(onStep(page).getByTestId("owner-code")).not.toHaveText(ownerCode) + await page.goto("/#/names") + const row = page.locator(".list-row", { hasText: `${label}.simplex` }) + await row.getByRole("button", { name: "Name code" }).click() + await expect(row.locator(".name-address .mono")).toHaveText(addressOf(ownerCode)) + await page.goto("/#/code") + await codeField(page).fill(ownerCode) + await expect(onStep(page).getByRole("button", { name: "Add to Your names" })).toBeEnabled() + await expect(shownAddress(page), "Check your code with the name code").toHaveText(addressOf(ownerCode)) +}) + +test("a registered name links the SimpleX Names app's page of its name address", async ({ page, request }) => { + const label = uniqueLabel("scan") + const { invoiceId, ownerCode } = await startOrder(page, label, { method: "btc" }) + await control(request, `settle/${invoiceId}`) + await waitRegistered(page, label) + const href = `${LOCAL.appOrigin}/${addressOf(ownerCode)}` + await expect(appLink(page), "with the code hidden").toHaveAttribute("href", href) + await expect(onStep(page).locator(".app-names")).toHaveText(`Please ${APP_LINK} and check that this name is listed. If it is not, please contact support.`) + const lead = await onStep(page).locator(".lead").boundingBox() + const line = await onStep(page).locator(".app-names").boundingBox() + expect(line!.y, "under Registered until").toBeGreaterThan(lead!.y) + expect(await onStep(page).locator(".screen-body > *").first().locator(".app-names").count(), "the first thing under it").toBe(1) + await page.goto("/#/names") + const row = page.locator(".list-row", { hasText: `${label}.simplex` }) + await row.getByRole("button", { name: "Name code" }).click() + await expect(row.getByRole("link", { name: APP_LINK })).toHaveAttribute("href", href) +}) diff --git a/webapp/e2e/offline.spec.ts b/webapp/e2e/offline.spec.ts index 6ac3540b..aa404b87 100644 --- a/webapp/e2e/offline.spec.ts +++ b/webapp/e2e/offline.spec.ts @@ -1,11 +1,12 @@ import { expect } from "@playwright/test" -import { test } from "./helpers.ts" +import { keepOrder, test } from "./helpers.ts" // The service worker is in the production build only: run with BASE_URL at `npx vite preview`. test.skip(!process.env.BASE_URL, "needs the production build, as BASE_URL") test("the production build opens offline: the page, an order's link and Your names, with a note while the network is gone", async ({ page, context }) => { const OFFLINE_NOTE = "You are offline. Searches, payments and order updates need the connection." + await keepOrder(page, "reg-abc", "abc", "offlinename") await page.goto("/") await page.evaluate(() => localStorage.setItem("simplex-names:code:SN6-OFFLINE", JSON.stringify({ code: "SN6-Z6VPA-7YPF0-XN8B4-9S1ZD", minLength: 6, years: 2, addedAt: new Date().toISOString() }))) // the worker takes no page it did not load, so it is active once the next load comes through it diff --git a/webapp/e2e/pages.spec.ts b/webapp/e2e/pages.spec.ts new file mode 100644 index 00000000..8de99a94 --- /dev/null +++ b/webapp/e2e/pages.spec.ts @@ -0,0 +1,35 @@ +import { expect } from "@playwright/test" +import { onStep, startOrder, test, uniqueLabel } from "./helpers.ts" + +const FRAMER = "http://127.0.0.2:5998" +const API_ORIGIN = process.env.API_ORIGIN +const SKEW_MS = 20 * 60_000 + +test("the page in another page's frame draws one line, with a link that opens it in its own tab", async ({ page, baseURL, browserName }) => { + if (browserName === "chromium") await page.context().grantPermissions(["local-network-access"]) + const url = new URL("/#/names", baseURL).href + await page.route(`${FRAMER}/**`, (route) => route.fulfill({ contentType: "text/html", body: `` })) + await page.goto(`${FRAMER}/`) + const inOtherPage = page.frameLocator("iframe") + await expect(inOtherPage.locator("p.own-tab")).toHaveText("This page can be used only in its own tab. Please open it in a new tab.") + await expect(inOtherPage.getByRole("link", { name: "open it in a new tab" })).toHaveAttribute("href", url) + await expect(inOtherPage.locator("main, header, input")).toHaveCount(0) +}) + +test("a build for an API on its own origin orders a name across origins, and reads the service's clock from its Date", async ({ page }) => { + test.skip(!API_ORIGIN, "needs a build for the dev chain with VITE_API_ORIGIN, served at BASE_URL") + const asked = new Set() + page.on("request", (r) => { if (new URL(r.url()).pathname.startsWith("/api/")) asked.add(new URL(r.url()).origin) }) + const { invoiceId } = await startOrder(page, uniqueLabel("cors"), { method: "btc" }) + await expect(onStep(page).getByRole("heading", { name: "Pay with Bitcoin" })).toBeVisible() + expect([...asked], "every API request to the API's origin").toEqual([API_ORIGIN]) + await page.addInitScript((skew) => { + const now = Date.now + Date.now = () => now() + skew + }, SKEW_MS) + const reads: number[] = [] + page.on("response", (r) => { if (new URL(r.url()).pathname === `/api/invoice/${invoiceId}`) reads.push(r.status()) }) + await page.reload() + await expect(onStep(page).getByRole("heading", { name: "Pay with Bitcoin" })).toBeVisible() + expect(reads.slice(0, 2), "refused for its time, then answered at the clock its Date gave").toEqual([400, 200]) +}) diff --git a/webapp/e2e/paid.spec.ts b/webapp/e2e/paid.spec.ts index 5cea37da..e65a9cfd 100644 --- a/webapp/e2e/paid.spec.ts +++ b/webapp/e2e/paid.spec.ts @@ -1,4 +1,5 @@ import { expect, type Locator, type Page, type Route } from "@playwright/test" +import { heldPrice, LOCAL } from "../src/config.ts" import { walletOf } from "../src/flow.ts" import { checksumAddress } from "../src/crypto/wallet.ts" import { dateOf } from "../src/format.ts" @@ -7,6 +8,7 @@ import { CARD_FORM_TIMEOUT_MS } from "../src/stripe.ts" import { blockTimeOf, chainExpiry, channelLink, CHECKOUT_KEY, checkoutOwnerCode, CODE_HEADING, codeField, contactLink, control, fakeRegisteredName, fillLinks, FIT_SIZES, LINKS_HEADING, MOCK, mockRegistration, onStep, oracleQuote, payButton, previewsShown, REGISTRATION_MS, offCentre, orderOwnerCode, qrText, registeredAnswer, registrationOf, restoreOrder, SAVED, AGREE, agreeToTerms, savedToReview, search, searchName, shot, shownCode, SLOW_FETCH_MS, startOrder, test, TERMS, toCodeStep, toFullReview, toReview, uniqueLabel, waitRegistered, withStripeKey, AVAILABLE_BRIEF, TAKEN_BRIEF, + cardFrame, fakeIntent, keepOrder, } from "./helpers.ts" // the card form these tests pay with is the dev server's stand-in; a production build loads Stripe's own @@ -94,7 +96,7 @@ test("a Bitcoin order pays in two parts, registers on chain, takes its links on await expect(onStep(page).locator(".pay-status")).toHaveText(new RegExp(`^Waiting for paymentInvoice valid for \\d+:\\d\\dReference ${invoiceId}$`)) await shot(page, "N4-bitcoin") // the wallet link is a BIP21 URI for what is left to send, and each copy button says what it copies - const invoice = async () => (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as Promise<{ address: string; cryptoAmount: string; cryptoAmountDue: string }> + const invoice = async () => (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as Promise<{ address: string; cryptoAmount: string; cryptoAmountDue: string }> const wallet = onStep(page).getByRole("link", { name: "Open in wallet" }) const { address, cryptoAmount } = await invoice() await expect(wallet).toHaveAttribute("href", `bitcoin:${address}?amount=${cryptoAmount}`) @@ -194,7 +196,7 @@ test("a Bitcoin order pays in two parts, registers on chain, takes its links on await channelField.fill(nextChannel) await expect(page.locator(".link-field").nth(1)).toHaveAttribute("data-state", "ok") await page.getByRole("button", { name: "Save links" }).click() - await expect(page.locator("[aria-hidden=true]", { hasText: /^Too many attempts\. Please try again in/ })).toBeVisible({ timeout: 30_000 }) + await expect(page.locator("[aria-hidden=true]", { hasText: /^Please try again in/ })).toBeVisible({ timeout: 30_000 }) expect(refused.map((body) => body.edits.map((e) => e.key))).toEqual([["contact", "channel"]]) expect((await searchName(request, label)).records).toMatchObject({ contact: "", channel }) await page.unroute("**/api/name/records") @@ -314,7 +316,7 @@ test("a purchase walks the steps a buyer expects, and the links set before payin await expect(step.getByRole("radio")).toHaveText(["Card", "Bitcoin", "Monero"]) // the ETH link ends the note under the methods, and nothing sits under Pay const dapp = step.locator(".notes").getByRole("link", { name: "Pay with ETH" }) - await expect(dapp).toHaveAttribute("href", "https://app.simplex.domains") + await expect(dapp).toHaveAttribute("href", LOCAL.appOrigin) await expect(step.locator(".notes")).toHaveText("After paying, keep this page open until the name is registered. Pay with ETH") await expect(step.locator(".actions-row .alt")).toHaveCount(0) // the one box to tick, the terms, holds Pay until it is ticked; its link opens the terms beside the order @@ -352,7 +354,7 @@ test("a purchase walks the steps a buyer expects, and the links set before payin const main = page.locator("body > main") await expect(main.locator(".lead")).toHaveText(`Registered until ${dateOf((await searchName(request, label)).expiresAt as number)}.`) // on chain: the price charged is the oracle's quote for the paid years, and the name expires the sent duration after the register's block - const paidInvoice = await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as { amount: number; registration: { years: number; duration: number; registerTx: string; phase: { disputeUntil: number } } } + const paidInvoice = await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { amount: number; registration: { years: number; duration: number; registerTx: string; phase: { disputeUntil: number } } } expect(paidInvoice.amount).toBe(await oracleQuote(label, paidInvoice.registration.years)) expect(await chainExpiry(label)).toBe(await blockTimeOf(paidInvoice.registration.registerTx) + paidInvoice.registration.duration) expect(paidInvoice.registration.phase.disputeUntil, "a Bitcoin payment's dispute end, 14 days after the register's block").toBe(await blockTimeOf(paidInvoice.registration.registerTx) + 14 * 86400) @@ -361,7 +363,7 @@ test("a purchase walks the steps a buyer expects, and the links set before payin await expect(await shownCode(page)).toHaveText(ownerCode) await expect(main.getByRole("button", { name: "Copy code" })).toBeVisible() await expect(main.getByRole("checkbox")).toHaveCount(0) - await expect(main.getByRole("link", { name: "Your names" })).toHaveCount(0) + await expect(main.getByRole("link", { name: "Your names", exact: true })).toHaveCount(0) await expect(main.getByRole("link", { name: "Edit links" })).toHaveCount(0) const answer = await searchName(request, label) expect(answer.owner, "the code saved before paying owns the name").toBe(checksumAddress(walletOf(ownerCode)!.address)) @@ -424,7 +426,6 @@ test("a purchase walks the steps a buyer expects, and the links set before payin const reviewLayout = (page: Page) => onStep(page).locator(".screen-body, .card.order, .trow, .pay-with, .notes, .check.terms, .actions-row .btn") .evaluateAll((nodes) => nodes.map((n) => [n.className, ...Object.values(n.getBoundingClientRect().toJSON())])) const bonusOf = (page: Page) => onStep(page).getByRole("button", { name: /^and (\d+ days|1 day)$/ }) -const termStartOf = (page: Page) => page.evaluate((key) => JSON.parse(sessionStorage.getItem(key)!).termStart as number, CHECKOUT_KEY) const inWindow = async (page: Page, node: Locator) => { const box = (await node.boundingBox())! const { width, height } = page.viewportSize()! @@ -436,7 +437,7 @@ const termLines = (page: Page) => onStep(page).locator(".trow").first().locator( test("the term's free days are the early adopter bonus, explained on hover, focus and tap, with nothing moving", async ({ page, browser, baseURL }) => { await search(page, uniqueLabel("bonus")) await toReview(page, false) - const hint = `Early adopter bonus: your 2 years start on ${dateOf(await termStartOf(page))}.` + const hint = `Early adopter bonus: your 2 years start on ${dateOf(LOCAL.termStart)}.` const bonus = bonusOf(page) const tip = onStep(page).getByRole("tooltip") await expect(bonus).toHaveAccessibleDescription(hint) @@ -492,14 +493,17 @@ test("the term's free days are the early adopter bonus, explained on hover, focu test("a term that has started has no free days, so no bonus or hint, which come back with the days", async ({ page }) => { await search(page, uniqueLabel("nobonus")) await toReview(page, false) - const termStart = await termStartOf(page) - const startAt = (at: number) => page.evaluate(([key, start]) => sessionStorage.setItem(key as string, JSON.stringify({ ...JSON.parse(sessionStorage.getItem(key as string)!), termStart: start })), [CHECKOUT_KEY, at]) - await startAt(Math.floor(Date.now() / 1000) - 86400) + await page.route("**/api/**", async (route) => { + const res = await route.fetch() + const { date: _, ...headers } = res.headers() + await route.fulfill({ response: res, headers }) + }) + await page.clock.install({ time: (LOCAL.termStart + 86400) * 1000 }) await page.reload() await expect(onStep(page).locator(".trow").first()).toHaveText("Term2 years") await expect(bonusOf(page)).toHaveCount(0) await expect(onStep(page).locator("[role=tooltip]")).toHaveCount(0) - await startAt(termStart) + await page.clock.setSystemTime(Date.now()) await page.reload() await expect(bonusOf(page)).toHaveAccessibleDescription(/^Early adopter bonus/) }) @@ -699,7 +703,7 @@ test("Continue on the links step waits for a link being checked, and takes focus test("a Monero invoice's wallet link is monero:// for Monero GUI on a laptop and monero: on a phone, and its QR keeps monero:", async ({ page, request }) => { const { invoiceId } = await startOrder(page, uniqueLabel("xmrlink"), { method: "xmr" }) await expect(page.getByRole("heading", { name: "Pay with Monero" })).toBeVisible() - const { address, cryptoAmount } = await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as { address: string; cryptoAmount: string } + const { address, cryptoAmount } = await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { address: string; cryptoAmount: string } const wallet = onStep(page).getByRole("link", { name: "Open in wallet" }) await expect(wallet).toHaveAttribute("href", `monero://${address}?tx_amount=${cryptoAmount}`) await expect(wallet.locator("xpath=..")).toHaveClass(/\bqr\b/) @@ -713,7 +717,7 @@ test("the owner code restores an order in another browser, and a bad code is ref const label = uniqueLabel("rest") const { invoiceId, ownerCode } = await startOrder(page, label, { method: "xmr" }) await expect(page.getByRole("heading", { name: "Pay with Monero" })).toBeVisible() - const { address, cryptoAmount } = await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as { address: string; cryptoAmount: string } + const { address, cryptoAmount } = await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { address: string; cryptoAmount: string } await expect(onStep(page).getByRole("link", { name: "Open in wallet" }), "the Monero URI").toHaveAttribute("href", `monero://${address}?tx_amount=${cryptoAmount}`) await control(request, `confirming/${invoiceId}`) await expect(page.getByText("Waiting for 1 confirmation")).toBeVisible() @@ -756,7 +760,7 @@ test("a card order waits for Stripe, blocks a second card order meanwhile, then await expect(onStep(page).getByRole("button", { name: /^Pay \$\d+$/ })).toBeVisible() await expect(onStep(page).getByText("The card form is provided by Stripe. Your card will be charged only when you press Pay.")).toBeVisible() // the development stand-in says what it is, and the invoice can be cancelled from the form as from a crypto invoice - await expect(onStep(page).locator(".stripe > .label")).toHaveText("Test card form: no Stripe key is set, so Pay simulates a payment.") + await expect(cardFrame(page).locator(".stand-in > .label")).toHaveText("Test card form: no Stripe key is set, so Pay simulates a payment.") await expect(onStep(page).getByRole("button", { name: "Cancel this invoice" })).toBeVisible() await onStep(page).getByRole("button", { name: /^Pay \$/ }).click() await expect(page.getByText("Waiting for Stripe to confirm")).toBeVisible() @@ -808,7 +812,7 @@ test("the card form stays in place while another tab writes the order, the same (k) => localStorage.setItem(k, JSON.stringify({ ...JSON.parse(localStorage.getItem(k)!), contact: "https://smp8.simplex.im/a#S1" })), ] for (const write of writes) { - const read = page.waitForResponse((r) => new URL(r.url()).pathname === `/api/invoice/${invoiceId}` && !r.url().includes("?")) + const read = page.waitForResponse((r) => new URL(r.url()).pathname === `/api/invoice/${invoiceId}` && !new URL(r.url()).searchParams.has("wait")) await other.evaluate(write, key) await read await expect(page.locator("main[aria-busy]")).toHaveCount(0) @@ -1009,7 +1013,7 @@ test("a part payment on a closed invoice, once credited, says so and gets an inv await actions.getByRole("button", { name: "Get a new invoice" }).click() await page.waitForURL((url) => url.searchParams.get("order") !== invoiceId) const second = new URL(page.url()).searchParams.get("order")! - const invoice = async (id: string) => (await request.get(`${MOCK}/api/invoice/${id}`)).json() + const invoice = async (id: string) => (await request.get(`${MOCK}/control/invoice/${id}`)).json() const [closed, whole] = [await invoice(invoiceId), await invoice(second)] expect([whole.amount, whole.registration.price, whole.registration.payment, whole.registration.labelHash], "the whole price, for the same name") .toEqual([10000, 10000, { type: "invoice", method: "btc" }, closed.registration.labelHash]) @@ -1181,7 +1185,7 @@ test("a cancel refused for a rate limit keeps the invoice payable and says so un await page.route("**/api/invoice/*/cancel", (route) => route.fulfill({ status: 429, headers: { "retry-after": "2" }, json: { type: "rate_limited" } })) const cancel = onStep(page).getByText("Cancel this invoice", { exact: true }) await cancel.click() - await expect(page.locator("[aria-hidden=true]", { hasText: /^Too many attempts\. Please try again in/ })).toBeVisible() + await expect(page.locator("[aria-hidden=true]", { hasText: /^Please try again in/ })).toBeVisible() await expect(onStep(page).getByRole("heading", { name: "Pay with Bitcoin" })).toBeVisible() await page.unroute("**/api/invoice/*/cancel") await expect(page.getByText("Too many attempts")).toHaveCount(0, { timeout: 10_000 }) @@ -1259,7 +1263,8 @@ test("a forgotten order whose code's lookup is rate limited waits as asked, then await control(request, "search", { findLimitSeconds: 0 }) }) -test("an unknown order link says so", async ({ page }) => { +test("an order link whose order the service does not know says so, in the browser holding its code", async ({ page }) => { + await keepOrder(page, "reg-nothing-here", "nothing-here", uniqueLabel("gone")) await page.goto("/?order=nothing-here") await expect(page.getByRole("heading", { name: "This link does not work" })).toBeVisible() await shot(page, "N11-unknown") @@ -1284,20 +1289,21 @@ test("a card form that does not load says so and offers a new invoice", async ({ await page.getByRole("button", { name: "Pay with Monero" }).click() await page.waitForURL((url) => url.searchParams.get("order") !== card) await expect(page.getByRole("heading", { name: "Pay with Monero" })).toBeVisible() - const cancelled = await (await page.request.get(`${MOCK}/api/invoice/${card}`)).json() as { status: string } + const cancelled = await (await page.request.get(`${MOCK}/control/invoice/${card}`)).json() as { status: string } expect(cancelled.status, "the card invoice").toBe("expired") }) // a Stripe.js whose card form reports, once mounted, that it could not load, as it does for an intent Stripe refuses -const STRIPE_FORM_FAILS = `window.Stripe = () => ({ elements: () => ({ create: () => { +const stripeFormFails = (amount: number) => `window.Stripe = () => ({ retrievePaymentIntent: async () => (${fakeIntent(amount)}), elements: () => ({ create: () => { const handlers = {} return { on: (event, handler) => { handlers[event] = handler }, mount: () => setTimeout(() => handlers.loaderror?.({ elementType: "payment" })), destroy: () => undefined } } }) })` test("a card form that Stripe cannot load says so and offers a new invoice, rather than a form that never comes", async ({ page }) => { - await startOrder(page, uniqueLabel("cardfail"), { method: "card" }) + const label = uniqueLabel("cardfail") + await startOrder(page, label, { method: "card" }) await withStripeKey(page) - await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: STRIPE_FORM_FAILS })) + await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: stripeFormFails(heldPrice(label.length)) })) await page.reload() await expect(page.getByRole("heading", { name: "Card payment not confirmed" })).toBeVisible() await expect(page.getByText("The card form did not load, so your card was not charged. Please reload the page.")).toBeVisible() @@ -1305,21 +1311,23 @@ test("a card form that Stripe cannot load says so and offers a new invoice, rath }) // a Stripe.js whose card form, once mounted, neither loads nor says it failed, as on a stalled network -const STRIPE_FORM_STALLS = `window.Stripe = () => ({ elements: () => ({ create: () => ({ on: () => undefined, mount: () => undefined, destroy: () => undefined }) }) })` +const stripeFormStalls = (amount: number) => `window.Stripe = () => ({ retrievePaymentIntent: async () => (${fakeIntent(amount)}), + elements: () => ({ create: () => ({ on: () => undefined, mount: () => undefined, destroy: () => undefined }) }) })` // room past the bound for the page to draw what follows const CARD_FORM_SLACK_MS = 15_000 // Stripe.js loaded with a form that never says how it went, or a request for Stripe.js that is never answered -const STALLS: [string, (route: Route) => Promise | undefined][] = [ - ["form", (route) => route.fulfill({ contentType: "text/javascript", body: STRIPE_FORM_STALLS })], - ["script", () => undefined], +const STALLS: [string, (amount: number) => (route: Route) => Promise | undefined][] = [ + ["form", (amount) => (route) => route.fulfill({ contentType: "text/javascript", body: stripeFormStalls(amount) })], + ["script", () => () => undefined], ] for (const [stalled, answer] of STALLS) { test(`a card ${stalled} that neither loads nor fails gives up after its bound and offers a new invoice, rather than Pay off for good`, async ({ page }) => { - await startOrder(page, uniqueLabel("cardstall"), { method: "card" }) + const label = uniqueLabel("cardstall") + await startOrder(page, label, { method: "card" }) await withStripeKey(page) - await page.route("https://js.stripe.com/**", answer) + await page.route("https://js.stripe.com/**", answer(heldPrice(label.length))) await page.reload() await expect(page.getByRole("heading", { name: "Pay by card" })).toBeVisible() await expect(payButton(page)).toBeDisabled() @@ -1329,13 +1337,12 @@ for (const [stalled, answer] of STALLS) { }) } -test("a card form that does not load, in a browser without the order, leads to the name code", async ({ page }) => { +test("a card order's page in a browser that lost the order leads to the name code, with no card form", async ({ page }) => { await startOrder(page, uniqueLabel("nocardrec"), { method: "card" }) - await withStripeKey(page) - await page.route("https://js.stripe.com/**", (route) => route.abort()) await page.evaluate(() => localStorage.clear()) await page.reload() - await expect(page.getByRole("heading", { name: "Card payment not confirmed" })).toBeVisible() + await expect(page.getByRole("heading", { name: "The name code is not in this browser" })).toBeVisible() + await expect(page.locator("body > main .stripe")).toHaveCount(0) await expect(page.getByRole("button", { name: "Get a new invoice" })).toHaveCount(0) await page.getByRole("button", { name: "Enter your name code" }).click() await expect(codeField(page)).toBeVisible() diff --git a/webapp/e2e/robustness.spec.ts b/webapp/e2e/robustness.spec.ts index 4c7fac24..963adeab 100644 --- a/webapp/e2e/robustness.spec.ts +++ b/webapp/e2e/robustness.spec.ts @@ -142,7 +142,7 @@ test("Get a new invoice keeps an invoice the service would not cancel", async ({ } await page.route("**/api/invoice/*/cancel", (route) => route.fulfill({ status: 429, headers: { "retry-after": "2" }, json: { type: "rate_limited" } })) await page.getByRole("button", { name: "Get a new invoice" }).click() - await expect(page.locator("[aria-hidden=true]", { hasText: /^Too many attempts\. Please try again in/ })).toBeVisible() + await expect(page.locator("[aria-hidden=true]", { hasText: /^Please try again in/ })).toBeVisible() await expect(page).toHaveURL(new RegExp(`order=${invoiceId}`)) }) @@ -163,8 +163,8 @@ test("a registered order opened in a browser without its code offers restore", a const other = await browser.newContext() const page2 = await other.newPage() await page2.goto(`/?order=${invoiceId}`) - await expect(page2.getByText("Its name code is not in this browser.")).toBeVisible() - await page2.getByRole("button", { name: "Restore with your name code" }).click() + await expect(page2.getByText("Please enter the name code you saved for this order.")).toBeVisible() + await page2.getByRole("button", { name: "Enter your name code" }).click() await codeField(page2).fill(ownerCode) await page2.getByRole("button", { name: "Add to Your names" }).click() // back on the order's page, which now has the code @@ -324,22 +324,19 @@ test("a row Your names could not read is read again while the page stays open", await expect(chip, "the row read again by itself").toHaveText("Waiting for payment", { timeout: UNREAD_ROUND_MS }) }) -test("Your names draws a row as last read while the service's config cannot be read, and reads the row once it can", async ({ page }) => { +test("Your names reads its rows while the service's config cannot be read, as the page holds its deployment", async ({ page }) => { const order = await keepOrder(page, "reg-config", null, "configunread") const expiresAt = Math.floor(Date.now() / 1000) + ROW_YEAR_S const registered = registrationView(order, { phase: registeredPhase(expiresAt), commitTx: "0x02", registerTx: "0x03" }) - await page.evaluate(([id, view]) => localStorage.setItem("simplex-names-seen", JSON.stringify({ [id]: { view, invoice: null } })), [order.registrationId, registered] as const) await page.route(`**/api/registration/${order.registrationId}*`, (route) => route.fulfill({ json: registered })) await page.route("**/api/name/**", (route) => route.fulfill({ json: registeredAnswer(order.owner, expiresAt, { contact: "", channel: "" }) })) - let unread = true - await page.route("**/api/config", (route) => unread ? route.fulfill({ status: 500, json: { type: "internal" } }) : route.continue()) + await page.route("**/api/config", (route) => route.fulfill({ status: 500, json: { type: "internal" } })) await page.goto("about:blank") await page.goto("/#/names") const row = page.locator(".list-row", { hasText: "configunread" }) await expect(row).toContainText("configunread.simplex") - await expect(row.locator(".chip")).toHaveText("Not checked") - unread = false - await expect(row.locator(".chip"), "the row read again once the config is read").toHaveCount(0, { timeout: UNREAD_ROUND_MS }) + await expect(row.locator(".sub")).toHaveText(/^Until /) + await expect(row.locator(".chip")).toHaveCount(0) }) test("a code Your names could not check is checked again while the page stays open", async ({ page, request }) => { @@ -467,7 +464,7 @@ test("Back from a paused order keeps the order paused", async ({ page }) => { await toReview(page) await page.route("**/api/invoice", (route) => route.request().method() === "POST" ? route.fulfill({ status: 429, headers: { "retry-after": "20" }, json: { type: "rate_limited" } }) : route.continue()) await payButton(page).click() - await expect(page.locator(".outcome .notice span[aria-hidden=true]")).toHaveText(/^Too many attempts\. Please try again in \d+ seconds\.$/) + await expect(page.locator(".outcome .notice span[aria-hidden=true]")).toHaveText(/^Please try again in \d+ seconds\.$/) await page.goBack() await expect(page.getByRole("heading", { name: CODE_HEADING })).toBeVisible() await page.goForward() diff --git a/webapp/e2e/screens.spec.ts b/webapp/e2e/screens.spec.ts index e1df8a0c..6c469c40 100644 --- a/webapp/e2e/screens.spec.ts +++ b/webapp/e2e/screens.spec.ts @@ -2,21 +2,21 @@ import { chromium, expect, type APIRequestContext, type Browser, type BrowserCon import { createHash } from "node:crypto" import { fileURLToPath } from "node:url" import { keccak256, toHex } from "viem" +import { heldPrice, LOCAL } from "../src/config.ts" import { labelHash, YEAR_S } from "../src/crypto/registration.ts" import { checksumAddress, hex } from "../src/crypto/wallet.ts" import { newOwnerCode, walletOf } from "../src/flow.ts" import { - addNameCode, agreeToTerms, answersReserved, CHAIN, channelLink, CHECKOUT_KEY, checkoutOwnerCode, CODE_HEADING, codeField, COMMUNITY_HEADING, contactLink, contractsOwnerLists, control, fillLinks, + addNameCode, agreeToTerms, ALTERNATE_COMMUNITY_TERMS, ALTERNATE_GENERAL_TERMS, answersReserved, channelLink, CHECKOUT_KEY, CODES_PAGE, codesPageHolds, codesTest, onCodesPage, checkoutOwnerCode, CODE_HEADING, codeField, COMMUNITY_HEADING, contactLink, contractsOwnerLists, control, fillLinks, keepOrder, type KeptOrder, LINKS_HEADING, MOCK, mockRegistration, newClient, okPreview, onStep, ownerSetsResolver, ownerSetsText, payButton, previewsShown, registeredAnswer, registeredPhase, REGISTRATION_MS, registrationOf, registrationView, SAVED, - savedToReview, search, searchName, selectedToReview, shownCode, startOrder, takenOrder, test, toCodeStep, toFullReview, toReview, useCode, waitRegistered, withStripeKey, + savedToReview, search, searchName, selectedToReview, shownCode, startOrder, takenOrder, test, toCodeStep, toFullReview, toReview, useCode, waitRegistered, withStripeKey, fakeIntent, } from "./helpers.ts" const START_S = Date.UTC(2026, 10, 2, 8) / 1000 const STEP_S = 300 const SIZES = [["desktop", { width: 1280, height: 800 }], ["phone", { width: 390, height: 844 }]] as const const LAPSED = "The name was not signed in time" -const TERMS_TEXT = "The general terms, changed for the screens" const FLAT_BACKGROUND = fileURLToPath(new URL("screens.css", import.meta.url)) interface Reach { page: Page; request: APIRequestContext; browser: Browser; baseURL: string; id: string; now: number } @@ -47,10 +47,11 @@ interface ScreenOptions { before?: Size covers?: string[] timeout?: number + codes?: boolean } -function screen(slot: number, id: string, reach: (r: Reach) => Promise, { sizes = ["desktop", "phone"], before, timeout }: ScreenOptions = {}): void { - test(id, async ({ page, request, browser, baseURL }) => { +function screen(slot: number, id: string, reach: (r: Reach) => Promise, { sizes = ["desktop", "phone"], before, timeout, codes = false }: ScreenOptions = {}): void { + (codes ? codesTest : test)(id, async ({ page, request, browser, baseURL }) => { if (timeout) test.setTimeout(timeout) const now = START_S + slot * STEP_S await control(request, "clock", { now }) @@ -84,6 +85,7 @@ test.afterEach(async ({ page, request }) => { await Promise.all(launched.splice(0).map((browser) => browser.close())) await control(request, "search", { chainDown: false, limitSeconds: 0, findLimitSeconds: 0, invoiceError: null, unsentSeconds: 0, unreadSeconds: 0, fetchDelays: {} }) await control(request, "mode", { mode: "open" }) + await control(request, "downtime", { on: false }) await control(request, "general-terms", { text: null }) await control(request, "seed", { seed: null }) }) @@ -537,19 +539,19 @@ screen(194, "home-codes-only-locked", async ({ page, request }) => { await control(request, "mode", { mode: "codes" }) await page.goto("/#/?name=bakery") await shown(page, "Names can be registered only with a code right now.") -}) +}, { codes: true }) screen(196, "home-codes-only-uncovered", async (r) => { await control(r.request, "mode", { mode: "codes" }) await withCode(r, 7) await searchHere(r.page, "abcdef") await answerLine(r.page) -}) +}, { codes: true }) screen(198, "home-codes-only-covered", async (r) => { await control(r.request, "mode", { mode: "codes" }) await withCode(r, 7, { years: 2 }) await searchHere(r.page, r.id) await answerRow(r.page) -}) +}, { codes: true }) screen(200, "home-header-code-chip", async (r) => { await withCode(r, 7) }) screen(204, "home-phone-menu", async ({ page }) => { await page.goto("/") @@ -638,13 +640,13 @@ screen(226, "checkout-select-busy", async (r) => { screen(234, "checkout-select-code", (r) => codeReview(r)) screen(240, "checkout-select-terms-changed", async (r) => { await selectReview(r) - await control(r.request, "general-terms", { text: TERMS_TEXT }) + await control(r.request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) await press(r.page, "Register with your payment") await shown(r.page, "The Names Conditions changed.") }) const selectionRefusals: [number, string, number, string, Record?][] = [ [242, "checkout-select-refused-taken", 409, "name_taken"], - [244, "checkout-select-refused-price", 409, "catalog_changed", { price: 20000 }], + [244, "checkout-select-refused-price", 409, "catalog_changed", { price: 10000 }], [248, "checkout-select-refused-unavailable", 503, "terms_unavailable"], [250, "checkout-select-refused-failed", 503, "name_check_unavailable"], ] @@ -728,15 +730,6 @@ screen(1016, "checkout-review-unticked", async ({ page, id }) => { await search(page, id) await toReview(page, false) }) -screen(1018, "checkout-review-term-started", async ({ page, id }) => { - await page.route("**/api/config", async (route) => { - const res = await route.fetch() - const json = await res.json() - await route.fulfill({ response: res, json: { ...json, names: { ...json.names, termStart: START_S - 86400 } } }) - }) - await search(page, id) - await toReview(page) -}) screen(1020, "checkout-review-bonus-tip", async (r) => { await review(r) await onStep(r.page).getByRole("button", { name: /^and (\d+ days|1 day)$/ }).focus() @@ -810,7 +803,7 @@ screen(1078, "checkout-review-hold", async (r) => { }) screen(1080, "checkout-review-terms-changed", async (r) => { await review(r) - await control(r.request, "general-terms", { text: TERMS_TEXT }) + await control(r.request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) await payButton(r.page).click() await expect(onStep(r.page).getByRole("checkbox", { name: /^I accept/, checked: false })).toBeVisible() }) @@ -1119,7 +1112,7 @@ screen(1196, "checkout-review-codes-only-code", async (r) => { await withCode(r, 6) await searchHere(r.page, r.id) await toReview(r.page) -}) +}, { codes: true }) screen(1198, "checkout-review-codes-only-field", async (r) => { await control(r.request, "mode", { mode: "codes" }) await withCode(r, 6) @@ -1127,7 +1120,7 @@ screen(1198, "checkout-review-codes-only-field", async (r) => { await toReview(r.page) await r.page.locator(".code-chip").getByRole("button", { name: "Remove code" }).click() await expect(codeField(r.page)).toBeVisible() -}) +}, { codes: true }) screen(1200, "checkout-review-codes-only-refused", async (r) => { await control(r.request, "mode", { mode: "codes" }) const code = await withCode(r, 6) @@ -1136,7 +1129,7 @@ screen(1200, "checkout-review-codes-only-refused", async (r) => { await control(r.request, "code/state", { code, state: "used" }) await press(r.page, "Register with your code") await shown(r.page, "Enter another code.") -}) +}, { codes: true }) screen(1212, "checkout-review-waiting-card", async (r) => { await startOrder(r.page, `${r.id}-card`, { method: "card" }) await onStep(r.page).getByRole("button", { name: /^Pay \$/ }).click() @@ -1172,7 +1165,7 @@ screen(1224, "checkout-status-failed-retrying", async (r) => { }) screen(1226, "checkout-status-unavailable", (r) => refusedOrder(r, () => control(r.request, "general-terms", { link: UNREADABLE_TERMS }), "Names can't be ordered right now")) screen(1228, "checkout-status-unavailable-retrying", async (r) => { - await refusedOrder(r, () => control(r.request, "general-terms", { link: UNREADABLE_TERMS }), "Names can't be ordered right now") + await refusedOrder(r, () => r.page.route("**/api/invoice", posting(/\/api\/invoice$/, (route) => answer(route, 503, "terms_unavailable"))), "Names can't be ordered right now") await r.page.route("**/api/invoice", posting(/\/api\/invoice$/, held)) await press(r.page, "Try again") await expect(onStep(r.page).getByRole("button", { name: "Try again" })).toHaveAttribute("aria-busy", "true") @@ -1258,7 +1251,7 @@ screen(2014, "order-registering-signature-refused", async (r) => { const termsChangedOrder = async (r: Reach) => { const { invoiceId } = await ordered(r, r.id) - await control(r.request, "general-terms", { text: TERMS_TEXT }) + await control(r.request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) await control(r.request, `settle/${invoiceId}`) await expect(onStep(r.page).getByRole("checkbox", { name: /^I accept/ })).toBeVisible({ timeout: REGISTRATION_MS }) return invoiceId @@ -1268,7 +1261,7 @@ screen(2016, "order-registering-terms-asked", async (r) => { await termsChangedO screen(2018, "order-registering-community-terms-asked", async (r) => { await control(r.request, "community", { label: r.id, for: "screens of the names page" }) const { invoiceId } = await ordered(r, r.id) - await control(r.request, "community-terms", { text: "The community terms, changed for the screens" }) + await control(r.request, "community-terms", { text: ALTERNATE_COMMUNITY_TERMS }) await control(r.request, `settle/${invoiceId}`) await expect(onStep(r.page).getByRole("checkbox", { name: /^I accept/ })).toBeVisible({ timeout: REGISTRATION_MS }) await control(r.request, "community-terms", { text: null }) @@ -1282,7 +1275,7 @@ const goneWhileTermsWait = async (r: Reach, gone: Record, says: const { invoiceId } = await ordered(r, r.id) let answered = false await r.page.route(`**/api/name/${hex(labelHash(r.id))}*`, (route) => answered ? route.fulfill({ json: gone }) : route.fallback()) - await control(r.request, "general-terms", { text: TERMS_TEXT }) + await control(r.request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) answered = true await control(r.request, `settle/${invoiceId}`) await shown(r.page, says) @@ -1292,32 +1285,6 @@ screen(2022, "order-registering-name-registered-meanwhile", (r) => goneWhileTermsWait(r, registeredTo(OTHER_OWNER, START_S + 2 * YEAR_S), "The Names Conditions changed.")) screen(2024, "order-registering-name-reserved-meanwhile", (r) => goneWhileTermsWait(r, { found: { type: "reserved" } }, "The Names Conditions changed.")) screen(2026, "order-registering-lapsed", async (r) => { await lapsedOrder(r, r.id) }) -screen(2028, "order-lapsed-no-record", async (r) => { - const { invoiceId } = await lapsedOrder(r, r.id) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "The name code is not in this browser") - return other -}) -screen(2030, "order-registering-no-record-committing", async (r) => { - const { invoiceId } = await ordered(r, r.id) - await control(r.request, "search", { unsentSeconds: 120 }) - await control(r.request, `settle/${invoiceId}`) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await expect(onStep(other).getByRole("heading")).toBeVisible() - return other -}) -screen(2032, "order-registering-no-record-wait", async (r) => { - const { invoiceId } = await committedUnsigned(r, r.id) - const other = await elsewhere(r, "/#/trademarks") - await other.route(`**/api/invoice/${invoiceId}*`, async (route) => { - const res = await route.fetch() - const json = await res.json() - await route.fulfill({ response: res, json: { ...json, registration: { ...json.registration, phase: committedPhase(r) } } }) - }) - await other.goto(`/?order=${invoiceId}`) - await expect(onStep(other).getByRole("heading")).toBeVisible() - return other -}) const BALANCE = { amount: 10000, refunded: 0 } const codeOrderAs = async (r: Reach, change: Record) => { const order = await kept(r, `reg-${r.id}`, null, r.id) @@ -1339,12 +1306,6 @@ screen(2057, "order-taken-before-commit", async (r) => { await heading(r.page, `${r.id}.simplex is no longer available`) }) screen(2060, "order-failed-generic-paid", async (r) => { await failed(r, r.id) }) -screen(2062, "order-failed-generic-paid-no-record", async (r) => { - const { invoiceId } = await failed(r, r.id) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "Paid, not registered") - return other -}) screen(2064, "order-failed-generic-code-unchecked", async (r) => { await codeFailed(r, r.id) await r.page.route("**/api/code/check", () => new Promise(() => undefined)) @@ -1368,12 +1329,6 @@ screen(2070, "order-failed-generic-code-refused", async (r) => { await r.page.reload() await shown(r.page, "Your code was used for another name") }) -screen(2072, "order-failed-generic-code-no-record", async (r) => { - const { registrationId } = await codeFailed(r, r.id) - const other = await elsewhere(r, `/?registration=${registrationId}`) - await heading(other, "Not registered") - return other -}) screen(2084, "order-failed-name-gone-since", async (r) => { await failed(r, r.id) await control(r.request, "take", { label: r.id }) @@ -1420,18 +1375,12 @@ const unreadOrder = async (r: Reach) => { return order } screen(2094, "order-failed-unread-paid", async (r) => { await unreadOrder(r) }) -screen(2096, "order-failed-unread-paid-no-record", async (r) => { - const { invoiceId } = await unreadOrder(r) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "Paid, not registered") - return other -}) screen(2098, "order-failed-unread-code", async (r) => { await unsigned(r.page) const { registrationId } = await codeOrder(r, r.id) await control(r.request, `stale/${registrationId}`) await expect.poll(async () => { - const { phase, label } = await (await r.request.get(`${MOCK}/api/registration/${registrationId}`)).json() as { phase: { type: string }; label: string | null } + const { phase, label } = await (await r.request.get(`${MOCK}/control/registration/${registrationId}`)).json() as { phase: { type: string }; label: string | null } return phase.type === "committed" && label === null }, { timeout: REGISTRATION_MS }).toBe(true) await control(r.request, `unread/${registrationId}`) @@ -1452,7 +1401,8 @@ screen(2102, "order-failed-action-failed", (r) => continueRefused(r, (route) => const nameChecked = (page: Page) => expect(onStep(page).locator(".name-check:not(.unchecked)")).toBeVisible() const TAKEN_ANSWER = registeredTo(OTHER_OWNER, START_S + 2 * YEAR_S) const cancelAnswer = (page: Page, f: (route: Route) => Promise) => page.route("**/api/invoice/*/cancel", posting(/\/cancel$/, f)) -const STRIPE_STUB = (declines: boolean) => `window.Stripe = () => ({ +const STRIPE_STUB = (declines: boolean, amount: number) => `window.Stripe = () => ({ + retrievePaymentIntent: async () => (${fakeIntent(amount)}), confirmPayment: async () => (${declines} ? { error: { type: "card_error", message: "Your card was declined." } } : { paymentIntent: { status: "processing" } }), elements: () => ({ update: () => undefined, create: () => { const handlers = {} @@ -1486,12 +1436,6 @@ screen(2120, "order-pay-crypto-unchecked", async ({ page, id }) => { await heading(page, "Pay with Bitcoin") await page.waitForTimeout(1500) }) -screen(2122, "order-pay-crypto-no-record", async (r) => { - const { invoiceId } = await startOrder(r.page, r.id, { method: "btc" }) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "Pay with Bitcoin") - return other -}) screen(2124, "order-pay-crypto-part-paid", async (r) => { const { invoiceId } = await startOrder(r.page, r.id, { method: "btc" }) await control(r.request, `partial/${invoiceId}`) @@ -1543,16 +1487,10 @@ screen(2136, "order-pay-card-taken-on-chain", async ({ page, id }) => { await page.reload() await shown(page, "Taken at") }) -screen(2138, "order-pay-card-no-record", async (r) => { - const { invoiceId } = await startOrder(r.page, r.id, { method: "card" }) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "Pay by card") - return other -}) screen(2140, "order-pay-card-declined", async ({ page, id }) => { await startOrder(page, id, { method: "card" }) await withStripeKey(page) - await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: STRIPE_STUB(true) })) + await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: STRIPE_STUB(true, heldPrice(id.length)) })) await page.reload() await heading(page, "Pay by card") await nameChecked(page) @@ -1615,8 +1553,10 @@ const cardFormFailed = async (r: Reach, before: () => Promise = async ( await heading(r.page, "Card payment not confirmed") } screen(2156, "order-card-form-failed", (r) => cardFormFailed(r)) -screen(2158, "order-card-form-failed-no-record", (r) => cardFormFailed(r, () => r.page.evaluate(() => localStorage.clear()))) -screen(2160, "order-card-form-failed-codes-only", (r) => cardFormFailed(r, () => control(r.request, "mode", { mode: "codes" }))) +screen(2160, "order-card-form-failed-codes-only", (r) => cardFormFailed(r, async () => { + await control(r.request, "mode", { mode: "codes" }) + await onCodesPage(r.page) +})) const cardSlow = async (r: Reach) => { const invoiceId = await cardSubmitted(r.page, r.id) await r.page.evaluate(([id, at]) => { @@ -1643,25 +1583,6 @@ screen(2166, "order-paid-by-invoice-record", async (r) => { await r.page.goto(`/?registration=${await registrationOf(r.request, invoiceId)}`) await heading(r.page, "This order is paid by invoice") }) -screen(2168, "order-paid-by-invoice-no-record", async (r) => { - const { invoiceId } = await startOrder(r.page, r.id, { method: "btc" }) - const other = await elsewhere(r, `/?registration=${await registrationOf(r.request, invoiceId)}`) - await heading(other, "This order is paid by invoice") - return other -}) -screen(2170, "order-registering-no-record-signed", async (r) => { - const order = await kept(r, `reg-${r.id}`, `inv-${r.id}`, r.id) - const view = registrationView(order, { phase: { type: "registering" }, commitTx: "0x02", registerTx: "0x03" }) - const other = await elsewhere(r, "/#/trademarks") - await other.route(`**/api/invoice/inv-${r.id}*`, (route) => route.fulfill({ json: { - invoiceId: `inv-${r.id}`, status: "paid", amount: 10000, currency: "usd", expiresAt: new Date((r.now + 3600) * 1000).toISOString(), kind: "name", registration: view, - cryptoCurrency: "btc", cryptoAmount: "0.00156", cryptoAmountPaid: "0.00156", cryptoAmountDue: "0", paidInFull: true, address: "bcrt1qjhmc6927ct4w4vnas0g70pg3sdhgfdhcl8pd7s", - } })) - await other.route(`**/api/registration/reg-${r.id}*`, (route) => route.fulfill({ json: view })) - await other.goto(`/?order=inv-${r.id}`) - await heading(other, `Registering ${r.id}.simplex`) - return other -}) screen(2172, "order-not-on-device", async (r) => { const { invoiceId } = await committedUnsigned(r, r.id) const other = await elsewhere(r, `/?order=${invoiceId}`) @@ -1678,14 +1599,6 @@ screen(2176, "order-registered-no-links", async (r) => { await control(r.request, `settle/${invoiceId}`) await waitRegistered(r.page, r.id) }) -screen(2178, "order-registered-no-record", async (r) => { - const { invoiceId } = await ordered(r, r.id) - await control(r.request, `settle/${invoiceId}`) - await waitRegistered(r.page, r.id) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, `${r.id}.simplex is yours`) - return other -}) screen(2179, "order-ended", async (r) => { const { invoiceId, registrationId } = await ordered(r, r.id) await control(r.request, `settle/${invoiceId}`) @@ -1702,12 +1615,6 @@ screen(2182, "order-taken-reserved", async (r) => { await control(r.request, `settle/${invoiceId}`) await heading(r.page, `${r.id}.simplex is reserved`) }) -screen(2184, "order-taken-no-record", async (r) => { - const { invoiceId } = await takenOrder(r.page, r.request, r.id) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, `${r.id}.simplex is no longer available`) - return other -}) screen(2186, "order-taken-balance-spent", async (r) => { const { invoiceId } = await takenOrder(r.page, r.request, r.id) await control(r.request, `refund/${invoiceId}`) @@ -1717,7 +1624,7 @@ screen(2186, "order-taken-balance-spent", async (r) => { screen(2190, "order-taken-codes-only", async (r) => { await takenOrder(r.page, r.request, r.id) await control(r.request, "mode", { mode: "codes" }) - await r.page.reload() + await onCodesPage(r.page) await shown(r.page, "You can ask for a refund.") }) const codeTaken = async (r: Reach) => { @@ -1739,13 +1646,6 @@ screen(2196, "order-taken-code-reserved", async (r) => { await answersReserved(r.page, r.id) await heading(r.page, `${r.id}.simplex is reserved`) }) -screen(2198, "order-taken-code-no-record", async (r) => { - const registrationId = await codeTaken(r) - await heading(r.page, `${r.id}.simplex is no longer available`) - const other = await elsewhere(r, `/?registration=${registrationId}`) - await heading(other, `${r.id}.simplex is no longer available`) - return other -}) const closed = async (r: Reach, method: "btc" | "card" = "btc") => { const { invoiceId } = await startOrder(r.page, r.id, { method }) await control(r.request, `expire/${invoiceId}`) @@ -1754,19 +1654,13 @@ const closed = async (r: Reach, method: "btc" | "card" = "btc") => { } screen(2200, "order-closed-expired-crypto", async (r) => { await closed(r) }) screen(2202, "order-closed-expired-card", async (r) => { await closed(r, "card") }) -screen(2204, "order-closed-expired-no-record", async (r) => { - const invoiceId = await closed(r) - const other = await elsewhere(r, `/?order=${invoiceId}`) - await heading(other, "Invoice closed") - return other -}) screen(2206, "order-closed-cancelled", async ({ page, id }) => { await startOrder(page, id, { method: "btc" }) await press(page, "Cancel this invoice") await heading(page, "Invoice closed") }) const halfOf = async (r: Reach, invoiceId: string) => { - const invoice = await (await r.request.get(`${MOCK}/api/invoice/${invoiceId}`)).json() as { cryptoAmountPaid: string } + const invoice = await (await r.request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { cryptoAmountPaid: string } return invoice.cryptoAmountPaid } const closedPart = async (r: Reach) => { @@ -1828,12 +1722,12 @@ screen(2222, "order-closed-replaced", async (r) => { screen(2224, "order-closed-codes-only", async (r) => { await closed(r) await control(r.request, "mode", { mode: "codes" }) - await r.page.reload() + await onCodesPage(r.page) await heading(r.page, "Invoice closed") }) screen(2226, "order-closed-terms-asked", async (r) => { await closed(r) - await control(r.request, "general-terms", { text: TERMS_TEXT }) + await control(r.request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) await press(r.page, "Get a new invoice") await expect(onStep(r.page).getByRole("checkbox", { name: /^I accept/, checked: false })).toBeVisible() }) @@ -1869,19 +1763,22 @@ screen(2246, "order-price-changed", async (r) => { await press(r.page, "Get a new invoice") await heading(r.page, "The price changed") }) -screen(2248, "order-unreadable", async ({ page, id }) => { - await page.route(`**/api/invoice/inv-${id}*`, (route) => answer(route, 500, "internal")) - await page.goto(`/?order=inv-${id}`) - await heading(page, "The order could not be loaded now") +screen(2248, "order-unreadable", async (r) => { + await kept(r, `reg-${r.id}`, `inv-${r.id}`, r.id) + await r.page.route(`**/api/invoice/inv-${r.id}*`, (route) => answer(route, 500, "internal")) + await r.page.goto(`/?order=inv-${r.id}`) + await heading(r.page, "The order could not be loaded now") }) -screen(2250, "order-loading", async ({ page, id }) => { - await page.route(`**/api/invoice/inv-${id}*`, held) - await page.goto(`/?order=inv-${id}`) - await shown(page, "Opening the order") +screen(2250, "order-loading", async (r) => { + await kept(r, `reg-${r.id}`, `inv-${r.id}`, r.id) + await r.page.route(`**/api/invoice/inv-${r.id}*`, held) + await r.page.goto(`/?order=inv-${r.id}`) + await shown(r.page, "Opening the order") }) -screen(2252, "order-unknown-link", async ({ page }) => { - await page.goto("/?order=nothing-here") - await heading(page, "This link does not work") +screen(2252, "order-unknown-link", async (r) => { + await kept(r, `reg-${r.id}`, "nothing-here", r.id) + await r.page.goto("/?order=nothing-here") + await heading(r.page, "This link does not work") }) const REVERSED = { phase: { type: "closed", closedBy: "reversed" } } screen(2254, "order-closed-reversed", async (r) => { @@ -2016,8 +1913,8 @@ screen(3030, "names-edit-field-noncanonical-kept", async (r) => { }) const listRow = (page: Page, text: string) => page.locator(".list-row", { hasText: text }).first() -const yourNames = async (page: Page, rows: string[] = []) => { - await page.goto("/#/names") +const yourNames = async (page: Page, rows: string[] = [], origin = "") => { + await page.goto(`${origin}/#/names`) await heading(page, "Your names") for (const text of rows) await expect(listRow(page, text)).toBeVisible({ timeout: 30_000 }) await page.waitForTimeout(2000) @@ -2166,7 +2063,7 @@ screen(3046, "names-rows-registered", async (r) => { await registered(r, "rows-community") const expiresAt = START_S + 2 * YEAR_S const other = await faked(r, "rows-other-owner", { phase: registeredPhase(expiresAt), commitTx: "0x02", registerTx: "0x03" }) - await answerName(r.page, "rows-other-owner", registeredFor(other, expiresAt, CHAIN.sponsor)) + await answerName(r.page, "rows-other-owner", registeredFor(other, expiresAt, LOCAL.sponsor)) const expired = await faked(r, "rows-expired", { phase: registeredPhase(r.now - 86400), commitTx: "0x02", registerTx: "0x03" }) await answerName(r.page, "rows-expired", registeredFor(expired, r.now - 86400)) await r.page.route(`**/api/name/${hex(labelHash("rows-answer-failed"))}*`, (route) => answer(route, 503, "unavailable")) @@ -2179,7 +2076,7 @@ const BALANCE_ROWS = ["names-balance-taken", "names-balance-rest", "names-balanc screen(3048, "names-rows-balances", async (r) => { await takenOrder(r.page, r.request, "rows-balance-taken") const rest = await startOrder(r.page, "rows-balance-rest", { method: "btc" }) - const due = await (await r.request.get(`${MOCK}/api/invoice/${rest.invoiceId}`)).json() as { cryptoAmount: string } + const due = await (await r.request.get(`${MOCK}/control/invoice/${rest.invoiceId}`)).json() as { cryptoAmount: string } await control(r.request, `settle/${rest.invoiceId}`, { paid: (Number(due.cryptoAmount) * 2).toFixed(8) }) await waitRegistered(r.page, "rows-balance-rest") const whole = await takenOrder(r.page, r.request, "rows-refunded-whole") @@ -2252,7 +2149,8 @@ screen(3054, "names-pending-held", async (r) => { screen(3056, "names-balance-taken-codes-only", async (r) => { await takenOrder(r.page, r.request, r.id) await control(r.request, "mode", { mode: "codes" }) - await yourNames(r.page, [r.id]) + await codesPageHolds(r.page) + await yourNames(r.page, [r.id], CODES_PAGE) }) screen(3058, "names-popup-refund", async (r) => { await takenOrder(r.page, r.request, r.id) @@ -2395,7 +2293,7 @@ screen(3118, "names-check-from-order", async (r) => { await control(r.request, `settle/${invoiceId}`) await waitRegistered(r.page, r.id) const other = await elsewhere(r, `/?order=${invoiceId}`) - await press(other, "Restore with your name code") + await press(other, "Enter your name code") await codeField(other).fill(ownerCode) await verdict(other) return other @@ -2649,3 +2547,28 @@ screen(3198, "names-balance-ended", async (r) => { await yourNames(r.page, [r.id]) }) +screen(3200, "home-available-downtime", async ({ page, request, id }) => { + await control(request, "downtime", { on: true }) + await search(page, id) + await answerRow(page) + await shown(page, "You will be able to order names again soon.") +}) +screen(3202, "checkout-status-downtime", async ({ page, request, id }) => { + await search(page, id) + await toReview(page) + await control(request, "downtime", { on: true }) + await payButton(page).click() + await heading(page, "You will be able to order names again soon") +}) +screen(3204, "order-pay-crypto-downtime", async (r) => { + await ordered(r, r.id) + await control(r.request, "downtime", { on: true }) + await r.page.reload() + await shown(r.page, "You will be able to pay again soon.") +}) + +screen(17200, "checkout-review-term-started", async ({ page, id }) => { + await search(page, id) + await toReview(page) +}) + diff --git a/webapp/e2e/screens/checkout-code-no-storage-desktop.png b/webapp/e2e/screens/checkout-code-no-storage-desktop.png index b395cd0c..d8fce0f5 100644 Binary files a/webapp/e2e/screens/checkout-code-no-storage-desktop.png and b/webapp/e2e/screens/checkout-code-no-storage-desktop.png differ diff --git a/webapp/e2e/screens/checkout-code-no-storage-phone.png b/webapp/e2e/screens/checkout-code-no-storage-phone.png index 1eeada91..5879e03c 100644 Binary files a/webapp/e2e/screens/checkout-code-no-storage-phone.png and b/webapp/e2e/screens/checkout-code-no-storage-phone.png differ diff --git a/webapp/e2e/screens/checkout-code-saved-desktop.png b/webapp/e2e/screens/checkout-code-saved-desktop.png index 60dd60a6..2d58224c 100644 Binary files a/webapp/e2e/screens/checkout-code-saved-desktop.png and b/webapp/e2e/screens/checkout-code-saved-desktop.png differ diff --git a/webapp/e2e/screens/checkout-code-saved-phone.png b/webapp/e2e/screens/checkout-code-saved-phone.png index af42461d..86c30e04 100644 Binary files a/webapp/e2e/screens/checkout-code-saved-phone.png and b/webapp/e2e/screens/checkout-code-saved-phone.png differ diff --git a/webapp/e2e/screens/checkout-code-shown-desktop.png b/webapp/e2e/screens/checkout-code-shown-desktop.png index 96afc400..f38af60b 100644 Binary files a/webapp/e2e/screens/checkout-code-shown-desktop.png and b/webapp/e2e/screens/checkout-code-shown-desktop.png differ diff --git a/webapp/e2e/screens/checkout-code-shown-phone.png b/webapp/e2e/screens/checkout-code-shown-phone.png index f356f246..59482cf8 100644 Binary files a/webapp/e2e/screens/checkout-code-shown-phone.png and b/webapp/e2e/screens/checkout-code-shown-phone.png differ diff --git a/webapp/e2e/screens/checkout-code-unsaved-desktop.png b/webapp/e2e/screens/checkout-code-unsaved-desktop.png index 57290832..1593ee2c 100644 Binary files a/webapp/e2e/screens/checkout-code-unsaved-desktop.png and b/webapp/e2e/screens/checkout-code-unsaved-desktop.png differ diff --git a/webapp/e2e/screens/checkout-code-unsaved-phone.png b/webapp/e2e/screens/checkout-code-unsaved-phone.png index c7c023f1..7f26d1d5 100644 Binary files a/webapp/e2e/screens/checkout-code-unsaved-phone.png and b/webapp/e2e/screens/checkout-code-unsaved-phone.png differ diff --git a/webapp/e2e/screens/checkout-review-term-started-desktop.png b/webapp/e2e/screens/checkout-review-term-started-desktop.png index 058214a5..fa04df56 100644 Binary files a/webapp/e2e/screens/checkout-review-term-started-desktop.png and b/webapp/e2e/screens/checkout-review-term-started-desktop.png differ diff --git a/webapp/e2e/screens/checkout-review-term-started-phone.png b/webapp/e2e/screens/checkout-review-term-started-phone.png index 0a88d7d2..9d218741 100644 Binary files a/webapp/e2e/screens/checkout-review-term-started-phone.png and b/webapp/e2e/screens/checkout-review-term-started-phone.png differ diff --git a/webapp/e2e/screens/checkout-select-refused-price-desktop.png b/webapp/e2e/screens/checkout-select-refused-price-desktop.png index ac73b509..3d40b8e4 100644 Binary files a/webapp/e2e/screens/checkout-select-refused-price-desktop.png and b/webapp/e2e/screens/checkout-select-refused-price-desktop.png differ diff --git a/webapp/e2e/screens/checkout-select-refused-price-phone.png b/webapp/e2e/screens/checkout-select-refused-price-phone.png index e39989db..81e8d6f6 100644 Binary files a/webapp/e2e/screens/checkout-select-refused-price-phone.png and b/webapp/e2e/screens/checkout-select-refused-price-phone.png differ diff --git a/webapp/e2e/screens/checkout-select-selected-elsewhere-desktop.png b/webapp/e2e/screens/checkout-select-selected-elsewhere-desktop.png index a02a98d3..cc291d6d 100644 Binary files a/webapp/e2e/screens/checkout-select-selected-elsewhere-desktop.png and b/webapp/e2e/screens/checkout-select-selected-elsewhere-desktop.png differ diff --git a/webapp/e2e/screens/checkout-select-selected-elsewhere-phone.png b/webapp/e2e/screens/checkout-select-selected-elsewhere-phone.png index 479d96f1..60ee8494 100644 Binary files a/webapp/e2e/screens/checkout-select-selected-elsewhere-phone.png and b/webapp/e2e/screens/checkout-select-selected-elsewhere-phone.png differ diff --git a/webapp/e2e/screens/checkout-status-downtime-desktop.png b/webapp/e2e/screens/checkout-status-downtime-desktop.png new file mode 100644 index 00000000..77aa2768 Binary files /dev/null and b/webapp/e2e/screens/checkout-status-downtime-desktop.png differ diff --git a/webapp/e2e/screens/checkout-status-downtime-phone.png b/webapp/e2e/screens/checkout-status-downtime-phone.png new file mode 100644 index 00000000..267c87fe Binary files /dev/null and b/webapp/e2e/screens/checkout-status-downtime-phone.png differ diff --git a/webapp/e2e/screens/checkout-status-price-changed-desktop.png b/webapp/e2e/screens/checkout-status-price-changed-desktop.png index a0fb9884..4974dde9 100644 Binary files a/webapp/e2e/screens/checkout-status-price-changed-desktop.png and b/webapp/e2e/screens/checkout-status-price-changed-desktop.png differ diff --git a/webapp/e2e/screens/checkout-status-price-changed-phone.png b/webapp/e2e/screens/checkout-status-price-changed-phone.png index 7f387800..59df1c7f 100644 Binary files a/webapp/e2e/screens/checkout-status-price-changed-phone.png and b/webapp/e2e/screens/checkout-status-price-changed-phone.png differ diff --git a/webapp/e2e/screens/home-available-downtime-desktop.png b/webapp/e2e/screens/home-available-downtime-desktop.png new file mode 100644 index 00000000..d08d2bc5 Binary files /dev/null and b/webapp/e2e/screens/home-available-downtime-desktop.png differ diff --git a/webapp/e2e/screens/home-available-downtime-phone.png b/webapp/e2e/screens/home-available-downtime-phone.png new file mode 100644 index 00000000..8fe3d283 Binary files /dev/null and b/webapp/e2e/screens/home-available-downtime-phone.png differ diff --git a/webapp/e2e/screens/home-select-failed-order-desktop.png b/webapp/e2e/screens/home-select-failed-order-desktop.png index c7682539..88274ffc 100644 Binary files a/webapp/e2e/screens/home-select-failed-order-desktop.png and b/webapp/e2e/screens/home-select-failed-order-desktop.png differ diff --git a/webapp/e2e/screens/home-select-failed-order-phone.png b/webapp/e2e/screens/home-select-failed-order-phone.png index 66dc27a5..1cebe6e9 100644 Binary files a/webapp/e2e/screens/home-select-failed-order-phone.png and b/webapp/e2e/screens/home-select-failed-order-phone.png differ diff --git a/webapp/e2e/screens/home-select-selected-elsewhere-desktop.png b/webapp/e2e/screens/home-select-selected-elsewhere-desktop.png index 81cfd718..9538f2c8 100644 Binary files a/webapp/e2e/screens/home-select-selected-elsewhere-desktop.png and b/webapp/e2e/screens/home-select-selected-elsewhere-desktop.png differ diff --git a/webapp/e2e/screens/home-select-selected-elsewhere-phone.png b/webapp/e2e/screens/home-select-selected-elsewhere-phone.png index 289ed962..c928894a 100644 Binary files a/webapp/e2e/screens/home-select-selected-elsewhere-phone.png and b/webapp/e2e/screens/home-select-selected-elsewhere-phone.png differ diff --git a/webapp/e2e/screens/home-select-unpaid-desktop.png b/webapp/e2e/screens/home-select-unpaid-desktop.png index e979dbe5..4383a338 100644 Binary files a/webapp/e2e/screens/home-select-unpaid-desktop.png and b/webapp/e2e/screens/home-select-unpaid-desktop.png differ diff --git a/webapp/e2e/screens/home-select-unpaid-phone.png b/webapp/e2e/screens/home-select-unpaid-phone.png index ec0ea334..b6701617 100644 Binary files a/webapp/e2e/screens/home-select-unpaid-phone.png and b/webapp/e2e/screens/home-select-unpaid-phone.png differ diff --git a/webapp/e2e/screens/names-check-add-held-desktop.png b/webapp/e2e/screens/names-check-add-held-desktop.png index 14a81d4b..90c696b6 100644 Binary files a/webapp/e2e/screens/names-check-add-held-desktop.png and b/webapp/e2e/screens/names-check-add-held-desktop.png differ diff --git a/webapp/e2e/screens/names-check-add-held-phone.png b/webapp/e2e/screens/names-check-add-held-phone.png index a48a2d23..70d7224f 100644 Binary files a/webapp/e2e/screens/names-check-add-held-phone.png and b/webapp/e2e/screens/names-check-add-held-phone.png differ diff --git a/webapp/e2e/screens/names-check-add-none-desktop.png b/webapp/e2e/screens/names-check-add-none-desktop.png index 2e8bd08b..88a8e579 100644 Binary files a/webapp/e2e/screens/names-check-add-none-desktop.png and b/webapp/e2e/screens/names-check-add-none-desktop.png differ diff --git a/webapp/e2e/screens/names-check-add-none-phone.png b/webapp/e2e/screens/names-check-add-none-phone.png index 6fe3a756..7967cfd6 100644 Binary files a/webapp/e2e/screens/names-check-add-none-phone.png and b/webapp/e2e/screens/names-check-add-none-phone.png differ diff --git a/webapp/e2e/screens/names-check-add-other-desktop.png b/webapp/e2e/screens/names-check-add-other-desktop.png index 2a14530a..fff9c180 100644 Binary files a/webapp/e2e/screens/names-check-add-other-desktop.png and b/webapp/e2e/screens/names-check-add-other-desktop.png differ diff --git a/webapp/e2e/screens/names-check-add-other-phone.png b/webapp/e2e/screens/names-check-add-other-phone.png index 4f84e134..535e3a06 100644 Binary files a/webapp/e2e/screens/names-check-add-other-phone.png and b/webapp/e2e/screens/names-check-add-other-phone.png differ diff --git a/webapp/e2e/screens/names-check-add-unasked-desktop.png b/webapp/e2e/screens/names-check-add-unasked-desktop.png index 7ba4cac3..3454bcd5 100644 Binary files a/webapp/e2e/screens/names-check-add-unasked-desktop.png and b/webapp/e2e/screens/names-check-add-unasked-desktop.png differ diff --git a/webapp/e2e/screens/names-check-add-unasked-phone.png b/webapp/e2e/screens/names-check-add-unasked-phone.png index b37e8173..7927c5e2 100644 Binary files a/webapp/e2e/screens/names-check-add-unasked-phone.png and b/webapp/e2e/screens/names-check-add-unasked-phone.png differ diff --git a/webapp/e2e/screens/names-check-adding-desktop.png b/webapp/e2e/screens/names-check-adding-desktop.png index a9d3ee6b..81b966d8 100644 Binary files a/webapp/e2e/screens/names-check-adding-desktop.png and b/webapp/e2e/screens/names-check-adding-desktop.png differ diff --git a/webapp/e2e/screens/names-check-adding-phone.png b/webapp/e2e/screens/names-check-adding-phone.png index ff8cead9..7748fe11 100644 Binary files a/webapp/e2e/screens/names-check-adding-phone.png and b/webapp/e2e/screens/names-check-adding-phone.png differ diff --git a/webapp/e2e/screens/names-check-from-order-desktop.png b/webapp/e2e/screens/names-check-from-order-desktop.png index 08d7de4c..9984faff 100644 Binary files a/webapp/e2e/screens/names-check-from-order-desktop.png and b/webapp/e2e/screens/names-check-from-order-desktop.png differ diff --git a/webapp/e2e/screens/names-check-from-order-phone.png b/webapp/e2e/screens/names-check-from-order-phone.png index 79a80ab5..6a402e6e 100644 Binary files a/webapp/e2e/screens/names-check-from-order-phone.png and b/webapp/e2e/screens/names-check-from-order-phone.png differ diff --git a/webapp/e2e/screens/names-check-owner-found-desktop.png b/webapp/e2e/screens/names-check-owner-found-desktop.png index 2282e1aa..3b1cfce0 100644 Binary files a/webapp/e2e/screens/names-check-owner-found-desktop.png and b/webapp/e2e/screens/names-check-owner-found-desktop.png differ diff --git a/webapp/e2e/screens/names-check-owner-found-phone.png b/webapp/e2e/screens/names-check-owner-found-phone.png index 70bc4c64..d1fc5e01 100644 Binary files a/webapp/e2e/screens/names-check-owner-found-phone.png and b/webapp/e2e/screens/names-check-owner-found-phone.png differ diff --git a/webapp/e2e/screens/names-list-config-unread-always-desktop.png b/webapp/e2e/screens/names-list-config-unread-always-desktop.png index 83458c69..2658dbef 100644 Binary files a/webapp/e2e/screens/names-list-config-unread-always-desktop.png and b/webapp/e2e/screens/names-list-config-unread-always-desktop.png differ diff --git a/webapp/e2e/screens/names-list-config-unread-always-phone.png b/webapp/e2e/screens/names-list-config-unread-always-phone.png index 1775fda5..b95f2323 100644 Binary files a/webapp/e2e/screens/names-list-config-unread-always-phone.png and b/webapp/e2e/screens/names-list-config-unread-always-phone.png differ diff --git a/webapp/e2e/screens/names-pending-config-unread-desktop.png b/webapp/e2e/screens/names-pending-config-unread-desktop.png index 85275eb0..42dc99fb 100644 Binary files a/webapp/e2e/screens/names-pending-config-unread-desktop.png and b/webapp/e2e/screens/names-pending-config-unread-desktop.png differ diff --git a/webapp/e2e/screens/names-pending-config-unread-phone.png b/webapp/e2e/screens/names-pending-config-unread-phone.png index e08087d7..ce290ea2 100644 Binary files a/webapp/e2e/screens/names-pending-config-unread-phone.png and b/webapp/e2e/screens/names-pending-config-unread-phone.png differ diff --git a/webapp/e2e/screens/names-rows-registered-desktop.png b/webapp/e2e/screens/names-rows-registered-desktop.png index 56f1820c..8bdfdbbf 100644 Binary files a/webapp/e2e/screens/names-rows-registered-desktop.png and b/webapp/e2e/screens/names-rows-registered-desktop.png differ diff --git a/webapp/e2e/screens/names-rows-registered-phone.png b/webapp/e2e/screens/names-rows-registered-phone.png index d6f82d50..958b2713 100644 Binary files a/webapp/e2e/screens/names-rows-registered-phone.png and b/webapp/e2e/screens/names-rows-registered-phone.png differ diff --git a/webapp/e2e/screens/order-card-form-failed-no-record-desktop.png b/webapp/e2e/screens/order-card-form-failed-no-record-desktop.png deleted file mode 100644 index 60f86bff..00000000 Binary files a/webapp/e2e/screens/order-card-form-failed-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-card-form-failed-no-record-phone.png b/webapp/e2e/screens/order-card-form-failed-no-record-phone.png deleted file mode 100644 index 9d6711af..00000000 Binary files a/webapp/e2e/screens/order-card-form-failed-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-closed-cancelled-desktop.png b/webapp/e2e/screens/order-closed-cancelled-desktop.png index 6acd5253..a10ae960 100644 Binary files a/webapp/e2e/screens/order-closed-cancelled-desktop.png and b/webapp/e2e/screens/order-closed-cancelled-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-cancelled-phone.png b/webapp/e2e/screens/order-closed-cancelled-phone.png index dce8a8d8..bf975508 100644 Binary files a/webapp/e2e/screens/order-closed-cancelled-phone.png and b/webapp/e2e/screens/order-closed-cancelled-phone.png differ diff --git a/webapp/e2e/screens/order-closed-codes-only-desktop.png b/webapp/e2e/screens/order-closed-codes-only-desktop.png index 6ec4b915..47d4d87e 100644 Binary files a/webapp/e2e/screens/order-closed-codes-only-desktop.png and b/webapp/e2e/screens/order-closed-codes-only-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-codes-only-phone.png b/webapp/e2e/screens/order-closed-codes-only-phone.png index f571aa32..6831e7d3 100644 Binary files a/webapp/e2e/screens/order-closed-codes-only-phone.png and b/webapp/e2e/screens/order-closed-codes-only-phone.png differ diff --git a/webapp/e2e/screens/order-closed-expired-crypto-desktop.png b/webapp/e2e/screens/order-closed-expired-crypto-desktop.png index c2e7ee9c..57774a78 100644 Binary files a/webapp/e2e/screens/order-closed-expired-crypto-desktop.png and b/webapp/e2e/screens/order-closed-expired-crypto-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-expired-crypto-phone.png b/webapp/e2e/screens/order-closed-expired-crypto-phone.png index 8849d432..d00ebbdf 100644 Binary files a/webapp/e2e/screens/order-closed-expired-crypto-phone.png and b/webapp/e2e/screens/order-closed-expired-crypto-phone.png differ diff --git a/webapp/e2e/screens/order-closed-expired-no-record-desktop.png b/webapp/e2e/screens/order-closed-expired-no-record-desktop.png deleted file mode 100644 index c17343f3..00000000 Binary files a/webapp/e2e/screens/order-closed-expired-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-closed-expired-no-record-phone.png b/webapp/e2e/screens/order-closed-expired-no-record-phone.png deleted file mode 100644 index 2511e454..00000000 Binary files a/webapp/e2e/screens/order-closed-expired-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-closed-late-confirming-desktop.png b/webapp/e2e/screens/order-closed-late-confirming-desktop.png index 9c41f624..8dc6c7d0 100644 Binary files a/webapp/e2e/screens/order-closed-late-confirming-desktop.png and b/webapp/e2e/screens/order-closed-late-confirming-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-late-confirming-phone.png b/webapp/e2e/screens/order-closed-late-confirming-phone.png index a5daa0b0..e454f010 100644 Binary files a/webapp/e2e/screens/order-closed-late-confirming-phone.png and b/webapp/e2e/screens/order-closed-late-confirming-phone.png differ diff --git a/webapp/e2e/screens/order-closed-paid-late-offer-desktop.png b/webapp/e2e/screens/order-closed-paid-late-offer-desktop.png index 97ad59d9..fe091d4a 100644 Binary files a/webapp/e2e/screens/order-closed-paid-late-offer-desktop.png and b/webapp/e2e/screens/order-closed-paid-late-offer-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-paid-late-offer-phone.png b/webapp/e2e/screens/order-closed-paid-late-offer-phone.png index 343dee8c..36b3a11d 100644 Binary files a/webapp/e2e/screens/order-closed-paid-late-offer-phone.png and b/webapp/e2e/screens/order-closed-paid-late-offer-phone.png differ diff --git a/webapp/e2e/screens/order-closed-paid-late-support-desktop.png b/webapp/e2e/screens/order-closed-paid-late-support-desktop.png index f3310836..1c8f3b68 100644 Binary files a/webapp/e2e/screens/order-closed-paid-late-support-desktop.png and b/webapp/e2e/screens/order-closed-paid-late-support-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-paid-late-support-phone.png b/webapp/e2e/screens/order-closed-paid-late-support-phone.png index e6df8d92..441bcc6e 100644 Binary files a/webapp/e2e/screens/order-closed-paid-late-support-phone.png and b/webapp/e2e/screens/order-closed-paid-late-support-phone.png differ diff --git a/webapp/e2e/screens/order-closed-received-confirming-desktop.png b/webapp/e2e/screens/order-closed-received-confirming-desktop.png index 1a4cb789..5cf99c8a 100644 Binary files a/webapp/e2e/screens/order-closed-received-confirming-desktop.png and b/webapp/e2e/screens/order-closed-received-confirming-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-received-confirming-phone.png b/webapp/e2e/screens/order-closed-received-confirming-phone.png index 45384d66..7c3d2ff1 100644 Binary files a/webapp/e2e/screens/order-closed-received-confirming-phone.png and b/webapp/e2e/screens/order-closed-received-confirming-phone.png differ diff --git a/webapp/e2e/screens/order-closed-received-crediting-desktop.png b/webapp/e2e/screens/order-closed-received-crediting-desktop.png index 8beaca2f..d27c5a08 100644 Binary files a/webapp/e2e/screens/order-closed-received-crediting-desktop.png and b/webapp/e2e/screens/order-closed-received-crediting-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-received-crediting-phone.png b/webapp/e2e/screens/order-closed-received-crediting-phone.png index f633d217..91c79f79 100644 Binary files a/webapp/e2e/screens/order-closed-received-crediting-phone.png and b/webapp/e2e/screens/order-closed-received-crediting-phone.png differ diff --git a/webapp/e2e/screens/order-closed-received-offer-desktop.png b/webapp/e2e/screens/order-closed-received-offer-desktop.png index f54b5c63..44a9e6ed 100644 Binary files a/webapp/e2e/screens/order-closed-received-offer-desktop.png and b/webapp/e2e/screens/order-closed-received-offer-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-received-offer-phone.png b/webapp/e2e/screens/order-closed-received-offer-phone.png index bf939d51..990b7e79 100644 Binary files a/webapp/e2e/screens/order-closed-received-offer-phone.png and b/webapp/e2e/screens/order-closed-received-offer-phone.png differ diff --git a/webapp/e2e/screens/order-closed-received-support-desktop.png b/webapp/e2e/screens/order-closed-received-support-desktop.png index 47975d37..24fcac62 100644 Binary files a/webapp/e2e/screens/order-closed-received-support-desktop.png and b/webapp/e2e/screens/order-closed-received-support-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-received-support-phone.png b/webapp/e2e/screens/order-closed-received-support-phone.png index 952eb058..0d42a0ea 100644 Binary files a/webapp/e2e/screens/order-closed-received-support-phone.png and b/webapp/e2e/screens/order-closed-received-support-phone.png differ diff --git a/webapp/e2e/screens/order-closed-replaced-desktop.png b/webapp/e2e/screens/order-closed-replaced-desktop.png index e2225f1f..7c6382a5 100644 Binary files a/webapp/e2e/screens/order-closed-replaced-desktop.png and b/webapp/e2e/screens/order-closed-replaced-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-replaced-phone.png b/webapp/e2e/screens/order-closed-replaced-phone.png index 70a08a19..124aa1df 100644 Binary files a/webapp/e2e/screens/order-closed-replaced-phone.png and b/webapp/e2e/screens/order-closed-replaced-phone.png differ diff --git a/webapp/e2e/screens/order-closed-terms-asked-desktop.png b/webapp/e2e/screens/order-closed-terms-asked-desktop.png index 3c538ae5..0337c7dd 100644 Binary files a/webapp/e2e/screens/order-closed-terms-asked-desktop.png and b/webapp/e2e/screens/order-closed-terms-asked-desktop.png differ diff --git a/webapp/e2e/screens/order-closed-terms-asked-phone.png b/webapp/e2e/screens/order-closed-terms-asked-phone.png index a63b1366..3007f5b7 100644 Binary files a/webapp/e2e/screens/order-closed-terms-asked-phone.png and b/webapp/e2e/screens/order-closed-terms-asked-phone.png differ diff --git a/webapp/e2e/screens/order-confirming-crypto-desktop.png b/webapp/e2e/screens/order-confirming-crypto-desktop.png index f6fe4b25..036d99d7 100644 Binary files a/webapp/e2e/screens/order-confirming-crypto-desktop.png and b/webapp/e2e/screens/order-confirming-crypto-desktop.png differ diff --git a/webapp/e2e/screens/order-confirming-crypto-phone.png b/webapp/e2e/screens/order-confirming-crypto-phone.png index 0067e533..33b6ec64 100644 Binary files a/webapp/e2e/screens/order-confirming-crypto-phone.png and b/webapp/e2e/screens/order-confirming-crypto-phone.png differ diff --git a/webapp/e2e/screens/order-ended-desktop.png b/webapp/e2e/screens/order-ended-desktop.png index 56f13434..95512d5f 100644 Binary files a/webapp/e2e/screens/order-ended-desktop.png and b/webapp/e2e/screens/order-ended-desktop.png differ diff --git a/webapp/e2e/screens/order-ended-phone.png b/webapp/e2e/screens/order-ended-phone.png index 861afccc..143f14bb 100644 Binary files a/webapp/e2e/screens/order-ended-phone.png and b/webapp/e2e/screens/order-ended-phone.png differ diff --git a/webapp/e2e/screens/order-failed-action-failed-desktop.png b/webapp/e2e/screens/order-failed-action-failed-desktop.png index 5e20d397..1a64edc4 100644 Binary files a/webapp/e2e/screens/order-failed-action-failed-desktop.png and b/webapp/e2e/screens/order-failed-action-failed-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-action-failed-phone.png b/webapp/e2e/screens/order-failed-action-failed-phone.png index d82b13bf..688f0f07 100644 Binary files a/webapp/e2e/screens/order-failed-action-failed-phone.png and b/webapp/e2e/screens/order-failed-action-failed-phone.png differ diff --git a/webapp/e2e/screens/order-failed-action-limited-desktop.png b/webapp/e2e/screens/order-failed-action-limited-desktop.png index 6f7e4c1b..1dd0f3ea 100644 Binary files a/webapp/e2e/screens/order-failed-action-limited-desktop.png and b/webapp/e2e/screens/order-failed-action-limited-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-action-limited-phone.png b/webapp/e2e/screens/order-failed-action-limited-phone.png index ac24f41d..100502ae 100644 Binary files a/webapp/e2e/screens/order-failed-action-limited-phone.png and b/webapp/e2e/screens/order-failed-action-limited-phone.png differ diff --git a/webapp/e2e/screens/order-failed-generic-code-no-record-desktop.png b/webapp/e2e/screens/order-failed-generic-code-no-record-desktop.png deleted file mode 100644 index 307c25cc..00000000 Binary files a/webapp/e2e/screens/order-failed-generic-code-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-generic-code-no-record-phone.png b/webapp/e2e/screens/order-failed-generic-code-no-record-phone.png deleted file mode 100644 index 0d8fd090..00000000 Binary files a/webapp/e2e/screens/order-failed-generic-code-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-generic-paid-desktop.png b/webapp/e2e/screens/order-failed-generic-paid-desktop.png index 9fe0c106..41492193 100644 Binary files a/webapp/e2e/screens/order-failed-generic-paid-desktop.png and b/webapp/e2e/screens/order-failed-generic-paid-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-generic-paid-no-record-desktop.png b/webapp/e2e/screens/order-failed-generic-paid-no-record-desktop.png deleted file mode 100644 index d8598773..00000000 Binary files a/webapp/e2e/screens/order-failed-generic-paid-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-generic-paid-no-record-phone.png b/webapp/e2e/screens/order-failed-generic-paid-no-record-phone.png deleted file mode 100644 index 84d9baba..00000000 Binary files a/webapp/e2e/screens/order-failed-generic-paid-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-generic-paid-phone.png b/webapp/e2e/screens/order-failed-generic-paid-phone.png index 5787d40a..1461f846 100644 Binary files a/webapp/e2e/screens/order-failed-generic-paid-phone.png and b/webapp/e2e/screens/order-failed-generic-paid-phone.png differ diff --git a/webapp/e2e/screens/order-failed-month-paid-desktop.png b/webapp/e2e/screens/order-failed-month-paid-desktop.png index 4a505160..4f11f97a 100644 Binary files a/webapp/e2e/screens/order-failed-month-paid-desktop.png and b/webapp/e2e/screens/order-failed-month-paid-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-month-paid-phone.png b/webapp/e2e/screens/order-failed-month-paid-phone.png index fbd3f2f6..73a94f1b 100644 Binary files a/webapp/e2e/screens/order-failed-month-paid-phone.png and b/webapp/e2e/screens/order-failed-month-paid-phone.png differ diff --git a/webapp/e2e/screens/order-failed-name-gone-since-desktop.png b/webapp/e2e/screens/order-failed-name-gone-since-desktop.png index b9919857..a906ca8f 100644 Binary files a/webapp/e2e/screens/order-failed-name-gone-since-desktop.png and b/webapp/e2e/screens/order-failed-name-gone-since-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-name-gone-since-phone.png b/webapp/e2e/screens/order-failed-name-gone-since-phone.png index 91249cc6..098449f7 100644 Binary files a/webapp/e2e/screens/order-failed-name-gone-since-phone.png and b/webapp/e2e/screens/order-failed-name-gone-since-phone.png differ diff --git a/webapp/e2e/screens/order-failed-signature-paid-desktop.png b/webapp/e2e/screens/order-failed-signature-paid-desktop.png index 3b1130b7..126a2bab 100644 Binary files a/webapp/e2e/screens/order-failed-signature-paid-desktop.png and b/webapp/e2e/screens/order-failed-signature-paid-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-signature-paid-phone.png b/webapp/e2e/screens/order-failed-signature-paid-phone.png index d905a395..c6a3eb52 100644 Binary files a/webapp/e2e/screens/order-failed-signature-paid-phone.png and b/webapp/e2e/screens/order-failed-signature-paid-phone.png differ diff --git a/webapp/e2e/screens/order-failed-unread-paid-desktop.png b/webapp/e2e/screens/order-failed-unread-paid-desktop.png index c356dbdd..981e1c1e 100644 Binary files a/webapp/e2e/screens/order-failed-unread-paid-desktop.png and b/webapp/e2e/screens/order-failed-unread-paid-desktop.png differ diff --git a/webapp/e2e/screens/order-failed-unread-paid-no-record-desktop.png b/webapp/e2e/screens/order-failed-unread-paid-no-record-desktop.png deleted file mode 100644 index d6f79d48..00000000 Binary files a/webapp/e2e/screens/order-failed-unread-paid-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-unread-paid-no-record-phone.png b/webapp/e2e/screens/order-failed-unread-paid-no-record-phone.png deleted file mode 100644 index 9ba4b3e8..00000000 Binary files a/webapp/e2e/screens/order-failed-unread-paid-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-failed-unread-paid-phone.png b/webapp/e2e/screens/order-failed-unread-paid-phone.png index 4c6e2ab0..e970edcb 100644 Binary files a/webapp/e2e/screens/order-failed-unread-paid-phone.png and b/webapp/e2e/screens/order-failed-unread-paid-phone.png differ diff --git a/webapp/e2e/screens/order-lapsed-no-record-desktop.png b/webapp/e2e/screens/order-lapsed-no-record-desktop.png deleted file mode 100644 index 30010518..00000000 Binary files a/webapp/e2e/screens/order-lapsed-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-lapsed-no-record-phone.png b/webapp/e2e/screens/order-lapsed-no-record-phone.png deleted file mode 100644 index 2d085d30..00000000 Binary files a/webapp/e2e/screens/order-lapsed-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-paid-by-invoice-no-record-desktop.png b/webapp/e2e/screens/order-paid-by-invoice-no-record-desktop.png deleted file mode 100644 index 87a29f47..00000000 Binary files a/webapp/e2e/screens/order-paid-by-invoice-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-paid-by-invoice-no-record-phone.png b/webapp/e2e/screens/order-paid-by-invoice-no-record-phone.png deleted file mode 100644 index 4c209053..00000000 Binary files a/webapp/e2e/screens/order-paid-by-invoice-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-pay-btc-available-desktop.png b/webapp/e2e/screens/order-pay-btc-available-desktop.png index b129ed56..da6c58a4 100644 Binary files a/webapp/e2e/screens/order-pay-btc-available-desktop.png and b/webapp/e2e/screens/order-pay-btc-available-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-btc-available-phone.png b/webapp/e2e/screens/order-pay-btc-available-phone.png index 6d65ab38..de957a6f 100644 Binary files a/webapp/e2e/screens/order-pay-btc-available-phone.png and b/webapp/e2e/screens/order-pay-btc-available-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-available-desktop.png b/webapp/e2e/screens/order-pay-card-available-desktop.png index 4f7986c9..9405a881 100644 Binary files a/webapp/e2e/screens/order-pay-card-available-desktop.png and b/webapp/e2e/screens/order-pay-card-available-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-available-phone.png b/webapp/e2e/screens/order-pay-card-available-phone.png index 7722d35c..1864dad6 100644 Binary files a/webapp/e2e/screens/order-pay-card-available-phone.png and b/webapp/e2e/screens/order-pay-card-available-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-cancel-refused-desktop.png b/webapp/e2e/screens/order-pay-card-cancel-refused-desktop.png index 708c2217..79058dc9 100644 Binary files a/webapp/e2e/screens/order-pay-card-cancel-refused-desktop.png and b/webapp/e2e/screens/order-pay-card-cancel-refused-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-cancel-refused-phone.png b/webapp/e2e/screens/order-pay-card-cancel-refused-phone.png index fd79a476..9e48d80e 100644 Binary files a/webapp/e2e/screens/order-pay-card-cancel-refused-phone.png and b/webapp/e2e/screens/order-pay-card-cancel-refused-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-cannot-persist-desktop.png b/webapp/e2e/screens/order-pay-card-cannot-persist-desktop.png index ad41e1d0..24fc5b6a 100644 Binary files a/webapp/e2e/screens/order-pay-card-cannot-persist-desktop.png and b/webapp/e2e/screens/order-pay-card-cannot-persist-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-cannot-persist-phone.png b/webapp/e2e/screens/order-pay-card-cannot-persist-phone.png index e4070abe..9e96bb8e 100644 Binary files a/webapp/e2e/screens/order-pay-card-cannot-persist-phone.png and b/webapp/e2e/screens/order-pay-card-cannot-persist-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-held-by-order-desktop.png b/webapp/e2e/screens/order-pay-card-held-by-order-desktop.png index 0637adad..ecdc295b 100644 Binary files a/webapp/e2e/screens/order-pay-card-held-by-order-desktop.png and b/webapp/e2e/screens/order-pay-card-held-by-order-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-held-by-order-phone.png b/webapp/e2e/screens/order-pay-card-held-by-order-phone.png index 6b6b55e3..b2891284 100644 Binary files a/webapp/e2e/screens/order-pay-card-held-by-order-phone.png and b/webapp/e2e/screens/order-pay-card-held-by-order-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-no-record-desktop.png b/webapp/e2e/screens/order-pay-card-no-record-desktop.png deleted file mode 100644 index 91a08063..00000000 Binary files a/webapp/e2e/screens/order-pay-card-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-pay-card-no-record-phone.png b/webapp/e2e/screens/order-pay-card-no-record-phone.png deleted file mode 100644 index 81d7e849..00000000 Binary files a/webapp/e2e/screens/order-pay-card-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-pay-card-opened-instead-desktop.png b/webapp/e2e/screens/order-pay-card-opened-instead-desktop.png index 7560ce12..40c6aa59 100644 Binary files a/webapp/e2e/screens/order-pay-card-opened-instead-desktop.png and b/webapp/e2e/screens/order-pay-card-opened-instead-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-opened-instead-phone.png b/webapp/e2e/screens/order-pay-card-opened-instead-phone.png index 8a3aa0a8..b44bc7c0 100644 Binary files a/webapp/e2e/screens/order-pay-card-opened-instead-phone.png and b/webapp/e2e/screens/order-pay-card-opened-instead-phone.png differ diff --git a/webapp/e2e/screens/order-pay-card-taken-on-chain-desktop.png b/webapp/e2e/screens/order-pay-card-taken-on-chain-desktop.png index 2e8d4adc..f62538a4 100644 Binary files a/webapp/e2e/screens/order-pay-card-taken-on-chain-desktop.png and b/webapp/e2e/screens/order-pay-card-taken-on-chain-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-card-taken-on-chain-phone.png b/webapp/e2e/screens/order-pay-card-taken-on-chain-phone.png index 7d8820e0..c2456789 100644 Binary files a/webapp/e2e/screens/order-pay-card-taken-on-chain-phone.png and b/webapp/e2e/screens/order-pay-card-taken-on-chain-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-cancel-limited-desktop.png b/webapp/e2e/screens/order-pay-crypto-cancel-limited-desktop.png index 072e4712..d4f9282a 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-cancel-limited-desktop.png and b/webapp/e2e/screens/order-pay-crypto-cancel-limited-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-cancel-limited-phone.png b/webapp/e2e/screens/order-pay-crypto-cancel-limited-phone.png index b611952d..5113fcc1 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-cancel-limited-phone.png and b/webapp/e2e/screens/order-pay-crypto-cancel-limited-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-cancel-refused-desktop.png b/webapp/e2e/screens/order-pay-crypto-cancel-refused-desktop.png index 31784b26..1a395de6 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-cancel-refused-desktop.png and b/webapp/e2e/screens/order-pay-crypto-cancel-refused-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-cancel-refused-phone.png b/webapp/e2e/screens/order-pay-crypto-cancel-refused-phone.png index db6797da..b64818cd 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-cancel-refused-phone.png and b/webapp/e2e/screens/order-pay-crypto-cancel-refused-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-downtime-desktop.png b/webapp/e2e/screens/order-pay-crypto-downtime-desktop.png new file mode 100644 index 00000000..4a16271e Binary files /dev/null and b/webapp/e2e/screens/order-pay-crypto-downtime-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-downtime-phone.png b/webapp/e2e/screens/order-pay-crypto-downtime-phone.png new file mode 100644 index 00000000..cf47773e Binary files /dev/null and b/webapp/e2e/screens/order-pay-crypto-downtime-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-held-by-order-desktop.png b/webapp/e2e/screens/order-pay-crypto-held-by-order-desktop.png index 2d099d0e..2f8a7a68 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-held-by-order-desktop.png and b/webapp/e2e/screens/order-pay-crypto-held-by-order-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-held-by-order-phone.png b/webapp/e2e/screens/order-pay-crypto-held-by-order-phone.png index 3962d0db..b364d232 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-held-by-order-phone.png and b/webapp/e2e/screens/order-pay-crypto-held-by-order-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-no-record-desktop.png b/webapp/e2e/screens/order-pay-crypto-no-record-desktop.png deleted file mode 100644 index 706f9110..00000000 Binary files a/webapp/e2e/screens/order-pay-crypto-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-pay-crypto-no-record-phone.png b/webapp/e2e/screens/order-pay-crypto-no-record-phone.png deleted file mode 100644 index 39bfd9f6..00000000 Binary files a/webapp/e2e/screens/order-pay-crypto-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-pay-crypto-opened-instead-desktop.png b/webapp/e2e/screens/order-pay-crypto-opened-instead-desktop.png index 37671a8b..66bda8b5 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-opened-instead-desktop.png and b/webapp/e2e/screens/order-pay-crypto-opened-instead-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-opened-instead-phone.png b/webapp/e2e/screens/order-pay-crypto-opened-instead-phone.png index 76f71fc5..0549b62f 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-opened-instead-phone.png and b/webapp/e2e/screens/order-pay-crypto-opened-instead-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-part-paid-desktop.png b/webapp/e2e/screens/order-pay-crypto-part-paid-desktop.png index 17aa81b5..dc65e80f 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-part-paid-desktop.png and b/webapp/e2e/screens/order-pay-crypto-part-paid-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-part-paid-expired-desktop.png b/webapp/e2e/screens/order-pay-crypto-part-paid-expired-desktop.png index 1dac5189..11340668 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-part-paid-expired-desktop.png and b/webapp/e2e/screens/order-pay-crypto-part-paid-expired-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-part-paid-expired-phone.png b/webapp/e2e/screens/order-pay-crypto-part-paid-expired-phone.png index fb04bb51..364831ec 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-part-paid-expired-phone.png and b/webapp/e2e/screens/order-pay-crypto-part-paid-expired-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-part-paid-phone.png b/webapp/e2e/screens/order-pay-crypto-part-paid-phone.png index bb473b1b..db9eb076 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-part-paid-phone.png and b/webapp/e2e/screens/order-pay-crypto-part-paid-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-taken-on-chain-desktop.png b/webapp/e2e/screens/order-pay-crypto-taken-on-chain-desktop.png index 96b5ebc1..dd8d6176 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-taken-on-chain-desktop.png and b/webapp/e2e/screens/order-pay-crypto-taken-on-chain-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-taken-on-chain-phone.png b/webapp/e2e/screens/order-pay-crypto-taken-on-chain-phone.png index e5dca998..5e9fb247 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-taken-on-chain-phone.png and b/webapp/e2e/screens/order-pay-crypto-taken-on-chain-phone.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-unchecked-desktop.png b/webapp/e2e/screens/order-pay-crypto-unchecked-desktop.png index 8c048d64..bc0b0f25 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-unchecked-desktop.png and b/webapp/e2e/screens/order-pay-crypto-unchecked-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-crypto-unchecked-phone.png b/webapp/e2e/screens/order-pay-crypto-unchecked-phone.png index f9e9551b..053c9ee0 100644 Binary files a/webapp/e2e/screens/order-pay-crypto-unchecked-phone.png and b/webapp/e2e/screens/order-pay-crypto-unchecked-phone.png differ diff --git a/webapp/e2e/screens/order-pay-xmr-available-desktop.png b/webapp/e2e/screens/order-pay-xmr-available-desktop.png index 74d1260b..f7207390 100644 Binary files a/webapp/e2e/screens/order-pay-xmr-available-desktop.png and b/webapp/e2e/screens/order-pay-xmr-available-desktop.png differ diff --git a/webapp/e2e/screens/order-pay-xmr-available-phone.png b/webapp/e2e/screens/order-pay-xmr-available-phone.png index 3d0a7acd..2133cbed 100644 Binary files a/webapp/e2e/screens/order-pay-xmr-available-phone.png and b/webapp/e2e/screens/order-pay-xmr-available-phone.png differ diff --git a/webapp/e2e/screens/order-price-changed-desktop.png b/webapp/e2e/screens/order-price-changed-desktop.png index d2cb894f..09fbe7c6 100644 Binary files a/webapp/e2e/screens/order-price-changed-desktop.png and b/webapp/e2e/screens/order-price-changed-desktop.png differ diff --git a/webapp/e2e/screens/order-price-changed-phone.png b/webapp/e2e/screens/order-price-changed-phone.png index c2785efb..242644ae 100644 Binary files a/webapp/e2e/screens/order-price-changed-phone.png and b/webapp/e2e/screens/order-price-changed-phone.png differ diff --git a/webapp/e2e/screens/order-registered-links-desktop.png b/webapp/e2e/screens/order-registered-links-desktop.png index 62c275c1..23f826b1 100644 Binary files a/webapp/e2e/screens/order-registered-links-desktop.png and b/webapp/e2e/screens/order-registered-links-desktop.png differ diff --git a/webapp/e2e/screens/order-registered-links-phone.png b/webapp/e2e/screens/order-registered-links-phone.png index 031e1bd7..0a2f16b6 100644 Binary files a/webapp/e2e/screens/order-registered-links-phone.png and b/webapp/e2e/screens/order-registered-links-phone.png differ diff --git a/webapp/e2e/screens/order-registered-no-links-desktop.png b/webapp/e2e/screens/order-registered-no-links-desktop.png index 40eeb41d..c15c1e9e 100644 Binary files a/webapp/e2e/screens/order-registered-no-links-desktop.png and b/webapp/e2e/screens/order-registered-no-links-desktop.png differ diff --git a/webapp/e2e/screens/order-registered-no-links-phone.png b/webapp/e2e/screens/order-registered-no-links-phone.png index c890b9a6..c4c97141 100644 Binary files a/webapp/e2e/screens/order-registered-no-links-phone.png and b/webapp/e2e/screens/order-registered-no-links-phone.png differ diff --git a/webapp/e2e/screens/order-registered-no-record-desktop.png b/webapp/e2e/screens/order-registered-no-record-desktop.png deleted file mode 100644 index 4e807a68..00000000 Binary files a/webapp/e2e/screens/order-registered-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registered-no-record-phone.png b/webapp/e2e/screens/order-registered-no-record-phone.png deleted file mode 100644 index 209d56c7..00000000 Binary files a/webapp/e2e/screens/order-registered-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-committing-desktop.png b/webapp/e2e/screens/order-registering-committing-desktop.png index b1048834..70e9d4e8 100644 Binary files a/webapp/e2e/screens/order-registering-committing-desktop.png and b/webapp/e2e/screens/order-registering-committing-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-committing-phone.png b/webapp/e2e/screens/order-registering-committing-phone.png index 484f1ff6..cd5c5575 100644 Binary files a/webapp/e2e/screens/order-registering-committing-phone.png and b/webapp/e2e/screens/order-registering-committing-phone.png differ diff --git a/webapp/e2e/screens/order-registering-community-terms-asked-desktop.png b/webapp/e2e/screens/order-registering-community-terms-asked-desktop.png index e2794725..59689112 100644 Binary files a/webapp/e2e/screens/order-registering-community-terms-asked-desktop.png and b/webapp/e2e/screens/order-registering-community-terms-asked-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-community-terms-asked-phone.png b/webapp/e2e/screens/order-registering-community-terms-asked-phone.png index cd33a5e7..afeb4e41 100644 Binary files a/webapp/e2e/screens/order-registering-community-terms-asked-phone.png and b/webapp/e2e/screens/order-registering-community-terms-asked-phone.png differ diff --git a/webapp/e2e/screens/order-registering-lapsed-desktop.png b/webapp/e2e/screens/order-registering-lapsed-desktop.png index 67adf44b..1fb06b72 100644 Binary files a/webapp/e2e/screens/order-registering-lapsed-desktop.png and b/webapp/e2e/screens/order-registering-lapsed-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-lapsed-phone.png b/webapp/e2e/screens/order-registering-lapsed-phone.png index ff4dd3ef..8c842028 100644 Binary files a/webapp/e2e/screens/order-registering-lapsed-phone.png and b/webapp/e2e/screens/order-registering-lapsed-phone.png differ diff --git a/webapp/e2e/screens/order-registering-name-registered-meanwhile-desktop.png b/webapp/e2e/screens/order-registering-name-registered-meanwhile-desktop.png index 2c12b919..ff71a3e3 100644 Binary files a/webapp/e2e/screens/order-registering-name-registered-meanwhile-desktop.png and b/webapp/e2e/screens/order-registering-name-registered-meanwhile-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-name-registered-meanwhile-phone.png b/webapp/e2e/screens/order-registering-name-registered-meanwhile-phone.png index cdc6dab4..ac2bc128 100644 Binary files a/webapp/e2e/screens/order-registering-name-registered-meanwhile-phone.png and b/webapp/e2e/screens/order-registering-name-registered-meanwhile-phone.png differ diff --git a/webapp/e2e/screens/order-registering-name-reserved-meanwhile-desktop.png b/webapp/e2e/screens/order-registering-name-reserved-meanwhile-desktop.png index 25bc86b0..c524d568 100644 Binary files a/webapp/e2e/screens/order-registering-name-reserved-meanwhile-desktop.png and b/webapp/e2e/screens/order-registering-name-reserved-meanwhile-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-name-reserved-meanwhile-phone.png b/webapp/e2e/screens/order-registering-name-reserved-meanwhile-phone.png index 011bd702..a4b0e989 100644 Binary files a/webapp/e2e/screens/order-registering-name-reserved-meanwhile-phone.png and b/webapp/e2e/screens/order-registering-name-reserved-meanwhile-phone.png differ diff --git a/webapp/e2e/screens/order-registering-no-record-committing-desktop.png b/webapp/e2e/screens/order-registering-no-record-committing-desktop.png deleted file mode 100644 index a7cbb530..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-committing-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-no-record-committing-phone.png b/webapp/e2e/screens/order-registering-no-record-committing-phone.png deleted file mode 100644 index 80a52283..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-committing-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-no-record-signed-desktop.png b/webapp/e2e/screens/order-registering-no-record-signed-desktop.png deleted file mode 100644 index b932dc25..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-signed-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-no-record-signed-phone.png b/webapp/e2e/screens/order-registering-no-record-signed-phone.png deleted file mode 100644 index c88a5b44..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-signed-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-no-record-wait-desktop.png b/webapp/e2e/screens/order-registering-no-record-wait-desktop.png deleted file mode 100644 index 2465343d..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-wait-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-no-record-wait-phone.png b/webapp/e2e/screens/order-registering-no-record-wait-phone.png deleted file mode 100644 index 2d3740a1..00000000 Binary files a/webapp/e2e/screens/order-registering-no-record-wait-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-registering-signature-refused-desktop.png b/webapp/e2e/screens/order-registering-signature-refused-desktop.png index ad87b8d0..fc7b8af8 100644 Binary files a/webapp/e2e/screens/order-registering-signature-refused-desktop.png and b/webapp/e2e/screens/order-registering-signature-refused-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-signature-refused-phone.png b/webapp/e2e/screens/order-registering-signature-refused-phone.png index 3d3287e1..fe211ce6 100644 Binary files a/webapp/e2e/screens/order-registering-signature-refused-phone.png and b/webapp/e2e/screens/order-registering-signature-refused-phone.png differ diff --git a/webapp/e2e/screens/order-registering-terms-asked-desktop.png b/webapp/e2e/screens/order-registering-terms-asked-desktop.png index 8da049ba..6c57685e 100644 Binary files a/webapp/e2e/screens/order-registering-terms-asked-desktop.png and b/webapp/e2e/screens/order-registering-terms-asked-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-terms-asked-phone.png b/webapp/e2e/screens/order-registering-terms-asked-phone.png index 891d726d..c28c2405 100644 Binary files a/webapp/e2e/screens/order-registering-terms-asked-phone.png and b/webapp/e2e/screens/order-registering-terms-asked-phone.png differ diff --git a/webapp/e2e/screens/order-registering-terms-ticked-desktop.png b/webapp/e2e/screens/order-registering-terms-ticked-desktop.png index 49749cf8..0aad9e91 100644 Binary files a/webapp/e2e/screens/order-registering-terms-ticked-desktop.png and b/webapp/e2e/screens/order-registering-terms-ticked-desktop.png differ diff --git a/webapp/e2e/screens/order-registering-terms-ticked-phone.png b/webapp/e2e/screens/order-registering-terms-ticked-phone.png index 7c4e8356..b7b61e7a 100644 Binary files a/webapp/e2e/screens/order-registering-terms-ticked-phone.png and b/webapp/e2e/screens/order-registering-terms-ticked-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-codes-only-desktop.png b/webapp/e2e/screens/order-reorder-codes-only-desktop.png index 352e0c0f..26841ffc 100644 Binary files a/webapp/e2e/screens/order-reorder-codes-only-desktop.png and b/webapp/e2e/screens/order-reorder-codes-only-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-codes-only-phone.png b/webapp/e2e/screens/order-reorder-codes-only-phone.png index 9cdd398d..b8d306cb 100644 Binary files a/webapp/e2e/screens/order-reorder-codes-only-phone.png and b/webapp/e2e/screens/order-reorder-codes-only-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-failed-desktop.png b/webapp/e2e/screens/order-reorder-failed-desktop.png index d07afee0..be5de092 100644 Binary files a/webapp/e2e/screens/order-reorder-failed-desktop.png and b/webapp/e2e/screens/order-reorder-failed-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-failed-phone.png b/webapp/e2e/screens/order-reorder-failed-phone.png index 7311dcb4..b1bdc795 100644 Binary files a/webapp/e2e/screens/order-reorder-failed-phone.png and b/webapp/e2e/screens/order-reorder-failed-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-limited-desktop.png b/webapp/e2e/screens/order-reorder-limited-desktop.png index 841b5ba2..2d0e3cf0 100644 Binary files a/webapp/e2e/screens/order-reorder-limited-desktop.png and b/webapp/e2e/screens/order-reorder-limited-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-limited-phone.png b/webapp/e2e/screens/order-reorder-limited-phone.png index d992846e..6d69d899 100644 Binary files a/webapp/e2e/screens/order-reorder-limited-phone.png and b/webapp/e2e/screens/order-reorder-limited-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-name-unchecked-desktop.png b/webapp/e2e/screens/order-reorder-name-unchecked-desktop.png index 8be9cb20..c246cc5e 100644 Binary files a/webapp/e2e/screens/order-reorder-name-unchecked-desktop.png and b/webapp/e2e/screens/order-reorder-name-unchecked-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-name-unchecked-phone.png b/webapp/e2e/screens/order-reorder-name-unchecked-phone.png index 849475cc..99acfdaf 100644 Binary files a/webapp/e2e/screens/order-reorder-name-unchecked-phone.png and b/webapp/e2e/screens/order-reorder-name-unchecked-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-no-orders-desktop.png b/webapp/e2e/screens/order-reorder-no-orders-desktop.png index 94b32fbb..9575d6d7 100644 Binary files a/webapp/e2e/screens/order-reorder-no-orders-desktop.png and b/webapp/e2e/screens/order-reorder-no-orders-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-no-orders-phone.png b/webapp/e2e/screens/order-reorder-no-orders-phone.png index 0c5a83e2..b3592be5 100644 Binary files a/webapp/e2e/screens/order-reorder-no-orders-phone.png and b/webapp/e2e/screens/order-reorder-no-orders-phone.png differ diff --git a/webapp/e2e/screens/order-reorder-provider-unavailable-desktop.png b/webapp/e2e/screens/order-reorder-provider-unavailable-desktop.png index c677b51a..095637d4 100644 Binary files a/webapp/e2e/screens/order-reorder-provider-unavailable-desktop.png and b/webapp/e2e/screens/order-reorder-provider-unavailable-desktop.png differ diff --git a/webapp/e2e/screens/order-reorder-provider-unavailable-phone.png b/webapp/e2e/screens/order-reorder-provider-unavailable-phone.png index 59950240..07e4a1f8 100644 Binary files a/webapp/e2e/screens/order-reorder-provider-unavailable-phone.png and b/webapp/e2e/screens/order-reorder-provider-unavailable-phone.png differ diff --git a/webapp/e2e/screens/order-taken-balance-spent-desktop.png b/webapp/e2e/screens/order-taken-balance-spent-desktop.png index f08552dd..3c6207bc 100644 Binary files a/webapp/e2e/screens/order-taken-balance-spent-desktop.png and b/webapp/e2e/screens/order-taken-balance-spent-desktop.png differ diff --git a/webapp/e2e/screens/order-taken-balance-spent-phone.png b/webapp/e2e/screens/order-taken-balance-spent-phone.png index 5c1f23a6..bc4d1342 100644 Binary files a/webapp/e2e/screens/order-taken-balance-spent-phone.png and b/webapp/e2e/screens/order-taken-balance-spent-phone.png differ diff --git a/webapp/e2e/screens/order-taken-chain-desktop.png b/webapp/e2e/screens/order-taken-chain-desktop.png index 11a2f1fa..1ad4f9d9 100644 Binary files a/webapp/e2e/screens/order-taken-chain-desktop.png and b/webapp/e2e/screens/order-taken-chain-desktop.png differ diff --git a/webapp/e2e/screens/order-taken-chain-phone.png b/webapp/e2e/screens/order-taken-chain-phone.png index 49a4b22b..e39a3aa4 100644 Binary files a/webapp/e2e/screens/order-taken-chain-phone.png and b/webapp/e2e/screens/order-taken-chain-phone.png differ diff --git a/webapp/e2e/screens/order-taken-code-no-record-desktop.png b/webapp/e2e/screens/order-taken-code-no-record-desktop.png deleted file mode 100644 index 46112fb1..00000000 Binary files a/webapp/e2e/screens/order-taken-code-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-taken-code-no-record-phone.png b/webapp/e2e/screens/order-taken-code-no-record-phone.png deleted file mode 100644 index 1676f661..00000000 Binary files a/webapp/e2e/screens/order-taken-code-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-taken-codes-only-desktop.png b/webapp/e2e/screens/order-taken-codes-only-desktop.png index 9f89bc3d..cc198fe3 100644 Binary files a/webapp/e2e/screens/order-taken-codes-only-desktop.png and b/webapp/e2e/screens/order-taken-codes-only-desktop.png differ diff --git a/webapp/e2e/screens/order-taken-codes-only-phone.png b/webapp/e2e/screens/order-taken-codes-only-phone.png index 7662fded..c75fb57e 100644 Binary files a/webapp/e2e/screens/order-taken-codes-only-phone.png and b/webapp/e2e/screens/order-taken-codes-only-phone.png differ diff --git a/webapp/e2e/screens/order-taken-no-record-desktop.png b/webapp/e2e/screens/order-taken-no-record-desktop.png deleted file mode 100644 index 033710a0..00000000 Binary files a/webapp/e2e/screens/order-taken-no-record-desktop.png and /dev/null differ diff --git a/webapp/e2e/screens/order-taken-no-record-phone.png b/webapp/e2e/screens/order-taken-no-record-phone.png deleted file mode 100644 index 229afa1e..00000000 Binary files a/webapp/e2e/screens/order-taken-no-record-phone.png and /dev/null differ diff --git a/webapp/e2e/screens/order-taken-outpaid-desktop.png b/webapp/e2e/screens/order-taken-outpaid-desktop.png index 4c82542d..04b9adbb 100644 Binary files a/webapp/e2e/screens/order-taken-outpaid-desktop.png and b/webapp/e2e/screens/order-taken-outpaid-desktop.png differ diff --git a/webapp/e2e/screens/order-taken-outpaid-phone.png b/webapp/e2e/screens/order-taken-outpaid-phone.png index e9630119..5b143999 100644 Binary files a/webapp/e2e/screens/order-taken-outpaid-phone.png and b/webapp/e2e/screens/order-taken-outpaid-phone.png differ diff --git a/webapp/e2e/screens/order-taken-reserved-desktop.png b/webapp/e2e/screens/order-taken-reserved-desktop.png index 7c36a5e4..e56db59d 100644 Binary files a/webapp/e2e/screens/order-taken-reserved-desktop.png and b/webapp/e2e/screens/order-taken-reserved-desktop.png differ diff --git a/webapp/e2e/screens/order-taken-reserved-phone.png b/webapp/e2e/screens/order-taken-reserved-phone.png index 1548ff93..ec288d24 100644 Binary files a/webapp/e2e/screens/order-taken-reserved-phone.png and b/webapp/e2e/screens/order-taken-reserved-phone.png differ diff --git a/webapp/e2e/signed.spec.ts b/webapp/e2e/signed.spec.ts new file mode 100644 index 00000000..9a48d7b5 --- /dev/null +++ b/webapp/e2e/signed.spec.ts @@ -0,0 +1,48 @@ +import { expect, type APIRequestContext } from "@playwright/test" +import { control, MOCK, onStep, REGISTRATION_MS, startOrder, test, uniqueLabel, waitRegistered } from "./helpers.ts" + +const NO_CODE = "Please enter the name code you saved for this order." +const SKEW_MS = 20 * 60_000 +const ORDER_READ = /\/api\/(invoice|registration)\/[^/]+$/ + +const orderRequests = async (request: APIRequestContext) => + ((await (await request.get(`${MOCK}/control/state`)).json()) as { orderRequests: { signed: number; refused: number } }).orderRequests + +test("every request for an order is signed with its owner's name key, polls, cancels and the reads to the name registered", async ({ page, request }) => { + const before = await orderRequests(request) + const label = uniqueLabel("signed") + const { invoiceId } = await startOrder(page, label, { method: "btc" }) + await control(request, `settle/${invoiceId}`) + await waitRegistered(page, label) + await startOrder(page, uniqueLabel("signedc"), { method: "btc" }) + await onStep(page).getByRole("button", { name: "Cancel this invoice" }).click() + await expect(page.getByText("This invoice is closed. No payment was received.")).toBeVisible() + const after = await orderRequests(request) + expect(after.refused - before.refused, "no order request refused").toBe(0) + expect(after.signed - before.signed, "the order's reads, signed").toBeGreaterThan(1) +}) + +test("an order's link in a browser without its name code sends no request for the order and asks for the code", async ({ page, browser, request }) => { + const { invoiceId } = await startOrder(page, uniqueLabel("nocode"), { method: "btc" }) + const elsewhere = await (await browser.newContext()).newPage() + const asked: string[] = [] + elsewhere.on("request", (r) => { if (ORDER_READ.test(new URL(r.url()).pathname)) asked.push(r.url()) }) + await elsewhere.goto(`/?order=${invoiceId}`) + await expect(onStep(elsewhere).getByText(NO_CODE)).toBeVisible() + await expect(onStep(elsewhere).getByRole("button", { name: "Enter your name code" })).toBeVisible() + expect(asked).toEqual([]) + expect((await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json() as { status: string }).status).toBe("open") +}) + +test("a device clock 20 minutes off has the order drawn after one more signature, at the service's clock", async ({ page }) => { + const { invoiceId } = await startOrder(page, uniqueLabel("skew"), { method: "btc" }) + await page.addInitScript((skew) => { + const now = Date.now + Date.now = () => now() + skew + }, SKEW_MS) + const reads: number[] = [] + page.on("response", (r) => { if (new URL(r.url()).pathname === `/api/invoice/${invoiceId}`) reads.push(r.status()) }) + await page.reload() + await expect(onStep(page).getByRole("heading", { name: "Pay with Bitcoin" })).toBeVisible({ timeout: REGISTRATION_MS }) + expect(reads.slice(0, 2), "refused for its time, then answered").toEqual([400, 200]) +}) diff --git a/webapp/e2e/slots.ts b/webapp/e2e/slots.ts index 73a54620..5460b52d 100644 --- a/webapp/e2e/slots.ts +++ b/webapp/e2e/slots.ts @@ -1,7 +1,10 @@ // Each worker's mock and page server listen on the first slot's ports plus the slot's index, as its chain does. const MOCK_PORT = 8099 const PAGE_PORT = 5173 +const CODES_PAGE_PORT = 5273 export const mockUrl = (slot: number) => `http://127.0.0.1:${MOCK_PORT + slot}` export const pagePort = (slot: number) => PAGE_PORT + slot export const pageUrl = (slot: number) => `http://127.0.0.1:${pagePort(slot)}` +export const codesPagePort = (slot: number) => CODES_PAGE_PORT + slot +export const codesPageUrl = (slot: number) => `http://127.0.0.1:${codesPagePort(slot)}` diff --git a/webapp/e2e/taken.spec.ts b/webapp/e2e/taken.spec.ts index 5ba0dda6..536dfb0e 100644 --- a/webapp/e2e/taken.spec.ts +++ b/webapp/e2e/taken.spec.ts @@ -3,8 +3,9 @@ import { walletOf } from "../src/flow.ts" import { labelHash } from "../src/crypto/registration.ts" import { checksumAddress, hex } from "../src/crypto/wallet.ts" import { dateOf } from "../src/format.ts" +import { ALTERNATE_GENERAL_TERMS } from "./terms.ts" import { - addNameCode, answersReserved, control, failedOrder, FIT_SIZES, keepOrder, MOCK, mockRegistration, onStep, REGISTRATION_MS, registrationOf, + addNameCode, agreeToTerms, answersReserved, control, failedOrder, FIT_SIZES, keepOrder, MOCK, mockRegistration, onStep, REGISTRATION_MS, registrationOf, registrationView, offCentre, search, searchName, selectedToReview, sevenLetters, shot, startOrder, takenHeading, takenOrder, test, uniqueLabel, waitRegistered, } from "./helpers.ts" @@ -18,7 +19,7 @@ async function paidOrder(page: Parameters[0], id: string, reg: await page.goto(`/?order=inv-${id}`) } -const phaseOf = async (request: APIRequestContext, invoiceId: string) => ((await (await request.get(`${MOCK}/api/invoice/${invoiceId}`)).json()) as { registration: { phase: { type: string } } }).registration.phase.type +const phaseOf = async (request: APIRequestContext, invoiceId: string) => ((await (await request.get(`${MOCK}/control/invoice/${invoiceId}`)).json()) as { registration: { phase: { type: string } } }).registration.phase.type test("an order another buyer's paid order took first shows no stage done, as it never committed", async ({ page }) => { await paidOrder(page, "outpaid", { phase: { type: "taken" }, balance: { amount: 10000, refunded: 0 } }) @@ -39,12 +40,12 @@ test("a name taken first keeps its payment as its balance, with which a name sel await expect(onStep(page).locator(".stage.failed")).toHaveText("Taken") await expect(page.getByText(`Reference ${invoiceId}`)).toBeVisible() await shot(page, "N8-taken") - // a browser without the order's code says where to add it, and offers neither the selection nor the refund + // a browser without the order's code asks for it, and offers neither the selection nor the refund const elsewhere = await page.context().browser()!.newContext() const stranger = await elsewhere.newPage() await stranger.goto(`/?order=${invoiceId}`) - await expect(stranger.getByText("Add it in Check your code to use the balance.")).toBeVisible() - await expect(onStep(stranger).getByRole("button", { name: "Choose another name" })).toBeDisabled() + await expect(stranger.getByText("Please enter the name code you saved for this order.")).toBeVisible() + await expect(onStep(stranger).getByRole("button", { name: "Choose another name" })).toHaveCount(0) await expect(onStep(stranger).getByText("Get a refund")).toHaveCount(0) await elsewhere.close() @@ -174,7 +175,7 @@ test("an order failed while its page was not read says until when the name stays }, { timeout: REGISTRATION_MS }).toBe(true) await control(request, `unread/${registrationId}`) await expect(page.getByRole("heading", { name: "Paid, not registered" })).toBeVisible({ timeout: REGISTRATION_MS }) - const view = await (await request.get(`${MOCK}/api/registration/${registrationId}`)).json() as { phase: { heldUntil: string } } + const view = await (await request.get(`${MOCK}/control/registration/${registrationId}`)).json() as { phase: { heldUntil: string } } const until = dateOf(Date.parse(view.phase.heldUntil) / 1000) await expect(onStep(page).locator(".notice", { hasText: "The order was not opened for 3 days" })).toHaveText( `The order was not opened for 3 daysPlease choose Continue before ${until} to finish the registration, or contact support via chat@simplex.chat or SimpleX, with the name and the order reference ${invoiceId}.`) @@ -184,6 +185,42 @@ test("an order failed while its page was not read says until when the name stays await waitRegistered(page, label) }) +test("an order failed unread offers Continue only outside the service's downtime, asks at Continue for terms changed since, and signs and registers it once they are accepted", async ({ page, request }) => { + const label = uniqueLabel("unt") + const { invoiceId } = await startOrder(page, label, { method: "btc" }) + const registrationId = await registrationOf(request, invoiceId) + await page.route("**/api/registration/*/reveal", (route) => route.abort()) + await control(request, `stale/${registrationId}`) + await control(request, `settle/${invoiceId}`) + await expect.poll(async () => { + const { phase, label: revealed } = await mockRegistration(request, invoiceId) + return phase === "committed" && revealed === null + }, { timeout: REGISTRATION_MS }).toBe(true) + await control(request, `unread/${registrationId}`) + await expect(page.getByRole("heading", { name: "Paid, not registered" })).toBeVisible({ timeout: REGISTRATION_MS }) + await page.unrouteAll({ behavior: "wait" }) + const continued = onStep(page).getByRole("button", { name: "Continue" }) + await page.route("**/api/config", (route) => route.fulfill({ json: { stripePublishableKey: null, names: { downtime: true } } })) + await page.reload() + await expect(onStep(page).getByText("You will be able to continue the registration soon.")).toBeVisible() + await expect(continued).toBeDisabled() + await page.unrouteAll({ behavior: "wait" }) + await page.reload() + await control(request, "general-terms", { text: ALTERNATE_GENERAL_TERMS }) + try { + await continued.click() + const notice = onStep(page).locator(".line", { hasText: "The Names Conditions changed. Please accept them to continue." }) + await expect(notice).toBeVisible() + await expect(notice, "the notice takes the focus of Continue, which waits for the tick").toBeFocused() + await expect(continued).toBeDisabled() + await agreeToTerms(page) + await continued.click() + await waitRegistered(page, label) + } finally { + await control(request, "general-terms", { text: null }) + } +}) + // a chain that fails each transaction before it goes out, as an RPC provider down for a while, and a look half way through const UNSENT_S = 30 const UNSENT_CHECK_MS = UNSENT_S * 1000 / 2 diff --git a/webapp/e2e/terms.ts b/webapp/e2e/terms.ts new file mode 100644 index 00000000..333ca69e --- /dev/null +++ b/webapp/e2e/terms.ts @@ -0,0 +1,2 @@ +export const ALTERNATE_GENERAL_TERMS = "# SimpleX Names Conditions of Use\n\nChanged for the browser tests.\n" +export const ALTERNATE_COMMUNITY_TERMS = "# Community terms\n\nChanged for the browser tests.\n" diff --git a/webapp/e2e/track.spec.ts b/webapp/e2e/track.spec.ts index 7563cafd..4335d686 100644 --- a/webapp/e2e/track.spec.ts +++ b/webapp/e2e/track.spec.ts @@ -1,11 +1,13 @@ import { type APIRequestContext, expect, type Locator, type Page } from "@playwright/test" +import { bitcoinPayee, devReceiving } from "../dev/mock/addresses.ts" +import { heldPrice, LOCAL } from "../src/config.ts" import { YEAR_S } from "../src/crypto/registration.ts" import { MAX_LABEL_LENGTH } from "../src/names.ts" import { TX_STALL_MS } from "../src/screens/order.ts" import { AVAILABLE_BRIEF, brokenNames, channelLink, CHECKOUT_KEY, CODE_HEADING, codeField, contactLink, control, fakeRegisteredName, fillLinks, FIT_SIZES, keepOrder, type KeptOrder, LINKS_HEADING, okPreview, onStep, payButton, previewsShown, SAVED, lineStarts, offCentre, recordedFrames, recordFrames, REGISTRATION_MS, registeredAnswer, registrationOf, registrationView, rowFit, savedToReview, search, shot, startOrder, takenOrder, TERMS, test, toCodeStep, - TAKEN_BRIEF, toFullReview, toReview, uniqueLabel, useCode, waitRegistered, withStripeKey, + TAKEN_BRIEF, toFullReview, toReview, uniqueLabel, useCode, waitRegistered, withStripeKey, cardFrame, cardFrameOf, fakeIntent, } from "./helpers.ts" test("the purchase steps swap the whole page, one screen at a time rising in, and Back walks them in reverse", async ({ page }) => { @@ -61,11 +63,12 @@ const METHOD_TILES = [66, 72] // The screen in view fits the window at each size, its content above its actions' row, its methods' tiles at their // height and no name broken that fits its line whole; a step's heading and actions' row stand where every step's do, -// which the caller compares. Captured for review when shots are asked for. -async function fitsWindow(page: Page, name: string, frames?: Record): Promise { +// which the caller compares; a screen that grows, as the name-is-yours screen of a long name, may reach past the window. +// Captured for review when shots are asked for. +async function fitsWindow(page: Page, name: string, frames?: Record, grows = false): Promise { for (const [i, size] of FIT_SIZES.entries()) { await page.setViewportSize(size) - const measured = async () => ({ broken: await brokenNames(page), ...await page.evaluate((tile) => { + const measured = async () => ({ broken: await brokenNames(page), ...await page.evaluate(([tile, mayGrow]) => { const shown = document.querySelector("body > main > section")! // a step with no action gives its content the action row's room, down to the step's foot; one with only a link, // the empty place of a main button above it @@ -77,12 +80,12 @@ async function fitsWindow(page: Page, name: string, frames?: Record new Set([...n.getClientRects()].map((r) => Math.round(r.top))).size > 1) return { - overflow: Math.max(0, document.scrollingElement!.scrollHeight - innerHeight - footer), + overflow: mayGrow ? 0 : Math.max(0, document.scrollingElement!.scrollHeight - innerHeight - footer), overlap: actions && content.length ? Math.max(0, Math.round(Math.max(...content.map((b) => b.bottom)) - actions.top)) : 0, split: split.map((n) => n.textContent), tiles: [...shown.querySelectorAll(".method")].map((m) => Math.round(m.getBoundingClientRect().height)).filter((h) => h !== tile), } - }, METHOD_TILES[i]) }) + }, [METHOD_TILES[i], grows] as const) }) await expect.poll(measured, { message: `${name} at ${size.width}x${size.height}` }).toEqual({ broken: [], overflow: 0, overlap: 0, split: [], tiles: [] }) if (frames) { const at = await page.evaluate(() => { @@ -203,7 +206,8 @@ const DECLINED = "Your card was declined." // A Stripe.js whose card form comes when the test calls __loadCard, `px` tall for the column, and grows by __growCard; // it declines every card when asked to. It counts its mounts in __mounts, and keeps in __logos Stripe's logo tone of // each appearance the form is given once made. -const stripeOnCue = (px: FormPx, declines = false) => `window.Stripe = () => ({ +const stripeOnCue = (px: FormPx, amount: number, declines = false) => `window.Stripe = () => ({ + retrievePaymentIntent: async () => (${fakeIntent(amount)}), confirmPayment: async () => (${declines} ? { error: { type: "card_error", message: "${DECLINED}" } } : { paymentIntent: { status: "processing" } }), elements: () => ({ update: ({ appearance }) => { (window.__logos ??= []).push(appearance.variables.logoColor) }, create: () => { const handlers = {} @@ -220,14 +224,15 @@ const stripeOnCue = (px: FormPx, declines = false) => `window.Stripe = () => ({ } }), })` const loadCard = async (page: Page) => { - await page.waitForFunction(() => typeof (window as unknown as { __loadCard?: unknown }).__loadCard === "function") - await page.evaluate(() => (window as unknown as { __loadCard: () => void }).__loadCard()) + const frame = await cardFrameOf(page) + await frame.waitForFunction(() => typeof (window as unknown as { __loadCard?: unknown }).__loadCard === "function") + await frame.evaluate(() => (window as unknown as { __loadCard: () => void }).__loadCard()) } -const cardSeen = (page: Page) => page.evaluate(() => { +const cardSeen = async (page: Page) => (await cardFrameOf(page)).evaluate(() => { const w = window as unknown as { __logos?: string[]; __mounts?: number } return { logos: w.__logos ?? [], mounts: w.__mounts ?? 0 } }) -const growCard = (page: Page, by: number) => page.evaluate((px) => (window as unknown as { __growCard: (by: number) => void }).__growCard(px), by) +const growCard = async (page: Page, by: number) => (await cardFrameOf(page)).evaluate((px) => (window as unknown as { __growCard: (by: number) => void }).__growCard(px), by) // the card page's windows: a laptop's, a narrow desktop window's, and two phones' const CARD_SIZES = [{ width: 1280, height: 800 }, { width: 600, height: 800 }, { width: 390, height: 844 }, { width: 360, height: 780 }] // the widest window drawn as a phone (styles.css) @@ -267,7 +272,7 @@ function cardFollows(drawn: Awaited>, where: string) // notice stays above the form; Stripe's note is under Cancel, centred, clear of the invest note. With `declines`, Pay is // pressed once the form loads, and Stripe declines the card. A page that `scrolls`, for a name of the most wide letters, // may reach past a laptop's window, as its actions take their whole height under the form. -async function cardFits(page: Page, notice: RegExp, open: () => Promise, { declines = false, scrolls = false } = {}): Promise { +async function cardFits(page: Page, notice: RegExp, open: () => Promise, amount: number, { declines = false, scrolls = false } = {}): Promise { for (const size of CARD_SIZES) { for (const px of FORMS_PX) { const wide = size.width > PHONE_WIDTH @@ -276,14 +281,15 @@ async function cardFits(page: Page, notice: RegExp, open: () => Promise, { const where = `${size.width}x${size.height}, a form of ${formPx} px` await page.setViewportSize(size) await page.unroute("https://js.stripe.com/**") - await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: stripeOnCue(px, declines) })) + await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: stripeOnCue(px, amount, declines) })) await open() await expect(onStep(page).getByRole("heading", { name: "Pay by card" }), where).toBeVisible() await expect(onStep(page).locator(".name-check:not(.unchecked)"), `${where}: the notice`).toBeVisible() await page.evaluate(() => document.fonts.ready) const before = await cardPage(page) await loadCard(page) - await expect(onStep(page).locator(".stripe > div"), where).toHaveCount(1) + await expect(cardFrame(page).locator("#form > div"), where).toHaveCount(1) + await expect.poll(async () => (await cardPage(page)).form!.bottom - (await cardPage(page)).form!.top, `${where}: the frame grown to the form`).toBe(Math.max(formPx, room)) if (declines) await payButton(page).click() await expect(onStep(page).locator(".name-check > :not(.sizer)"), `${where}: the notice`).toHaveText(notice) const loaded = await cardPage(page) @@ -309,6 +315,8 @@ async function cardFits(page: Page, notice: RegExp, open: () => Promise, { if (!scrolls && formPx <= room && FIT_SIZES.some((fit) => fit.width === size.width && fit.height === size.height)) expect(await overflow(page), where).toBe(0) // an error line under a field: the form grows past its room by the line, and Pay and what follows move down with it await growCard(page, ERROR_LINE_PX) + await expect.poll(async () => (await cardPage(page)).form!.bottom - (await cardPage(page)).form!.top, `${where}: the frame grown by the line`) + .toBe(Math.max(formPx + ERROR_LINE_PX, room)) for (const dark of [false, true]) { await page.evaluate((d) => document.documentElement.classList.toggle("dark", d), dark) const grown = await cardPage(page) @@ -325,19 +333,20 @@ async function cardFits(page: Page, notice: RegExp, open: () => Promise, { const CARD_INVOICE = "inv-cardfit" const CARD_REGISTRATION = "reg-cardfit" -interface CardOrder { label: string; price: number; taken?: boolean; forgetful?: boolean } +interface CardOrder { label: string; taken?: boolean; forgetful?: boolean } // A card order of this browser's, answered by routes, whose page opens at `/?order=`; the name is available or taken, // and the browser can keep a record or not. async function routedCardOrder(page: Page, o: CardOrder): Promise<() => Promise> { const order = await keepOrder(page, CARD_REGISTRATION, CARD_INVOICE, o.label) await page.evaluate((r) => localStorage.setItem(`simplex-names:order:${r.registrationId}`, JSON.stringify({ ...r, method: "card" })), order) - const registration = registrationView(order, { price: o.price, payment: { type: "invoice", method: "card" } }) - const invoice = { invoiceId: CARD_INVOICE, status: "open", amount: o.price, currency: "usd", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), kind: "name", + const price = heldPrice(o.label.length) + const registration = registrationView(order, { price, payment: { type: "invoice", method: "card" } }) + const invoice = { invoiceId: CARD_INVOICE, status: "open", amount: price, currency: "usd", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), kind: "name", registration, clientSecret: "pi_cardfit_secret" } await page.route(`**/api/invoice/${CARD_INVOICE}*`, (route) => route.fulfill({ json: invoice })) await page.route(`**/api/registration/${CARD_REGISTRATION}*`, (route) => route.fulfill({ json: registration })) - await page.route("**/api/name/**", (route) => route.fulfill({ json: o.taken ? homeAnswers(order.owner).taken : homeAnswers(order.owner).available })) + await page.route("**/api/name/**", (route) => route.fulfill({ json: o.taken ? homeAnswers(order.owner, o.label).taken : homeAnswers(order.owner, o.label).available })) if (o.forgetful) await page.addInitScript(() => { const keep = Storage.prototype.setItem Storage.prototype.setItem = function (key: string, value: string) { @@ -354,7 +363,8 @@ test.describe(() => { test.use({ serviceWorkers: "block" }) test("a card invoice opened in place of a new Bitcoin one says why in the card page's one notice, above the form", async ({ page }) => { - await search(page, uniqueLabel("cardinst")) + const label = uniqueLabel("cardinst") + await search(page, label) await toReview(page) await page.getByRole("radio", { name: "Card" }).click() const checkout = await page.evaluate((key) => sessionStorage.getItem(key)!, CHECKOUT_KEY) @@ -369,16 +379,16 @@ test.describe(() => { await copy.getByRole("radio", { name: "Bitcoin" }).click() await payButton(copy).click() await copy.waitForURL(/\?order=/) - }) + }, heldPrice(label.length)) }) }) // the service worker of a production build answers these pages before Playwright's routes in WebKit test.describe(() => { test.use({ serviceWorkers: "block" }) - const tenLetters = { label: "cardfitabc", price: 10000 } - const sixWide = { label: "w".repeat(6), price: 10000 } - const longest = { label: "w".repeat(MAX_LABEL_LENGTH), price: 20000 } + const tenLetters = { label: "cardfitabc" } + const sixWide = { label: "w".repeat(6) } + const longest = { label: "w".repeat(MAX_LABEL_LENGTH) } const CARD_CASES: [string, CardOrder, RegExp][] = [ ["a name of 10 letters", tenLetters, AVAILABLE_BRIEF], ["a name of 6 wide letters", sixWide, AVAILABLE_BRIEF], @@ -389,28 +399,28 @@ test.describe(() => { ] for (const [name, order, notice] of CARD_CASES) { test(`the card page draws Pay under Stripe's form as it loads and grows, its one notice above it, for ${name}`, async ({ page }) => { - await cardFits(page, notice, await routedCardOrder(page, order), { scrolls: order.label.length === MAX_LABEL_LENGTH }) + await cardFits(page, notice, await routedCardOrder(page, order), heldPrice(order.label.length), { scrolls: order.label.length === MAX_LABEL_LENGTH }) }) } test("a card Stripe declines is said in the card page's one notice, Pay under the form", async ({ page }) => { - await cardFits(page, new RegExp(`^${DECLINED}$`), await routedCardOrder(page, tenLetters), { declines: true }) + await cardFits(page, new RegExp(`^${DECLINED}$`), await routedCardOrder(page, tenLetters), heldPrice(tenLetters.label.length), { declines: true }) await expect(onStep(page).locator(".name-check")).toHaveClass(/\bdanger\b/) }) test("a card Stripe declines in a browser that cannot remember a card payment takes the warning's place, Pay under the form", async ({ page }) => { - await cardFits(page, new RegExp(`^${DECLINED}$`), await routedCardOrder(page, { ...tenLetters, forgetful: true }), { declines: true }) + await cardFits(page, new RegExp(`^${DECLINED}$`), await routedCardOrder(page, { ...tenLetters, forgetful: true }), heldPrice(tenLetters.label.length), { declines: true }) }) // Stripe's logo tone stands for the appearance: light on the dark theme, dark on the light one test("the card form follows the system's theme while none is chosen, and the theme switch, in place", async ({ page }) => { await page.emulateMedia({ colorScheme: "light" }) const open = await routedCardOrder(page, tenLetters) - await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: stripeOnCue(FORMS_PX[1]) })) + await page.route("https://js.stripe.com/**", (route) => route.fulfill({ contentType: "text/javascript", body: stripeOnCue(FORMS_PX[1], heldPrice(tenLetters.label.length)) })) await open() await expect(onStep(page).getByRole("heading", { name: "Pay by card" })).toBeVisible() await loadCard(page) - await expect(onStep(page).locator(".stripe > div")).toHaveCount(1) + await expect(cardFrame(page).locator("#form > div")).toHaveCount(1) expect(await cardSeen(page), "made in the light theme").toEqual({ logos: [], mounts: 1 }) const html = page.locator("html") await page.emulateMedia({ colorScheme: "dark" }) @@ -437,8 +447,8 @@ test.describe(() => { const FIT_INVOICE = "inv-fitall" // an invoice of a kept order, as the service answers it, for a page to draw const invoiceOf = (o: KeptOrder, status: string, reg: Record, change: Record = {}) => ({ - invoiceId: FIT_INVOICE, status, amount: 10000, currency: "usd", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), kind: "name", registration: registrationView(o, reg), - cryptoCurrency: "btc", cryptoAmount: "0.00156", address: "bcrt1qjhmc6927ct4w4vnas0g70pg3sdhgfdhcl8pd7s", ...change, + invoiceId: FIT_INVOICE, status, amount: heldPrice(o.label.length), currency: "usd", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), kind: "name", registration: registrationView(o, reg), + cryptoCurrency: "btc", cryptoAmount: "0.00156", ...bitcoinPayee(devReceiving, LOCAL.bitcoinHrp, 0), ...change, }) // the money that reached an invoice short of its amount const PART = { cryptoAmountPaid: "0.0005", cryptoAmountDue: "0.00106", paidInFull: false } @@ -493,7 +503,7 @@ test.describe(() => { await expect(onStep(page).getByText("Card is unavailable right now")).toBeVisible() await fitsWindow(page, "o6-review-code-and-method-refused", frames) await page.unroute("**/api/invoice") - await page.route("**/api/invoice", (route) => route.request().method() === "POST" ? route.fulfill({ status: 409, json: { type: "catalog_changed", price: 12345 } }) : route.continue()) + await page.route("**/api/invoice", (route) => route.request().method() === "POST" ? route.fulfill({ status: 409, json: { type: "catalog_changed", price: heldPrice(label.length) } }) : route.continue()) await payButton(page).click() await expect(onStep(page).getByRole("heading", { name: "The price changed" })).toBeVisible() await fitsWindow(page, "o7-price-changed", frames) @@ -587,8 +597,8 @@ test("the home keeps its headline and search still as each kind of answer comes, const linked = (kind: "contact" | "channel") => ({ preview: okPreview(kind, kind), link: kind === "contact" ? contactLink("H1") : channelLink("H2"), deepLink: "simplex:/a#x" }) // the search's answers for a name: available, taken with two chats, and this browser's, of `owner`, with two chats -const homeAnswers = (owner: string) => ({ - available: { found: { type: "available", price: 10000, years: 2, terms: TERMS } }, +const homeAnswers = (owner: string, label: string) => ({ + available: { found: { type: "available", price: heldPrice(label.length), years: 2, terms: TERMS } }, taken: registeredAnswer(`0x${"00".repeat(19)}01`, Math.floor(Date.now() / 1000) + YEAR_S, { contact: "", channel: "" }, [linked("contact"), linked("channel")]), yours: registeredAnswer(owner, Math.floor(Date.now() / 1000) + YEAR_S, { contact: "", channel: "" }, [linked("contact"), linked("channel")]), }) @@ -609,7 +619,7 @@ test.describe(() => { for (const label of [SHORT_NAME, wideLabel(6), wideLabel(MAX_LABEL_LENGTH)]) { const { owner } = await keepOrder(page, "reg-rowfit", null, label) await page.route("**/api/registration/reg-rowfit*", (route) => route.fulfill({ status: 404, json: { type: "not_found" } })) - for (const [state, answer] of Object.entries(homeAnswers(owner))) { + for (const [state, answer] of Object.entries(homeAnswers(owner, label))) { await page.unroute("**/api/name/**") await page.route("**/api/name/**", (route) => route.fulfill({ json: answer })) for (const size of FIT_SIZES) { @@ -750,6 +760,7 @@ test.describe(() => { // A name of the widest letters breaks its lines as early as any name of its length can; drawn at random from two // letters, it is still new to the chain on each run. const wideLabel = (length: number) => Array.from({ length }, () => (Math.random() < 0.5 ? "m" : "w")).join("") +const LONG_REGISTERED = 25 for (const length of [15, 25, MAX_LABEL_LENGTH]) { test(`every purchase step fits both windows for a name of ${length} wide letters`, async ({ page, request }) => { @@ -777,7 +788,7 @@ for (const length of [15, 25, MAX_LABEL_LENGTH]) { await expect(page.locator(".stage.active", { hasText: "Waiting" })).toBeVisible({ timeout: REGISTRATION_MS }) await fitsWindow(page, `${shots}-6-registering`) await waitRegistered(page, label) - await fitsWindow(page, `${shots}-7-registered`) + await fitsWindow(page, `${shots}-7-registered`, undefined, length > LONG_REGISTERED) // a heading with the name in it may take more lines; the main button stays where every step's is for (const [i, size] of FIT_SIZES.entries()) { expect(new Set(Object.values(frames).map((f) => f[i].actions)).size, `the actions' row at ${size.width}x${size.height}: ${JSON.stringify(frames)}`).toBe(1) @@ -793,7 +804,7 @@ test(`the name-is-yours screen fits both windows for a name of ${MAX_LABEL_LENGT await page.goto(`/?registration=${registrationId}`) await expect(page.getByRole("heading", { name: `${label}.simplex is yours` })).toBeVisible() await expect(onStep(page).getByRole("button", { name: "Edit links" })).toBeVisible() - await fitsWindow(page, `long-${MAX_LABEL_LENGTH}-m-registered`) + await fitsWindow(page, `long-${MAX_LABEL_LENGTH}-m-registered`, undefined, true) }) test("a part paid takes the name's note with its notice, the payment keeping its heading still and fitting both windows", async ({ page, request }) => { diff --git a/webapp/index.html b/webapp/index.html index 8cae586b..f38df896 100644 --- a/webapp/index.html +++ b/webapp/index.html @@ -9,7 +9,7 @@ - + @@ -18,13 +18,13 @@ + no preload goes unused. The build writes the script's hash into the page's CSP. --> + its hash is in the page's CSP --> - - + + diff --git a/webapp/package-lock.json b/webapp/package-lock.json index 28bd8eea..40dfcf54 100644 --- a/webapp/package-lock.json +++ b/webapp/package-lock.json @@ -9,6 +9,7 @@ "dependencies": { "@noble/curves": "1.9.7", "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "jsqr": "1.4.0" diff --git a/webapp/package.json b/webapp/package.json index 8e957c90..27236261 100644 --- a/webapp/package.json +++ b/webapp/package.json @@ -5,15 +5,19 @@ "type": "module", "scripts": { "dev": "vite", + "dev:card": "vite --config card/vite.config.ts", "build": "tsc --noEmit && vite build", + "build:card": "vite build --config card/vite.config.ts", "test": "vitest run", "e2e": "playwright test", "chain:deploy": "node dev/deploy.ts", + "check:mainnet": "node dev/check-mainnet.ts", "mock": "node dev/mock.ts" }, "dependencies": { "@noble/curves": "1.9.7", "@noble/hashes": "1.8.0", + "@scure/base": "1.2.6", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "jsqr": "1.4.0" diff --git a/webapp/playwright.config.ts b/webapp/playwright.config.ts index 61072e60..2fda5fe4 100644 --- a/webapp/playwright.config.ts +++ b/webapp/playwright.config.ts @@ -1,5 +1,6 @@ import { defineConfig, devices } from "@playwright/test" -import { mockUrl, pagePort, pageUrl } from "./e2e/slots.ts" +import { codesPagePort, codesPageUrl, mockUrl, pagePort, pageUrl } from "./e2e/slots.ts" +import { LOCAL } from "./src/config.ts" // BASE_URL points the tests at another server, such as `npx vite preview` of the production build const BASE_URL = process.env.BASE_URL @@ -10,6 +11,8 @@ const CHROME = { ...devices["Desktop Chrome"], viewport: { width: 1280, height: const FIREFOX = { ...devices["Desktop Firefox"], viewport: { width: 1280, height: 900 } } const SAFARI = { ...devices["Desktop Safari"], viewport: { width: 1280, height: 900 } } +const pageServer = (port: number, url: string, env: Record) => ({ command: `npx vite --host 127.0.0.1 --port ${port}`, url, env, reuseExistingServer: true }) + const FRAMES = /frames\.spec\.ts$/ const SCREENS = /screens\.spec\.ts$/ const WEBKIT_WORKERS = 2 @@ -41,10 +44,11 @@ export default defineConfig({ ...FIREFOX_158_PROJECT, ...SCREENS_PROJECT, ], - webServer: BASE_URL ? undefined : Array.from({ length: SLOTS }, (_, slot) => ({ - command: `npx vite --host 127.0.0.1 --port ${pagePort(slot)}`, - url: pageUrl(slot), - env: { MOCK_URL: mockUrl(slot) }, - reuseExistingServer: true, - })), + webServer: [ + { command: "npx vite --config card/vite.config.ts", url: LOCAL.cardOrigin, reuseExistingServer: true }, + ...BASE_URL ? [] : Array.from({ length: SLOTS }, (_, slot) => [ + pageServer(pagePort(slot), pageUrl(slot), { MOCK_URL: mockUrl(slot) }), + pageServer(codesPagePort(slot), codesPageUrl(slot), { MOCK_URL: mockUrl(slot), VITE_CODES_ONLY: "true" }), + ]).flat(), + ], }) diff --git a/webapp/src/api.ts b/webapp/src/api.ts index b9d22b79..e8796465 100644 --- a/webapp/src/api.ts +++ b/webapp/src/api.ts @@ -1,13 +1,15 @@ -// The names service's HTTP API, on the page's own origin. +// The names service's HTTP API, at SITE.apiOrigin. import { sha256 } from "@noble/hashes/sha2" import { keccak_256 } from "@noble/hashes/sha3" import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils" +import { heldPrice, SITE } from "./config.ts" +import { bitcoinProven, moneroProven, type ViewProof } from "./crypto/payees.ts" import { MAX_LABEL_LENGTH } from "./names.ts" const REFUSALS = [ "bad_request", "invalid_name", "invalid_link", "not_found", "method_not_allowed", "internal", "rate_limited", "provider_unavailable", "terms_unavailable", "name_check_unavailable", "code_invalid", "code_used", "code_reserved", "code_expired", "code_not_covering", "payment_pending", "codes_only", "order_exists", - "name_taken", "catalog_changed", "terms_changed", "registration_changed", "not_open", "funded", + "name_taken", "catalog_changed", "terms_changed", "registration_changed", "not_open", "funded", "downtime", "stale_nonce", "record_reverted", "edit_pending", "edit_limit", ] as const type Refusal = typeof REFUSALS[number] @@ -58,13 +60,6 @@ export function retryDelay(e: unknown, usual: number): number | null { export type Phase = "unpaid" | "closed" | "queued" | "committing" | "committed" | "registering" | "registered" | "ended" | "taken" | "failed" export type Method = "card" | "btc" | "xmr" -export interface ChainInfo { - resolver: string - sponsor: string - chainId: number - tld: string -} - export const LINK_KINDS = ["contact", "channel"] as const export interface Links { contact: string @@ -97,6 +92,8 @@ export function signedHash(terms: string | null | undefined): string | null { return hash && /^[0-9a-f]{64}$/.test(hash) ? `0x${hash}` : null } +export const heldTerms = (hash: string, community: boolean): Terms | undefined => (community ? SITE.communityTerms : SITE.generalTerms).find((t) => t.hash === hash) + const LOCAL_CHAIN_ID = 31337 const MAX_PORT = 65535 const TERMS_LINK = /^(?:https:\/\/(?:git\.simplex\.chat\/simplex-chat\/simplex-chat\/raw\/commit|raw\.githubusercontent\.com\/simplex-chat\/simplex-chat)\/([0-9a-f]{40})|http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4}))\/([A-Za-z0-9_./-]+)#sha256=([0-9a-f]{64})$/ @@ -239,6 +236,8 @@ export const signedTermsOf = (terms: AgreedTerms) => `${terms.communityName ? CO const LATE_WAITS = ["confirming", "crediting", "support"] as const export type LateWait = typeof LATE_WAITS[number] +export type AddressProof = { type: "btc"; keyTweak: string } | { type: "xmr"; spendTweak: string; viewProof: ViewProof } + export interface InvoiceView { invoiceId: string status: "open" | "paid" | "expired" @@ -254,6 +253,7 @@ export interface InvoiceView { settledAt?: string clientSecret?: string address?: string + addressProof?: AddressProof cryptoAmount?: string cryptoCurrency?: Method requiredConfirmations?: number @@ -267,6 +267,26 @@ export const paymentKept = ({ balance, price }: RegistrationView) => balance !== export const selectable = (view: RegistrationView) => view.phase.type === "taken" && (view.payment.type === "code" || paymentKept(view)) +export const invoiceMethod = (inv: InvoiceView): Method | null => + inv.clientSecret !== undefined && inv.address === undefined && (inv.cryptoCurrency ?? "card") === "card" ? "card" + : (inv.cryptoCurrency === "btc" || inv.cryptoCurrency === "xmr") && inv.address !== undefined && inv.clientSecret === undefined ? inv.cryptoCurrency + : null + +function provenFromKeys(address: string, coin: InvoiceView["cryptoCurrency"], p: AddressProof | undefined): boolean { + if (coin === "btc" && p?.type === "btc") return bitcoinProven(address, p.keyTweak, SITE.bitcoinReceiveKeys, SITE.bitcoinHrp) + if (coin === "xmr" && p?.type === "xmr") return moneroProven(address, p.spendTweak, p.viewProof, SITE.moneroPrimaryAddresses, SITE.moneroSubaddressPrefix) + return false +} + +const proven = new Map() + +export function addressProven({ address, cryptoCurrency, addressProof }: InvoiceView): boolean { + if (address === undefined) return true + const key = JSON.stringify([address, cryptoCurrency, addressProof]) + if (!proven.has(key)) proven.set(key, provenFromKeys(address, cryptoCurrency, addressProof)) + return proven.get(key)! +} + export const holdsPayment = (inv: InvoiceView) => Boolean(inv.amountPaid) || Number(inv.cryptoAmountPaid ?? "0") > 0 || inv.paidInFull === true // All of a closed invoice's amount arrived after it closed and is credited, or waits on support alone. BTCPay keeps such an @@ -324,7 +344,7 @@ export const LIMITED_WAIT_S = 30 // The service's times are read against its clock, which each answer's Date header gives to the second; a device off by less than this is taken as right. const CLOCK_SLACK_MS = 2000 let clockOffsetMs = 0 -// counts changes of the offset, so a request signed before one can be signed again +// counts changes of the offset by more than the slack, so a request signed before one can be signed again let clockChanges = 0 export const serviceNow = () => Date.now() + clockOffsetMs export const serviceSeconds = () => Math.floor(serviceNow() / 1000) @@ -345,7 +365,7 @@ async function call(method: string, path: string, body?: unknown, signal?: Ab try { let res: Response try { - res = await fetch(path, { + res = await fetch(`${SITE.apiOrigin}${path}`, { method, signal: stop.signal, headers: body === undefined ? {} : { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), @@ -357,7 +377,7 @@ async function call(method: string, path: string, body?: unknown, signal?: Ab const date = Date.parse(res.headers.get("date") ?? "") if (Number.isFinite(date)) { const offset = Math.abs(date - Date.now()) > CLOCK_SLACK_MS ? date - Date.now() : 0 - if (offset !== clockOffsetMs) clockChanges++ + if (Math.abs(offset - clockOffsetMs) > CLOCK_SLACK_MS) clockChanges++ clockOffsetMs = offset } // a body cut off on its way is no answer, even after a 200 @@ -420,7 +440,7 @@ const isBalance = (v: unknown) => isObject(v) && isAmount(v.amount) && isAmount( const isPayment = (v: unknown) => isObject(v) && ((v.type === "invoice" && METHODS.includes(v.method as Method)) || v.type === "code") const isHash = (v: unknown) => typeof v === "string" && /^0x[0-9a-f]{64}$/.test(v) const isAgreedTerms = (v: unknown) => isObject(v) && typeof v.communityName === "boolean" && isHash(v.termsHash) -const isTerms = (v: unknown, chainId: number) => isObject(v) && isHash(v.hash) && typeof v.link === "string" && termsLink(v.link, chainId) !== null && keccakOf(v.link) === v.hash +const isTerms = (v: unknown) => isObject(v) && isHash(v.hash) && typeof v.link === "string" && termsLink(v.link, SITE.chainId) !== null && keccakOf(v.link) === v.hash const isCommunity = (v: unknown) => v === null || (isObject(v) && optional(v.for, (f) => typeof f === "string" && f !== "") && isCount(v.years)) const isAcceptance = (v: unknown) => isObject(v) && typeof v.community === "boolean" && isText(v.policy) && isHash(v.termsHash) && Number.isInteger(v.nonce) && (v.nonce as number) >= 0 const isToSign = (v: unknown) => isObject(v) && (v.type === "unread" || (v.type === "read" && isAmount(v.intentNonce) && isAcceptance(v.acceptance))) @@ -435,16 +455,22 @@ const isRegistration = (v: unknown) => isObject(v) && isText(v.id) && Number.isI const isInvoice = (v: unknown) => isObject(v) && isText(v.invoiceId) && ["open", "paid", "expired"].includes(v.status as string) && isAmount(v.amount) && isText(v.currency) && isText(v.expiresAt) && isRegistration(v.registration) && optional(v.amountPaid, isAmount) && optional(v.cryptoAmountPaid, isDecimal) && optional(v.cryptoAmountDue, isDue) && optional(v.cryptoAmount, isDecimal) - && optional(v.paidInFull, (x) => typeof x === "boolean") && optional(v.address, isText) + && optional(v.paidInFull, (x) => typeof x === "boolean") && optional(v.address, isText) && optional(v.clientSecret, isText) && optional(v.cryptoCurrency, (x) => ["card", "btc", "xmr"].includes(x as string)) && optional(v.requiredConfirmations, (x) => Number.isInteger(x) && (x as number) >= 0) const clampDue = (inv: InvoiceView): InvoiceView => inv.cryptoAmountDue?.startsWith("-") ? { ...inv, cryptoAmountDue: "0" } : inv -const checkedInvoice = (answer: Promise) => checked(answer, isInvoice).then(clampDue) +const isAddressProof = (p: unknown): p is AddressProof => isObject(p) && ((p.type === "btc" && isText(p.keyTweak)) + || (p.type === "xmr" && isText(p.spendTweak) && isObject(p.viewProof) && isText(p.viewProof.challenge) && isText(p.viewProof.response))) +const proofParsed = (inv: InvoiceView): InvoiceView => { + const { addressProof, ...rest } = inv + return addressProof === undefined || isAddressProof(addressProof) ? inv : rest +} +const checkedInvoice = (answer: Promise) => checked(answer, isInvoice).then(clampDue).then(proofParsed) const isTime = (v: unknown) => typeof v === "string" && Number.isFinite(Date.parse(v)) // none left only while an edit is counted, which returns at nextAt const isRecordEdits = (v: unknown) => isObject(v) && Number.isInteger(v.left) && (v.left as number) >= 0 && optional(v.nextAt, isTime) && (v.left !== 0 || v.nextAt !== undefined) const isResolverRecords = (v: unknown) => isObject(v) && (v.type === "other" || (v.type === "own" && isText(v.contact) && isText(v.channel) && isAmount(v.nonce) && isRecordEdits(v.edits))) -const isNameFound = (v: unknown, chainId: number) => isObject(v) && (v.type === "reserved" || v.type === "taken" - || (v.type === "available" && isAmount(v.price) && isCount(v.years) && optional(v.terms, (t) => isTerms(t, chainId))) +const isNameFound = (v: unknown) => isObject(v) && (v.type === "reserved" || v.type === "taken" + || (v.type === "available" && isAmount(v.price) && isCount(v.years) && optional(v.terms, isTerms)) || (v.type === "registered" && isText(v.owner) && isText(v.resolver) && isAmount(v.expiresAt) && isAmount(v.gracePeriod) && Array.isArray(v.entities) && v.entities.every(isEntity) && isResolverRecords(v.records))) @@ -452,9 +478,9 @@ type WireRecords = ({ type: "own"; nonce: number; edits: { left: number; nextAt? type WireFound = Extract | { type: "available"; price: number; years: number; terms?: Terms } | (Omit, "entities" | "records"> & { entities: LinkEntity[]; records: WireRecords }) -function foundOf(f: WireFound): Found { +function foundOf(f: WireFound, community: boolean): Found { switch (f.type) { - case "available": return { type: "available", price: f.price, years: f.years, terms: f.terms ?? null } + case "available": return { type: "available", price: f.price, years: f.years, terms: (f.terms && heldTerms(f.terms.hash, community)) ?? null } case "registered": { const records: ResolverRecords = f.records.type === "own" ? { ...f.records, edits: { left: f.records.edits.left, nextAt: f.records.edits.nextAt === undefined ? null : Date.parse(f.records.edits.nextAt) / 1000 } } @@ -465,73 +491,92 @@ function foundOf(f: WireFound): Found { } } -export const searchName = (labelHash: string, length: number, chainId: number) => - checked<{ found: WireFound; community?: Community }>(call("GET", `/api/name/${labelHash}?length=${length}`), (a) => optional(a.community, isCommunity) && isNameFound(a.found, chainId)) - .then((a): SearchAnswer => ({ found: foundOf(a.found), community: a.community ?? null })) +export const searchName = (labelHash: string, length: number) => + checked<{ found: WireFound; community?: Community }>(call("GET", `/api/name/${labelHash}?length=${length}`), (a) => optional(a.community, isCommunity) && isNameFound(a.found)) + .then(({ found, community = null }): SearchAnswer => ({ found: foundOf(found, community !== null), community })) export const previewLink = (link: string) => checked(call("POST", "/api/link/preview", { link }), isPreview).then(profileOf) // The terms' text, which the service fetches by their link, only when it is the file the link names: the page shows the very // text whose acceptance the owner signs. -export async function termsText(terms: Terms, chainId: number, signal?: AbortSignal): Promise { +export async function termsText(terms: Terms, signal?: AbortSignal): Promise { const read = await call>("GET", `/api/terms/${terms.hash}`, undefined, signal) - const digest = termsLink(terms.link, chainId)?.digest + const digest = termsLink(terms.link, SITE.chainId)?.digest if (read.link !== terms.link || keccakOf(terms.link) !== terms.hash || typeof read.text !== "string" || bytesToHex(sha256(utf8ToBytes(read.text))) !== digest) throw noAnswer() return read.text } -export async function currentTermsOf(hash: string, chainId: number): Promise { - const read = await call>("GET", `/api/terms/${hash}`) - const terms = { hash, link: read.link } - if (!isTerms(terms, chainId)) throw noAnswer() - return terms as Terms -} const CODE_STATES = ["unused", "used", "reserved", "expired", "unpaid", "revoked"] as const export type CodeState = typeof CODE_STATES[number] interface CodeAnswer { minLength: number; years: number; state: CodeState } export async function checkCode(code: string, signal?: AbortSignal): Promise { const answer: unknown = await call("POST", "/api/code/check", { code }, signal) const drawable = isObject(answer) && isCount(answer.minLength) && (answer.minLength as number) <= MAX_LABEL_LENGTH && isCount(answer.years) - && CODE_STATES.includes(answer.state as CodeState) + && (answer.years as number) >= SITE.minCodeYears && (answer.years as number) <= SITE.maxCodeYears && CODE_STATES.includes(answer.state as CodeState) if (!drawable) throw noAnswer() return answer as unknown as CodeAnswer } -const signingTerms = (sent: Promise, chainId: number) => sent.catch((e: unknown) => { +const signingTerms = (sent: Promise) => sent.catch((e: unknown) => { if (!(e instanceof ApiError && e.code === "terms_changed")) throw e - if (!isTerms(e.body.terms, chainId) || !isCommunity(e.body.community)) throw noAnswer() - throw new TermsChanged(e, e.body.terms as Terms, e.body.community as Community | null) + const community = e.body.community as Community | null + const terms = isTerms(e.body.terms) && isCommunity(community) ? heldTerms((e.body.terms as Terms).hash, community !== null) : undefined + if (!terms) throw noAnswer() + throw new TermsChanged(e, terms, community) }) -export const createOrder = (order: SignedOrder, method: Method, price: number, chainId: number) => - checkedInvoice(signingTerms(call("POST", "/api/invoice", { kind: "name", order: orderOf(order), method, price, reveal: order.reveal }), chainId)) -export const registerWithCode = (order: SignedOrder, code: string, chainId: number) => - checked<{ registrationId: string }>(signingTerms(call("POST", "/api/name/register", { order: orderOf(order), code, reveal: order.reveal }), chainId), (a) => isText(a.registrationId)) +const pricing = (length: number, sent: Promise) => sent.catch((e: unknown) => { + if (e instanceof ApiError && e.code === "catalog_changed" && e.body.price !== heldPrice(length)) throw noAnswer() + throw e +}) + +export const createOrder = (order: SignedOrder, method: Method, price: number) => + checkedInvoice(pricing(order.length, signingTerms(call("POST", "/api/invoice", { kind: "name", order: orderOf(order), method, price, reveal: order.reveal })))) +export const registerWithCode = (order: SignedOrder, code: string) => + checked<{ registrationId: string }>(signingTerms(call("POST", "/api/name/register", { order: orderOf(order), code, reveal: order.reveal })), (a) => isText(a.registrationId)) export type ToSignRead = Extract export const signFor = (labelHash: string, owner: string) => checked(call("GET", `/api/name/${labelHash}/sign?owner=${owner}`), (a) => a.type === "read" && isToSign(a)) -export const cancelInvoice = (invoiceId: string) => checkedInvoice(call("POST", `/api/invoice/${encodeURIComponent(invoiceId)}/cancel`)) +export type OrderAction = "read" | "cancel" | "retry" | "reveal" +export interface RequestSignature { timestamp: number; signature: string } +export type OrderSigner = (id: string, action: OrderAction) => RequestSignature + +export async function signedOnce(send: () => Promise): Promise { + const clock = clockVersion() + try { + return await send() + } catch (e) { + if (e instanceof ApiError && e.code === "bad_request" && clockVersion() !== clock) return send() + throw e + } +} +const signatureQuery = ({ timestamp, signature }: RequestSignature) => `timestamp=${timestamp}&signature=${signature}` + +export const cancelInvoice = (invoiceId: string, sign: OrderSigner) => + signedOnce(() => checkedInvoice(call("POST", `/api/invoice/${encodeURIComponent(invoiceId)}/cancel`, sign(invoiceId, "cancel")))) // what a long poll on an invoice has seen: its status, its registration's version, and the payment marks, the paid amount // and paidInFull, as Monero can report a full payment with no amount yet interface SeenInvoice { status: string; version: number; paid: string; full: boolean } export const seenOf = (inv: InvoiceView): SeenInvoice => ({ status: inv.status, version: inv.registration.version, paid: inv.cryptoAmountPaid ?? "", full: inv.paidInFull === true }) -export function readInvoice(invoiceId: string, seen?: SeenInvoice, signal?: AbortSignal): Promise { - const query = seen ? `?wait=${seen.status}&seenVersion=${seen.version}&seenPaid=${encodeURIComponent(seen.paid)}&seenFull=${seen.full ? "1" : "0"}` : "" - return checkedInvoice(call("GET", `/api/invoice/${encodeURIComponent(invoiceId)}${query}`, undefined, signal, seen ? null : REQUEST_TIMEOUT_MS)) +export function readInvoice(invoiceId: string, sign: OrderSigner, seen?: SeenInvoice, signal?: AbortSignal): Promise { + const held = seen ? `&wait=${seen.status}&seenVersion=${seen.version}&seenPaid=${encodeURIComponent(seen.paid)}&seenFull=${seen.full ? "1" : "0"}` : "" + return signedOnce(() => checkedInvoice(call("GET", `/api/invoice/${encodeURIComponent(invoiceId)}?${signatureQuery(sign(invoiceId, "read"))}${held}`, undefined, signal, seen ? null : REQUEST_TIMEOUT_MS))) } -export function readRegistration(registrationId: string, seenVersion?: number, signal?: AbortSignal): Promise { +export function readRegistration(registrationId: string, sign: OrderSigner, seenVersion?: number, signal?: AbortSignal): Promise { const held = seenVersion !== undefined - return checked(call("GET", `/api/registration/${encodeURIComponent(registrationId)}${held ? `?seenVersion=${seenVersion}` : ""}`, undefined, signal, held ? null : REQUEST_TIMEOUT_MS), isRegistration) + return signedOnce(() => checked(call("GET", `/api/registration/${encodeURIComponent(registrationId)}?${signatureQuery(sign(registrationId, "read"))}${held ? `&seenVersion=${seenVersion}` : ""}`, + undefined, signal, held ? null : REQUEST_TIMEOUT_MS), isRegistration)) } -export const reveal = (registrationId: string, body: RevealBody) => - call>("POST", `/api/registration/${encodeURIComponent(registrationId)}/reveal`, body) -export const selectName = (registrationId: string, body: Omit, chainId: number) => - checked(signingTerms(call("POST", `/api/registration/${encodeURIComponent(registrationId)}/name`, { ...signedFields(body), reveal: body.reveal }), chainId), isRegistration) -export const retry = (registrationId: string) => checked(call("POST", `/api/registration/${encodeURIComponent(registrationId)}/retry`), isRegistration) +export const reveal = (registrationId: string, body: RevealBody, sign: OrderSigner) => + signedOnce(() => call>("POST", `/api/registration/${encodeURIComponent(registrationId)}/reveal`, { ...body, request: sign(registrationId, "reveal") })) +export const selectName = (registrationId: string, body: Omit) => + checked(pricing(body.length, signingTerms(call("POST", `/api/registration/${encodeURIComponent(registrationId)}/name`, { ...signedFields(body), reveal: body.reveal }))), isRegistration) +export const retry = (registrationId: string, sign: OrderSigner) => + signedOnce(() => checked(call("POST", `/api/registration/${encodeURIComponent(registrationId)}/retry`, sign(registrationId, "retry")), isRegistration)) const isFound = (r: unknown) => isObject(r) && isText(r.registrationId) && nullable(r.invoiceId, isText) && PHASES.includes(r.phase as Phase) && isText(r.createdAt) && isText(r.labelHash) && isText(r.sealed) export interface FoundOrder { diff --git a/webapp/src/card-frame.ts b/webapp/src/card-frame.ts new file mode 100644 index 00000000..026f285a --- /dev/null +++ b/webapp/src/card-frame.ts @@ -0,0 +1,60 @@ +import { SITE } from "./config.ts" +import { el } from "./dom.ts" +import { CONFIRM_FAILED, type ConfirmOutcome, type FromCard, type MountedCard, type Theme, type ToCard, MISMATCHED } from "./stripe.ts" + +export const CARD_FRAME_TIMEOUT_MS = 25_000 + +const isFromCard = (m: unknown): m is FromCard => typeof m === "object" && m !== null && "type" in m && ( + m.type === "mounted" || m.type === "invalid" + || (m.type === "height" && "px" in m && typeof m.px === "number" && Number.isFinite(m.px) && m.px >= 0) + || (m.type === "paid" && "id" in m && typeof m.id === "string") + || (m.type === "declined" && "message" in m && typeof m.message === "string") + || (m.type === "failed" && "reason" in m && (m.reason === MISMATCHED || m.reason === "unloaded"))) + +const outcomeOf = (m: FromCard): ConfirmOutcome => m.type === "paid" ? { kind: "submitted", id: m.id } : m.type === "invalid" ? { kind: "invalid" } + : { kind: "error", message: m.type === "declined" ? m.message : CONFIRM_FAILED } + +export function mountCardFrame(clientSecret: string, amount: number, target: HTMLElement, theme: Theme): Promise { + const frame = el("iframe", { src: `${SITE.cardOrigin}/`, title: "Card form", class: "card-frame" }) + const post = (message: ToCard) => frame.contentWindow?.postMessage(message, SITE.cardOrigin) + let answer: ((m: FromCard) => void) | null = null + let unwatch: () => void = () => undefined + const stop = () => { + removeEventListener("message", onMessage) + unwatch() + answer?.({ type: "failed", reason: "unloaded" }) + frame.remove() + } + const card: MountedCard = { + confirm: () => new Promise((done) => { + answer = (m) => { + answer = null + done(outcomeOf(m)) + } + post({ type: "confirm" }) + }), + destroy: stop, + } + let settle: (result: MountedCard | typeof MISMATCHED | null) => void = () => undefined + function onMessage(e: MessageEvent): void { + const m = e.data + if (e.origin !== SITE.cardOrigin || e.source !== frame.contentWindow || !isFromCard(m)) return + if (m.type === "height") frame.style.height = `${m.px}px` + else if (m.type === "mounted") settle(card) + else if (m.type === "failed" && answer === null) settle(m.reason === MISMATCHED ? MISMATCHED : null) + else answer?.(m) + } + return new Promise((resolve) => { + const timer = setTimeout(() => settle(null), CARD_FRAME_TIMEOUT_MS) + settle = (result) => { + settle = () => undefined + clearTimeout(timer) + if (result !== card) stop() + resolve(result) + } + addEventListener("message", onMessage) + frame.addEventListener("load", () => post({ type: "mount", clientSecret, amount, dark: theme.dark() }), { once: true }) + unwatch = theme.watch((dark) => post({ type: "theme", dark })) + target.append(frame) + }) +} diff --git a/webapp/src/config.ts b/webapp/src/config.ts index 691b2167..c1271010 100644 --- a/webapp/src/config.ts +++ b/webapp/src/config.ts @@ -1,59 +1,151 @@ -// What differs between deployments, which the service answers at GET /api/config, so the same build serves every one. -// index.html preloads it, so its answer is normally in before the page's modules have loaded. -import { ApiError, type ChainInfo } from "./api.ts" -import { setPageMode } from "./mode.ts" -import { setPublishableKey } from "./stripe.ts" +import type { Terms } from "./api.ts" export const CONFIG_PATH = "/api/config" +export const CONFIG_TIMEOUT_MS = 5000 -export interface NamesSite extends ChainInfo { - codesOnly: boolean +export interface Deployment { + chainId: number + tld: string + sponsor: string + resolver: string + namePolicy: string + baseRegistrar: string termStart: number + paidYears: number + communityYears: number + minCodeYears: number + maxCodeYears: number + codesOnly: boolean + priceBaseCentsPerYear: number + priceExceptions: PriceException[] + currency: "usd" + generalTerms: Terms[] + communityTerms: Terms[] + stripeKey: string + stripeLive: boolean + cardOrigin: string + pageOrigins: string[] + apiOrigin: string + appOrigin: string + bitcoinHrp: string + bitcoinReceiveKeys: string[] + moneroSubaddressPrefix: number + moneroPrimaryAddresses: string[] +} + +export interface PriceException { + labelLength: number + centsPerYear: number +} + +export const MAINNET: Deployment = { + chainId: 1, + tld: "simplex", + sponsor: "0xeC9a522C756e46FB3E44d3405FFDd9368501Eb78", + resolver: "0x9BDa37F19b59Cbc58BA75932B3c598947fD88B0A", + namePolicy: "0x5147b65F547b766DBaf520127e8f59834475021E", + baseRegistrar: "0x4c0589dbC22862Babb25EB72D11bBA49d84AAbE8", + termStart: 1798761600, + paidYears: 2, + communityYears: 2, + minCodeYears: 2, + maxCodeYears: 10, + codesOnly: true, + priceBaseCentsPerYear: 5000, + priceExceptions: [], + currency: "usd", + generalTerms: [{ + hash: "0x70e0396b0a83f6c4e624b2e43d537b7c9816c6868bf705080237d93f5aa2541d", + link: "https://raw.githubusercontent.com/simplex-chat/simplex-chat/7cfd522f0f26454fc913f978a45f5f6028017b10/docs/NAMES-CONDITIONS.md#sha256=6871119c6e4088d2b6f2d7890443a82a4b8e65dd1ccb73456ce8f13c3434e6ee", + }], + communityTerms: [{ + hash: "0x70e0396b0a83f6c4e624b2e43d537b7c9816c6868bf705080237d93f5aa2541d", + link: "https://raw.githubusercontent.com/simplex-chat/simplex-chat/7cfd522f0f26454fc913f978a45f5f6028017b10/docs/NAMES-CONDITIONS.md#sha256=6871119c6e4088d2b6f2d7890443a82a4b8e65dd1ccb73456ce8f13c3434e6ee", + }], + stripeKey: "", + stripeLive: true, + cardOrigin: "https://pay.simplex.domains", + pageOrigins: ["https://simplex.domains"], + apiOrigin: "https://api.simplex.domains", + appOrigin: "https://app.simplex.domains", + bitcoinHrp: "bc", + bitcoinReceiveKeys: [], + moneroSubaddressPrefix: 42, + moneroPrimaryAddresses: [], +} + +export const LOCAL: Deployment = { + chainId: 31337, + tld: "simplex", + sponsor: "0x0B306BF915C4d645ff596e518fAf3F9669b97016", + resolver: "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318", + namePolicy: "0x68B1D87F95878fE05B998F19b66F4baba5De1aed", + baseRegistrar: "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", + termStart: 1798761600, + paidYears: 2, + communityYears: 2, + minCodeYears: 2, + maxCodeYears: 10, + codesOnly: false, + priceBaseCentsPerYear: 5000, + priceExceptions: [{ labelLength: 7, centsPerYear: 10000 }, { labelLength: 6, centsPerYear: 20000 }], + currency: "usd", + generalTerms: [{ + hash: "0xb0ecf1bb8f71f387d7d56ea055cb44378c91a8ad2e66b9c0c6497adccaa599e9", + link: "http://127.0.0.1:8098/terms/00516a11b53ad775b7a51fc8a96c9199529e7b53424eec791df0755a15645bda.md#sha256=00516a11b53ad775b7a51fc8a96c9199529e7b53424eec791df0755a15645bda", + }, { + hash: "0x79cb2cc4c33ab80f0883865eba393feb50383eadbd09c7d6fa9320213f1003d9", + link: "http://127.0.0.1:8098/terms/e40ffc052d26e9921b7a871fa2b2158e2c91fb0c5418bca2762285f5da13a726.md#sha256=e40ffc052d26e9921b7a871fa2b2158e2c91fb0c5418bca2762285f5da13a726", + }], + communityTerms: [{ + hash: "0xca7e84166f00dac5e40e8a0cbcd2a3ff5328d2d2a7fbb64c369c35b2c75f3f0f", + link: "http://127.0.0.1:8098/terms/7124c441467db09240c476e0347251fbe1f305d7d18bf3479af442c5587283f4.md#sha256=7124c441467db09240c476e0347251fbe1f305d7d18bf3479af442c5587283f4", + }, { + hash: "0xc84fc8765b05721378152c7f369ce2e3fb8ce48f37d3abe888347274e5d41897", + link: "http://127.0.0.1:8098/terms/c4aa8c69a695870643ceb72badbd1fcbfd866879379eb3c38ea0b9f17b2a1a59.md#sha256=c4aa8c69a695870643ceb72badbd1fcbfd866879379eb3c38ea0b9f17b2a1a59", + }, { + hash: "0x43c5f541d45cc6b0430acd28d29255eb65f90ac414d448f3f06be712a59a8788", + link: "https://git.simplex.chat/simplex-chat/simplex-chat/raw/commit/4cb24444a1f2e3d4c5b6a7980716253443526170/docs/community-terms.md#sha256=a081d9e2a2eb4c63f9dfa01f092724323ed8d24f8459f1626226e33d6198e8ab", + }, { + hash: "0xda08ab458b060f08de0ebe328d20d10b6f1d275237f1b3c03d2cc1177f5e3ba8", + link: "https://raw.githubusercontent.com/simplex-chat/simplex-chat/4cb24444a1f2e3d4c5b6a7980716253443526170/docs/community-terms.md#sha256=a081d9e2a2eb4c63f9dfa01f092724323ed8d24f8459f1626226e33d6198e8ab", + }], + stripeKey: "", + stripeLive: false, + cardOrigin: "http://127.0.0.1:5180", + pageOrigins: ["http://127.0.0.1", "http://localhost"], + apiOrigin: "", + appOrigin: "http://127.0.0.1:5181", + bitcoinHrp: "bcrt", + bitcoinReceiveKeys: ["0x036bf340760eb0da07d4d2bbb9d9aee7b7c27891cb72b6388cc0ee8d2a82d33e46"], + moneroSubaddressPrefix: 36, + moneroPrimaryAddresses: ["52jzuBBUMty3xPL3JsQxGP74LDuV6E1LS8Zda1PbdqQjGzFmH6N9ep9McbFKMALujVT9S5mKpbEgC5VPhfoAiVj8LdAqbp6"], } -export interface SiteConfig { stripePublishableKey: string; names: NamesSite | null } +declare const __MAINNET__: boolean + +export const SITE: Deployment = typeof __MAINNET__ === "undefined" ? LOCAL + : __MAINNET__ ? MAINNET + : { ...LOCAL, codesOnly: import.meta.env?.VITE_CODES_ONLY === "true", stripeKey: import.meta.env?.VITE_STRIPE_KEY ?? "", apiOrigin: import.meta.env?.VITE_API_ORIGIN ?? "" } + +export const heldPrice = (length: number) => (SITE.priceExceptions.find((e) => e.labelLength === length)?.centsPerYear ?? SITE.priceBaseCentsPerYear) * SITE.paidYears -const isText = (v: unknown) => typeof v === "string" -const isSeconds = (v: unknown) => Number.isInteger(v) && (v as number) >= 0 -const isNamesSite = (v: unknown): v is NamesSite => typeof v === "object" && v !== null && typeof (v as NamesSite).codesOnly === "boolean" - && isSeconds((v as NamesSite).chainId) && isText((v as NamesSite).resolver) && isText((v as NamesSite).sponsor) && isText((v as NamesSite).tld) && isSeconds((v as NamesSite).termStart) +export interface SiteConfig { downtime: boolean } + +const isObject = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v) export function configOf(body: unknown): SiteConfig | null { - if (typeof body !== "object" || body === null || !("stripePublishableKey" in body) || !("names" in body)) return null - const { stripePublishableKey, names } = body as Record - if (names !== null && !isNamesSite(names)) return null - return { stripePublishableKey: typeof stripePublishableKey === "string" ? stripePublishableKey.trim() : "", names } + if (!isObject(body) || !("names" in body)) return null + const { names } = body + if (names !== null && !isObject(names)) return null + return { downtime: names?.downtime === true } } export async function readConfig(init?: RequestInit): Promise { try { - const res = await fetch(CONFIG_PATH, init) + const res = await fetch(`${SITE.apiOrigin}${CONFIG_PATH}`, { ...init, signal: AbortSignal.timeout(CONFIG_TIMEOUT_MS) }) return res.ok ? configOf(await res.json()) : null } catch { return null } } - -let site: NamesSite | null = null - -// Unread, the page stays in open mode with no card form, as a page with nothing to pay with, until namesSite reads it. -export async function loadConfig(): Promise { - const config = await readConfig() - if (!config) return - site = config.names - setPageMode(site?.codesOnly ? "codes" : "open") - setPublishableKey(config.stripePublishableKey) -} - -export async function namesSite(): Promise { - if (!site) await loadConfig() - if (!site) throw new ApiError("network", 0, null, {}) - return site -} - -export const loadedSite = (): NamesSite | null => site - -export function readSite(): NamesSite { - if (!site) throw new Error("the names deployment is unread") - return site -} diff --git a/webapp/src/crypto/payees.ts b/webapp/src/crypto/payees.ts new file mode 100644 index 00000000..b0ac6c65 --- /dev/null +++ b/webapp/src/crypto/payees.ts @@ -0,0 +1,77 @@ +import { ed25519 } from "@noble/curves/ed25519" +import { secp256k1 } from "@noble/curves/secp256k1" +import { bytesToNumberLE, equalBytes } from "@noble/curves/utils" +import { ripemd160 } from "@noble/hashes/legacy" +import { sha256 } from "@noble/hashes/sha2" +import { keccak_256 } from "@noble/hashes/sha3" +import { concatBytes, hexToBytes, utf8ToBytes } from "@noble/hashes/utils" +import { base58xmr, bech32 } from "@scure/base" + +const SCALAR = /^[0-9a-f]{64}$/ +const WITNESS_V0 = 0 +const KEY_BYTES = 32 +const CHECKSUM_BYTES = 4 +const MONERO_ADDRESS_BYTES = 1 + 2 * KEY_BYTES + CHECKSUM_BYTES +const VIEW_PROOF = utf8ToBytes("simplex.domains view proof") +const L = ed25519.Point.Fn.ORDER +const G = ed25519.Point.BASE + +export interface ViewProof { challenge: string; response: string } + +export const p2wpkh = (hrp: string, publicKey: Uint8Array) => bech32.encode(hrp, [WITNESS_V0, ...bech32.toWords(ripemd160(sha256(publicKey)))]) + +export function bitcoinProven(address: string, keyTweak: string, receiveKeys: string[], hrp: string): boolean { + if (!SCALAR.test(keyTweak)) return false + const t = BigInt(`0x${keyTweak}`) + if (t === 0n || t >= secp256k1.Point.Fn.ORDER) return false + const tweak = secp256k1.Point.BASE.multiply(t) + return receiveKeys.some((key) => { + const derived = secp256k1.Point.fromHex(key.slice(2)).add(tweak) + return !derived.is0() && p2wpkh(hrp, derived.toBytes(true)) === address + }) +} + +export const hashToScalar = (...parts: Uint8Array[]) => bytesToNumberLE(keccak_256(concatBytes(...parts))) % L + +const scalarOf = (hex: string) => { + if (!SCALAR.test(hex)) return null + const value = bytesToNumberLE(hexToBytes(hex)) + return value < L ? value : null +} + +const pointOf = (bytes: Uint8Array) => { + try { + return ed25519.Point.fromBytes(bytes) + } catch { + return null + } +} + +export function moneroKeys(address: string): { prefix: number; spend: Uint8Array; view: Uint8Array } | null { + let bytes: Uint8Array + try { + bytes = base58xmr.decode(address) + } catch { + return null + } + if (bytes.length !== MONERO_ADDRESS_BYTES) return null + const body = bytes.slice(0, -CHECKSUM_BYTES) + if (!equalBytes(keccak_256(body).slice(0, CHECKSUM_BYTES), bytes.slice(-CHECKSUM_BYTES))) return null + return { prefix: bytes[0], spend: body.slice(1, 1 + KEY_BYTES), view: body.slice(1 + KEY_BYTES) } +} + +export function moneroProven(address: string, spendTweak: string, viewProof: ViewProof, primaryAddresses: string[], subaddressPrefix: number): boolean { + const sub = moneroKeys(address) + const [m, c, s] = [scalarOf(spendTweak), scalarOf(viewProof.challenge), scalarOf(viewProof.response)] + if (sub === null || sub.prefix !== subaddressPrefix || m === null || c === null || s === null) return false + const [D, C] = [pointOf(sub.spend), pointOf(sub.view)] + if (D === null || C === null || C.is0() || !C.isTorsionFree()) return false + return primaryAddresses.some((primary) => { + const keys = moneroKeys(primary)! + const [B, A] = [ed25519.Point.fromBytes(keys.spend), ed25519.Point.fromBytes(keys.view)] + if (!B.add(G.multiplyUnsafe(m)).equals(D)) return false + const R1 = G.multiplyUnsafe(s).add(A.multiplyUnsafe(c)) + const R2 = D.multiplyUnsafe(s).add(C.multiplyUnsafe(c)) + return hashToScalar(VIEW_PROOF, A.toBytes(), D.toBytes(), C.toBytes(), R1.toBytes(), R2.toBytes()) === c + }) +} diff --git a/webapp/src/crypto/seal.ts b/webapp/src/crypto/seal.ts index 764b53bf..a4ba05a0 100644 --- a/webapp/src/crypto/seal.ts +++ b/webapp/src/crypto/seal.ts @@ -1,15 +1,21 @@ -// The order's name and links, sealed under a key from the owner code, so the code alone restores the order in another browser. +// The order's name, links, payment method and agreed terms, sealed under a key from the owner code, so the code alone restores the order in another browser. import { hmac } from "@noble/hashes/hmac" import { sha256 } from "@noble/hashes/sha2" import { utf8ToBytes } from "@noble/hashes/utils" +import type { OrderRecord } from "../store.ts" import { base64url, fromBase64url } from "./code.ts" const IV_BYTES = 12 +const METHODS: OrderRecord["method"][] = ["card", "btc", "xmr", "code"] + +const SIGNED_TERMS = /^(community\/)?[0-9a-f]{64}$/ interface SealedOrder { label: string contact: string channel: string + method?: OrderRecord["method"] + terms?: string } async function sealingKey(seed: Uint8Array, usage: KeyUsage): Promise { @@ -29,7 +35,8 @@ export async function unseal(seed: Uint8Array, sealed: string): Promise formatOwnerCode(crypto.getRandomValues(new Uint8Array(16))) +const wallets = new Map() + export function walletOf(code: string): Wallet | null { - const parsed = parseNameCode(code) - return parsed?.kind === "owner" ? walletFromEntropy(parsed.entropy) : null + if (!wallets.has(code)) { + const parsed = parseNameCode(code) + wallets.set(code, parsed?.kind === "owner" ? walletFromEntropy(parsed.entropy) : null) + } + return wallets.get(code)! } -function registrationOf(label: string, owner: Uint8Array, secret: Uint8Array, links: api.Links, chain: api.ChainInfo, duration: bigint): Registration { +export const forgetWallets = () => wallets.clear() + +function registrationOf(label: string, owner: Uint8Array, secret: Uint8Array, links: api.Links, duration: bigint): Registration { return { - label, tld: chain.tld, owner, duration, secret, resolver: fromHex(chain.resolver), + label, tld: SITE.tld, owner, duration, secret, resolver: fromHex(SITE.resolver), contactLink: links.contact || null, channelLink: links.channel || null, } } @@ -34,9 +41,7 @@ function registrationOf(label: string, owner: Uint8Array, secret: Uint8Array, li export interface Draft { label: string links: api.Links - chain: api.ChainInfo years: number - termStart: number ownerCode: string terms: string method: store.OrderRecord["method"] @@ -44,47 +49,54 @@ export interface Draft { export type Available = Extract & { community: api.Community | null } export type Quote = Available & { terms: api.Terms } -export const orderable = (a: Available): a is Quote => a.terms !== null +export const orderable = (a: Available): a is Quote => a.terms !== null && a.years === SITE.paidYears && (a.community === null || a.community.years === SITE.communityYears) export const availableOf = ({ found, community }: api.SearchAnswer): Available | null => found.type === "available" ? { ...found, community } : null -export const chainOf = (q: api.ChainInfo): api.ChainInfo => ({ resolver: q.resolver, sponsor: q.sponsor, chainId: q.chainId, tld: q.tld }) // The name's search answer as an order needs it, or null when it can no longer be ordered. export async function quoteOf(label: string): Promise { - const available = availableOf(await api.searchName(hex(labelHash(label)), label.length, (await namesSite()).chainId)) + const available = availableOf(await api.searchName(hex(labelHash(label)), label.length)) if (available === null) return null - if (!orderable(available)) throw new api.ApiError("terms_unavailable", 503, null, {}) + if (!orderable(available) || available.price !== heldPrice(label.length)) throw new api.ApiError("terms_unavailable", 503, null, {}) return available } // An order of a record's name and links again, as a new order of its code: a new commitment for the term from now. export const draftAgain = (record: store.OrderRecord, quote: Quote, terms: string, method: api.Method): Draft => - ({ label: record.label, links: { contact: record.contact, channel: record.channel }, chain: chainOf(readSite()), years: api.termYears(quote.community, quote.years), termStart: readSite().termStart, ownerCode: record.ownerCode, terms, method }) + ({ label: record.label, links: { contact: record.contact, channel: record.channel }, years: api.termYears(quote.community, quote.years), ownerCode: record.ownerCode, terms, method }) export type BuiltOrder = { request: api.SignedOrder; owner: string } +export class Unsignable extends Error {} + +const heldAcceptance = (a: api.Acceptance) => a.policy.toLowerCase() === SITE.namePolicy.toLowerCase() && api.heldTerms(a.termsHash, a.community) !== undefined +const agreedTo = (a: api.Acceptance, agreed: string | undefined) => a.termsHash === api.signedHash(agreed) && a.community === api.communityAgreed(agreed) + // The order and its owner's signature over it, which proves that the code's wallet placed it, with the signed registration // and terms acceptance the service registers with after payment. export async function orderRequest(draft: Draft): Promise { const wallet = walletOf(draft.ownerCode)! const timestamp = now() - const duration = durationFor(draft.years, draft.termStart, timestamp) - const r = registrationOf(draft.label, wallet.address, commitmentSecret(wallet.seed, draft.label), draft.links, draft.chain, duration) + const duration = durationFor(draft.years, SITE.termStart, timestamp) + const r = registrationOf(draft.label, wallet.address, commitmentSecret(wallet.seed, draft.label), draft.links, duration) const commitment = makeCommitment(r) - const sealed = await seal(wallet.seed, { label: draft.label, ...draft.links }) + const sealed = await seal(wallet.seed, { label: draft.label, ...draft.links, method: draft.method, terms: draft.terms }) const owner = checksumAddress(wallet.address) const order = { labelHash: hex(labelHash(draft.label)), length: draft.label.length, duration: Number(duration), owner, commitment: hex(commitment), sealed, terms: draft.terms } - const reveal = signedReveal(wallet, r, commitment, await api.signFor(order.labelHash, owner), draft.chain, draft.method) + const toSign = await api.signFor(order.labelHash, owner) + const acceptance = { ...toSign.acceptance, community: api.communityAgreed(draft.terms), termsHash: api.signedHash(draft.terms) ?? "" } + if (!heldAcceptance(toSign.acceptance) || !heldAcceptance(acceptance)) throw new Unsignable() + const reveal = signedReveal(wallet, r, commitment, { ...toSign, acceptance }, draft.method) const message = `simplex.domains order ${order.labelHash} ${order.length} ${order.duration} ${order.commitment} ${await sha256Hex(sealed)} ${order.terms} ${timestamp}` return { request: { ...order, timestamp, signature: hex(signDigest(wallet.privateKey, personalDigest(message))), reveal }, owner } } -function signedReveal(wallet: Wallet, r: Registration, commitment: Uint8Array, toSign: api.ToSignRead, chain: Pick, method: store.OrderRecord["method"]): api.RevealBody { +function signedReveal(wallet: Wallet, r: Registration, commitment: Uint8Array, toSign: api.ToSignRead, method: store.OrderRecord["method"]): api.RevealBody { const deadline = now() + REVEAL_DEADLINE_SECONDS - const digest = registerIntentDigest(BigInt(chain.chainId), fromHex(chain.sponsor), r, BigInt(DISPUTE_DAYS[method]), BigInt(toSign.intentNonce), BigInt(deadline)) + const digest = registerIntentDigest(BigInt(SITE.chainId), fromHex(SITE.sponsor), r, BigInt(DISPUTE_DAYS[method]), BigInt(toSign.intentNonce), BigInt(deadline)) const a = toSign.acceptance const acceptance = { termsHash: a.termsHash, nonce: a.nonce, - signature: hex(signDigest(wallet.privateKey, acceptTermsDigest(a.community, BigInt(chain.chainId), fromHex(a.policy), commitment, fromHex(a.termsHash), BigInt(a.nonce), BigInt(deadline)))), + signature: hex(signDigest(wallet.privateKey, acceptTermsDigest(a.community, BigInt(SITE.chainId), fromHex(SITE.namePolicy), commitment, fromHex(a.termsHash), BigInt(a.nonce), BigInt(deadline)))), } return { label: r.label, secret: hex(r.secret), records: { contact: r.contactLink, channel: r.channelLink }, @@ -92,27 +104,26 @@ function signedReveal(wallet: Wallet, r: Registration, commitment: Uint8Array, t } } -// what the order is worth -export const paidWith = (res: api.InvoiceView): { method: api.Method; paid: number } => ({ method: res.cryptoCurrency ?? "card", paid: res.registration.price }) +export const payeeOf = ({ address, addressProof }: api.InvoiceView): Pick => ({ payee: address === undefined ? undefined : { address, addressProof } }) export function recordFor(draft: Draft, built: BuiltOrder, method: store.OrderRecord["method"], paid: number, ids: { registrationId: string; invoiceId: string | null }): store.OrderRecord { return { ...ids, label: draft.label, ownerCode: draft.ownerCode, owner: built.owner, ...draft.links, method, paid, years: draft.years, - request: built.request, terms: draft.terms, tld: draft.chain.tld, createdAt: new Date(api.serviceNow()).toISOString(), + request: built.request, terms: draft.terms, tld: SITE.tld, createdAt: new Date(api.serviceNow()).toISOString(), } } -export async function revealFor(record: Pick, duration: number, toSign: api.ToSignRead): Promise { +export function revealFor(record: Pick, view: api.RegistrationView, toSign: api.ToSignRead, agreed: string | undefined): api.RevealBody { + if (view.duration !== record.request.duration || !heldAcceptance(toSign.acceptance) || !agreedTo(toSign.acceptance, agreed)) throw new Unsignable() const wallet = walletOf(record.ownerCode)! - const site = await namesSite() - const r = registrationOf(record.label, wallet.address, commitmentSecret(wallet.seed, record.label), record, site, BigInt(duration)) - return signedReveal(wallet, r, makeCommitment(r), toSign, site, record.method) + const r = registrationOf(record.label, wallet.address, commitmentSecret(wallet.seed, record.label), record, BigInt(record.request.duration)) + return signedReveal(wallet, r, makeCommitment(r), toSign, record.method) } -export async function revealOrder(view: api.RegistrationView, record: store.OrderRecord): Promise { +export async function revealOrder(view: api.RegistrationView, record: store.OrderRecord, agreed: string | undefined): Promise { const toSign = api.toSignOf(view) if (toSign?.type !== "read") throw new Error("the order's view has nothing read to sign") - await api.reveal(view.id, await revealFor(record, view.duration, toSign)) + await api.reveal(view.id, revealFor(record, view, toSign, agreed), orderSigner(record)) } async function sha256Hex(text: string): Promise { @@ -127,33 +138,28 @@ export async function selectName(record: store.OrderRecord, draft: Draft, built: const timestamp = now() const { labelHash: lh, length, duration, commitment, sealed } = built.request const message = `simplex.domains name ${record.registrationId} ${lh} ${length} ${duration} ${commitment} ${await sha256Hex(sealed)} ${terms} ${timestamp}` - const view = await api.selectName(record.registrationId, { labelHash: lh, length, duration, commitment, sealed, terms, timestamp, signature: hex(signDigest(wallet.privateKey, personalDigest(message))), reveal: built.request.reveal }, draft.chain.chainId) + const view = await api.selectName(record.registrationId, { labelHash: lh, length, duration, commitment, sealed, terms, timestamp, signature: hex(signDigest(wallet.privateKey, personalDigest(message))), reveal: built.request.reveal }) store.saveOrder({ ...record, label, ...links, paid: view.price, request: built.request, terms }) return view } type RestoreResult = { record: store.OrderRecord; view: api.RegistrationView } -// The order's name and links, unsealed with the code, after checking that they rebuild the order's commitment. -async function openOrder(wallet: Wallet, view: api.RegistrationView): Promise> { +// The order's name and links, and the payment and terms it agreed to once those are sealed too, unsealed with the code, after +// checking that they rebuild the order's commitment; an order sealed before its terms were takes the view's. +async function openOrder(wallet: Wallet, view: api.RegistrationView): Promise & Partial>> { const opened = await unseal(wallet.seed, view.sealed) if (!opened) throw new Error("the code does not open this order") - const r = registrationOf(opened.label, wallet.address, commitmentSecret(wallet.seed, opened.label), opened, await namesSite(), BigInt(view.duration)) + const r = registrationOf(opened.label, wallet.address, commitmentSecret(wallet.seed, opened.label), opened, BigInt(view.duration)) if (hex(makeCommitment(r)) !== view.commitment) throw new Error("the order's commitment does not match the code") - const request = { labelHash: view.labelHash, length: opened.label.length, duration: view.duration, owner: checksumAddress(wallet.address), commitment: view.commitment, sealed: view.sealed } - return { label: opened.label, contact: opened.contact, channel: opened.channel, request, terms: api.signedTermsOf(view.terms) } + const request = { labelHash: hex(labelHash(opened.label)), length: opened.label.length, duration: view.duration, owner: checksumAddress(wallet.address), commitment: view.commitment, sealed: view.sealed } + return { label: opened.label, contact: opened.contact, channel: opened.channel, request, terms: opened.terms ?? api.signedTermsOf(view.terms), ...opened.method ? { method: opened.method } : {} } } // A name selected for the order elsewhere (another browser, or a selection whose answer was lost) is read back from the -// service; other terms alone keep the commitment. +// service. export async function syncRecord(record: store.OrderRecord, view: api.RegistrationView): Promise { - if (view.commitment === record.request.commitment) { - const terms = api.signedTermsOf(view.terms) - if (terms === record.terms) return record - const synced = { ...record, terms } - store.saveOrder(synced) - return synced - } + if (view.commitment === record.request.commitment) return record try { const synced = { ...record, ...await openOrder(walletOf(record.ownerCode)!, view), paid: view.price } store.saveOrder(synced) @@ -174,13 +180,7 @@ async function findOrders(wallet: Wallet): Promise { const signature = hex(signDigest(wallet.privateKey, personalDigest(`simplex.domains find ${owner.toLowerCase()} ${timestamp}`))) return api.findRegistrations(owner, timestamp, signature) } - const clock = api.clockVersion() - try { - return (await ask()).registrations - } catch (e) { - if (e instanceof api.ApiError && e.code === "bad_request" && api.clockVersion() !== clock) return (await ask()).registrations - throw e - } + return (await api.signedOnce(ask)).registrations } export interface CodeOrder { code: string; name: string; order: Found } @@ -225,6 +225,26 @@ export async function ownOrderFor(ownerCode: string, nameHash: string): Promise< return chosen ? (await reopen(wallet, ownerCode, chosen)).record : null } +const notListing = new Map>() + +export async function orderOfCodes(id: string): Promise { + const asked = notListing.get(id) ?? new Set() + notListing.set(id, asked) + for (const code of new Set(store.orders().map((o) => o.ownerCode))) { + const wallet = walletOf(code) + if (!wallet || asked.has(code)) continue + const found = (await findOrders(wallet)).find((r) => r.invoiceId === id || r.registrationId === id) + if (!found) { + asked.add(code) + continue + } + const { record } = await reopen(wallet, code, found) + if (found.phase === "closed") await newerOrder(record) + return store.orderByRegistration(record.registrationId) ?? record + } + return null +} + // orders this tab found nothing newer for; find has its own rate limit, so each is asked once const nothingNewer = new Set() @@ -250,24 +270,27 @@ export async function newerOrder(record: store.OrderRecord): Promise { - const wallet = walletOf(record.ownerCode) - if (!wallet) return null - return (await findOrders(wallet)).find((r) => r.registrationId === registrationId)?.createdAt ?? null +const signerOf = (wallet: Wallet): api.OrderSigner => (id, action) => { + const timestamp = now() + return { timestamp, signature: hex(signDigest(wallet.privateKey, personalDigest(`simplex.domains order ${id} ${action} ${timestamp}`))) } } +export const orderSigner = ({ ownerCode }: Pick): api.OrderSigner => signerOf(walletOf(ownerCode)!) async function reopen(wallet: Wallet, code: string, chosen: Found): Promise { const owner = checksumAddress(wallet.address) - const invoice = chosen.invoiceId ? await api.readInvoice(chosen.invoiceId) : null - const view = invoice?.registration ?? await api.readRegistration(chosen.registrationId) + const sign = signerOf(wallet) + const invoice = chosen.invoiceId ? await api.readInvoice(chosen.invoiceId, sign) : null + const view = invoice?.registration ?? await api.readRegistration(chosen.registrationId, sign) const opened = await openOrder(wallet, view) // what only this browser knew about the order (a card in confirmation, a cancel, the prepaid code that paid) is kept const known = store.orderByRegistration(view.id) + const payeeKnown = known !== undefined && invoice !== null && known.invoiceId === invoice.invoiceId && known.payee !== undefined const record: store.OrderRecord = { ...known, registrationId: view.id, invoiceId: chosen.invoiceId, ownerCode: code, owner, ...opened, - method: known?.method ?? (view.payment.type === "invoice" ? view.payment.method : view.payment.type), paid: view.price, years: view.years, - tld: readSite().tld, createdAt: chosen.createdAt, + method: known?.method ?? opened.method ?? (view.payment.type === "invoice" ? view.payment.method : view.payment.type), paid: view.price, years: view.years, + tld: SITE.tld, createdAt: chosen.createdAt, + ...known && known.request.commitment === view.commitment ? { terms: known.terms } : {}, + ...invoice && !payeeKnown ? payeeOf(invoice) : {}, } store.saveOrder(record) return { record, view } @@ -277,13 +300,13 @@ export const KEYS = { contact: CONTACT_KEY, channel: CHANNEL_KEY } as const // One signed SetText per changed key, in one request the service relays as one transaction. The resolver takes an // owner's intents only in nonce order, so the second is signed with the nonce the first spends. -export async function saveLinks(record: store.OrderRecord, chain: { chainId: number; resolver: string; tld: string }, nonce: number, changes: Partial): Promise { +export async function saveLinks(record: store.OrderRecord, nonce: number, changes: Partial): Promise { const wallet = walletOf(record.ownerCode)! - const node = namehash(chain.tld, record.label) + const node = namehash(SITE.tld, record.label) const deadline = now() + EDIT_DEADLINE_SECONDS const edits = api.LINK_KINDS.filter((kind) => changes[kind] !== undefined).map((kind, i) => { const value = changes[kind]! - const digest = setTextDigest(BigInt(chain.chainId), fromHex(chain.resolver), node, KEYS[kind], value, BigInt(nonce + i), BigInt(deadline)) + const digest = setTextDigest(BigInt(SITE.chainId), fromHex(SITE.resolver), node, KEYS[kind], value, BigInt(nonce + i), BigInt(deadline)) return { key: kind, value, nonce: nonce + i, deadline, signature: hex(signDigest(wallet.privateKey, digest)) } }) const { tx } = await api.editRecords({ labelHash: hex(labelHash(record.label)), edits }) diff --git a/webapp/src/main.ts b/webapp/src/main.ts index 55dd09b0..46b76f38 100644 --- a/webapp/src/main.ts +++ b/webapp/src/main.ts @@ -1,5 +1,6 @@ // The router: one page per route, redrawn on navigation. -import { loadConfig } from "./config.ts" +import { readConfig } from "./config.ts" +import { el } from "./dom.ts" import { checkoutStepOf, EDIT_PATH, fromOrder, viewOf } from "./screens/routes.ts" import { checkoutPage } from "./views/checkout.ts" import { setUpChrome } from "./views/chrome.ts" @@ -25,41 +26,47 @@ function render(): void { } } -setRenderer(render) -// The worker keeps this build for opening offline, registered after load so it does not slow the first visit; the dev server has none. -// Its listener is added before the await below, as Chromium fires load without waiting for a module's top-level await. -if (import.meta.env.PROD && "serviceWorker" in navigator) { - addEventListener("load", () => { - // checked for updates past the HTTP cache, which could keep a returning reader on an old worker - navigator.serviceWorker.register("/sw.js", { updateViaCache: "none" }).catch((e: unknown) => console.warn("This page will not open offline:", e)) +async function start(): Promise { + setRenderer(render) + // The worker keeps this build for opening offline, registered after load so it does not slow the first visit; the dev server has none. + // Its listener is added before the await below, as Chromium fires load without waiting for a module's top-level await. + if (import.meta.env.PROD && "serviceWorker" in navigator) { + addEventListener("load", () => { + // checked for updates past the HTTP cache, which could keep a returning reader on an old worker + navigator.serviceWorker.register("/sw.js", { updateViaCache: "none" }).catch((e: unknown) => console.warn("This page will not open offline:", e)) + }) + } + const config = await readConfig() + setUpChrome() + window.addEventListener("popstate", (e) => { + if (historyMoved(e) && !reloadedForRoute()) render() + }) + // The second click of a double click is dropped everywhere: an action that redraws the page or opens a popup puts + // another control under the pointer, where it would land (a checkbox, a payment method, the popup's backdrop). + document.addEventListener("click", (e) => { + if (e.detail <= 1) return + e.preventDefault() + e.stopImmediatePropagation() + }, true) + document.addEventListener("keydown", (e) => { + if (e.key !== " " || !(e.target instanceof Element) || !e.target.matches('a[role="button"]')) return + e.preventDefault() + if (!e.repeat) (e.target as HTMLElement).click() }) + // A link from /?order=… to /#/… would load a new document, dropping what this page holds in memory, so its views switch in place. + document.addEventListener("click", (e) => { + const a = (e.target as Element | null)?.closest("a") + const href = a?.getAttribute("href") + if (!a || !href || a.target || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return + if (!/^\/(#|\?)/.test(href)) return + e.preventDefault() + go(href) + }) + followServedMode(config) + render() } -// The mode decides the first screen, so nothing between the header and the footer is drawn before it is known. -await loadConfig() -setUpChrome() -window.addEventListener("popstate", (e) => { - if (historyMoved(e) && !reloadedForRoute()) render() -}) -// The second click of a double click is dropped everywhere: an action that redraws the page or opens a popup puts -// another control under the pointer, where it would land (a checkbox, a payment method, the popup's backdrop). -document.addEventListener("click", (e) => { - if (e.detail <= 1) return - e.preventDefault() - e.stopImmediatePropagation() -}, true) -document.addEventListener("keydown", (e) => { - if (e.key !== " " || !(e.target instanceof Element) || !e.target.matches('a[role="button"]')) return - e.preventDefault() - if (!e.repeat) (e.target as HTMLElement).click() -}) -// A link from /?order=… to /#/… would load a new document, dropping what this page holds in memory, so its views switch in place. -document.addEventListener("click", (e) => { - const a = (e.target as Element | null)?.closest("a") - const href = a?.getAttribute("href") - if (!a || !href || a.target || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return - if (!/^\/(#|\?)/.test(href)) return - e.preventDefault() - go(href) -}) -render() -followServedMode() + +if (window.top !== window.self) { + document.body.replaceChildren(el("p", { class: "own-tab" }, "This page can be used only in its own tab. Please ", + el("a", { href: location.href, target: "_blank", rel: "noopener" }, "open it in a new tab"), ".")) +} else await start() diff --git a/webapp/src/mode.ts b/webapp/src/mode.ts index aae99f73..a9727958 100644 --- a/webapp/src/mode.ts +++ b/webapp/src/mode.ts @@ -1,11 +1,7 @@ -// Whether the service sells names, or registers them only with prepaid codes until the full launch. The same build -// serves both: the page reads the service's mode from GET /api/config before it draws (src/config.ts). -export type Mode = "open" | "codes" +// Whether the service sells names, or registers them only with prepaid codes until the full launch. +import { SITE } from "./config.ts" // the service's refusal of a payment in codes-only mode export const CODES_ONLY = "codes_only" -let mode: Mode = "open" -export const setPageMode = (served: Mode) => { mode = served } -export const pageMode = (): Mode => mode -export const codesOnly = () => mode === "codes" +export const codesOnly = () => SITE.codesOnly diff --git a/webapp/src/screens/checkout.ts b/webapp/src/screens/checkout.ts index 0ca6793e..391bb387 100644 --- a/webapp/src/screens/checkout.ts +++ b/webapp/src/screens/checkout.ts @@ -6,7 +6,7 @@ import type { CheckoutStep } from "./routes.ts" export const FALLBACK_METHOD: Record = { card: "btc", btc: "xmr", xmr: "btc" } -export type Refusal = "price-changed" | "too-many" | "failed" | "taken" | "unavailable" | "codes-only" | `link-${LinkKind}` +export type Refusal = "price-changed" | "too-many" | "failed" | "taken" | "unavailable" | "codes-only" | "downtime" | `link-${LinkKind}` export type CheckoutKind = CheckoutStep | `status:${Refusal}` export interface WaitingOrder { registrationId: string; invoiceId: string } @@ -28,7 +28,7 @@ export interface CheckoutState { } export type CheckoutEvent = - | { type: "opened"; step: CheckoutStep; checkout: Checkout; sending: boolean; waiting: WaitingOrder | null; hold: Hold | null } + | { type: "opened"; step: CheckoutStep; checkout: Checkout; sending: boolean; waiting: WaitingOrder | null; hold: Hold | null; downtime: boolean } | { type: "link-set"; kind: LinkKind; link: string } | { type: "saved"; saved: boolean } | { type: "agreed"; agreed: boolean } @@ -43,7 +43,7 @@ export type CheckoutEvent = | { type: "open-order-seen"; order: OpenOrder | null } | { type: "send-started" } | { type: "order-refused"; reason: "code"; error: string } - | { type: "order-refused"; reason: "method" | "failed" | "taken" | "unavailable" | "codes-only" | `link-${LinkKind}` } + | { type: "order-refused"; reason: "method" | "failed" | "taken" | "unavailable" | "codes-only" | "downtime" | `link-${LinkKind}` } | { type: "price-changed"; price: number } | { type: "terms-changed"; terms: Terms; community: Community | null } | { type: "hold-started"; until: number } @@ -79,7 +79,7 @@ export function reduce(s: CheckoutState, e: CheckoutEvent): CheckoutState { const change = changeOf(s, e) const checkout = change ? { ...s.checkout, ...change } : s.checkout switch (e.type) { - case "opened": return { ...s, step: e.step, checkout: e.checkout, sending: e.sending, busy: false, waiting: e.waiting, hold: e.hold, refusal: null } + case "opened": return { ...s, step: e.step, checkout: e.checkout, sending: e.sending, busy: false, waiting: e.waiting, hold: e.hold, refusal: e.downtime ? "downtime" : null } case "link-set": case "saved": case "agreed": diff --git a/webapp/src/screens/hold.ts b/webapp/src/screens/hold.ts index b67a238e..3812b16c 100644 --- a/webapp/src/screens/hold.ts +++ b/webapp/src/screens/hold.ts @@ -2,3 +2,4 @@ export interface Hold { until: number; lead: string } export const NO_LEAD = "" export const LIMITED_LEAD = "Too many attempts. Please " +export const PLEASE_LEAD = "Please " diff --git a/webapp/src/screens/names.ts b/webapp/src/screens/names.ts index 97b8abe6..d4177585 100644 --- a/webapp/src/screens/names.ts +++ b/webapp/src/screens/names.ts @@ -2,7 +2,7 @@ import { holdsPayment, type CodeState, type Found, type InvoiceView, type LateWa import { YEAR_S } from "../crypto/registration.ts" import { dateOf, dollars, methodName } from "../format.ts" import { type CodeRecord, type OrderRecord, orderUrl, type PendingCode } from "../store.ts" -import { type Hold, LIMITED_LEAD, NO_LEAD } from "./hold.ts" +import { type Hold, NO_LEAD, PLEASE_LEAD } from "./hold.ts" export interface RowSeen { view: RegistrationView; invoice: InvoiceView | null; answer?: SearchAnswer | null } export type CodeCheck = CodeState | "unchecked" @@ -375,7 +375,7 @@ function applyToForm(f: EditForm, e: EditEvent): EditForm { return { ...saved, saving: false, result: "saved", settled: Object.keys(changesOf(saved)).length === 0 } } case "save-unanswered": return { ...f, saving: false, unanswered: true, result: "unanswered", edits: e.counted ? spent(f.edits, e.at) : f.edits } - case "save-held": return { ...f, saving: false, result: null, hold: { until: e.until, lead: LIMITED_LEAD } } + case "save-held": return { ...f, saving: false, result: null, hold: { until: e.until, lead: PLEASE_LEAD } } // the edits line says when they return case "save-limited": return { ...f, saving: false, result: null, edits: { left: 0, nextAt: e.nextAt } } case "save-refused": { diff --git a/webapp/src/screens/order.ts b/webapp/src/screens/order.ts index e36d5f93..d60eaf09 100644 --- a/webapp/src/screens/order.ts +++ b/webapp/src/screens/order.ts @@ -1,4 +1,8 @@ -import { committedOf, type Community, type FailReason, type Found, holdsPayment, type InvoiceView, lapsedOf, paidLate, type RegistrationView, reversedOrder, type Terms, toSignOf } from "../api.ts" +import { + addressProven, committedOf, type Community, type FailReason, type Found, heldTerms, holdsPayment, invoiceMethod, type InvoiceView, lapsedOf, paidLate, type RegistrationView, reversedOrder, signedHash, + type Terms, toSignOf, +} from "../api.ts" +import { heldPrice, SITE } from "../config.ts" import type { IconName } from "../icons.ts" import type { CodeRefusal, OrderRecord } from "../store.ts" import { type Hold, NO_LEAD } from "./hold.ts" @@ -17,7 +21,7 @@ export const TX_STALL_MS = 180_000 const UNREAD_PACING_MS = [5_000, 15_000, 30_000] export const unreadDelay = (reads: number) => UNREAD_PACING_MS[Math.min(reads, UNREAD_PACING_MS.length - 1)] -export type OrderKind = "pay-crypto" | "pay-card" | "confirming" | "registering" | "registered" | "ended" | "taken" | "failed" | "not-on-device" +export type OrderKind = "pay-crypto" | "pay-card" | "confirming" | "registering" | "registered" | "ended" | "taken" | "failed" | "status:no-code" | "status:closed" | "status:card-unconfirmed" | "status:paid-by-invoice" | "status:unreadable" | "status:unknown-link" | "status:price-changed" export type ClosedCase = "paid-late" | "cancelled" | "received" | "expired" | "reversed" @@ -37,12 +41,14 @@ export interface OrderState { record: OrderRecord | null cardSubmittedAt: string | null cardFailed: boolean + cardMismatched: boolean reveal: Reveal | null busy: Action | null note: Note | null hold: Hold | null price: number | null gone: boolean + noCode: boolean codeRefused: boolean // the service said the order's code is unspent, which the failed page waits for before saying so codeKept: boolean @@ -53,17 +59,21 @@ export interface OrderState { nameStatus: Found["type"] | null // when this page first saw the stage, or the buyer ticked changed terms in it, on the service's clock since: { stage: string; at: number } | null + downtime: boolean } export type OrderEvent = - | { type: "answered"; seq: number; now: number; invoice: InvoiceView | null; view: RegistrationView; record: OrderRecord | null; cardSubmittedAt: string | null; nameStatus: Found["type"] | null } + | { type: "answered"; seq: number; now: number; invoice: InvoiceView | null; view: RegistrationView; record: OrderRecord | null; cardSubmittedAt: string | null; nameStatus: Found["type"] | null + downtime: boolean } | { type: "record-changed"; record: OrderRecord | null; cardSubmittedAt: string | null } | { type: "read-failed" } | { type: "not-found" } + | { type: "no-code" } | { type: "tick"; now: number } | { type: "card-started" } | { type: "card-submitted"; at: string } | { type: "card-failed" } + | { type: "card-mismatched" } | { type: "card-refused"; note: Note | null } | { type: "reveal-sent"; key: string } | { type: "reveal-refused"; key: string } @@ -88,7 +98,7 @@ export type OrderEvent = | { type: "hold-ended" } export function initialState(reference: string, hold: Hold | null, reveal: Reveal | null = null): OrderState { - return { reference, seq: 0, now: 0, invoice: null, view: null, record: null, cardSubmittedAt: null, cardFailed: false, reveal, busy: null, note: null, hold, price: null, gone: false, codeRefused: false, codeKept: false, codeCheckAt: null, ask: null, nameStatus: null, since: null } + return { reference, seq: 0, now: 0, invoice: null, view: null, record: null, cardSubmittedAt: null, cardFailed: false, cardMismatched: false, reveal, busy: null, note: null, hold, price: null, gone: false, noCode: false, codeRefused: false, codeKept: false, codeCheckAt: null, ask: null, nameStatus: null, since: null, downtime: false } } const stageOf = (view: RegistrationView) => `${view.id} ${view.phase.type}${view.phase.type === "committed" && view.label !== null ? " signed" : ""}` @@ -105,13 +115,15 @@ function apply(s: OrderState, e: OrderEvent): OrderState { // a reveal the view shows as stored is no longer sending, so one the service clears is signed again under the same key return { ...s, seq: e.seq, now: e.now, invoice: e.invoice, view: e.view, record: e.record, cardSubmittedAt: e.cardSubmittedAt, ask: askKept(s.ask, e.record?.label ?? e.view.label), nameStatus: e.nameStatus, since: sinceOf(s.since, e.view, e.now), reveal: e.view.label !== null && s.reveal ? { ...s.reveal, sending: false } : s.reveal, - busy: s.busy === "retry" && !lapsedOf(e.view) ? null : s.busy } + busy: s.busy === "retry" && !lapsedOf(e.view) ? null : s.busy, downtime: e.downtime, noCode: false, gone: false } case "record-changed": return { ...s, record: e.record, cardSubmittedAt: e.cardSubmittedAt, ask: askKept(s.ask, e.record?.label ?? null) } case "read-failed": return s case "not-found": return { ...s, gone: true } + case "no-code": return { ...s, noCode: true } case "tick": return { ...s, now: e.now } case "card-submitted": return { ...s, cardSubmittedAt: e.at } case "card-failed": return { ...s, cardFailed: true } + case "card-mismatched": return { ...s, cardMismatched: true } case "card-started": return start(s, "card") case "card-refused": return end(s, "card", { note: e.note }) // at a reveal, the ask is kept only for the changed terms whose acceptance the reveal includes @@ -193,10 +205,15 @@ export const unpaidOrClosed = (view: RegistrationView) => view.phase.type === "u export const coinOf = (invoice: InvoiceView) => invoice.cryptoCurrency === "btc" || invoice.cryptoCurrency === "xmr" ? invoice.cryptoCurrency : null +export const paymentChecked = ({ invoice, record, cardMismatched }: OrderState) => invoice === null || (!cardMismatched && record !== null + && invoice.currency === SITE.currency && addressProven(invoice) && invoiceMethod(invoice) === record.method && invoice.amount === heldPrice(record.label.length) + && (record.invoiceId !== invoice.invoiceId || record.payee === undefined || record.payee.address === invoice.address)) + // What the order's name costs; null for a code, which costs nothing. export const costOf = (view: RegistrationView, invoice: InvoiceView | null): number | null => invoice ? view.price : null export function screenOf(s: OrderState): OrderKind { + if (s.noCode) return "status:no-code" if (s.gone) return "status:unknown-link" if (s.price !== null) return "status:price-changed" const { invoice, view, record } = s @@ -208,7 +225,7 @@ export function screenOf(s: OrderState): OrderKind { if (view.phase.type === "ended") return "ended" if (view.phase.type === "taken") return "taken" if (view.phase.type === "failed") return "failed" - if (view.phase.type !== "registering" && view.label === null && !record) return "not-on-device" + if (view.phase.type !== "registering" && view.label === null && !record) return "status:no-code" return "registering" } @@ -258,9 +275,10 @@ export const revealKey = (view: RegistrationView) => { } // The terms of the name's kind on chain are not the ones the order signed, so the buyer agrees to them again before the reveal. -const termsChanged = ({ view }: OrderState) => { +const termsChanged = ({ view, record }: OrderState) => { const read = view && readToSign(view) - return !!read && read.acceptance.termsHash !== view.terms.termsHash + const signed = record ? signedHash(record.terms) : view?.terms.termsHash + return !!read && read.acceptance.termsHash !== signed && heldTerms(read.acceptance.termsHash, read.acceptance.community) !== undefined } // The buyer is asked for the changed terms, ticked or not. @@ -278,7 +296,7 @@ export function refusalsOf({ view, reveal }: OrderState): number { export function revealDue(s: OrderState): boolean { const { view, record, reveal } = s - if (view?.phase.type !== "committed" || view.label !== null || !readToSign(view) || !record) return false + if (view?.phase.type !== "committed" || view.label !== null || !readToSign(view) || !record || s.downtime) return false if (termsToAgree(s)) return false if (view.phase.revealAfter * 1000 > s.now) return false return !(reveal?.key === revealKey(view) && reveal.sending) && refusalsOf(s) < REVEAL_ATTEMPTS @@ -288,6 +306,7 @@ export function stalledAt(s: OrderState): number | null { const { view, since } = s if (!view || !since || screenOf(s) !== "registering" || refusalsOf(s) >= REVEAL_ATTEMPTS || (termsAskedAgain(s) && !ticked(s.ask!))) return null if (view.phase.type !== "committed" || view.label !== null) return since.at + TX_STALL_MS + if (s.downtime) return null return Math.max(since.at, view.phase.revealAfter * 1000) + REVEAL_ATTEMPTS * RETRY_MS + STALL_MARGIN_MS } diff --git a/webapp/src/screens/search.ts b/webapp/src/screens/search.ts index c4a5c84a..821ac885 100644 --- a/webapp/src/screens/search.ts +++ b/webapp/src/screens/search.ts @@ -28,14 +28,15 @@ export interface SearchState { hold: Hold | null paused: boolean ownOrder: string | null + downtime: boolean } export type SearchEvent = - | { type: "opened"; opening: Opening; name: string; order: OrderRecord | null; hold: Hold | null } + | { type: "opened"; opening: Opening; name: string; order: OrderRecord | null; hold: Hold | null; downtime: boolean } | { type: "typed"; text: string } // minLength: the least letters the tab's or the order's code covers, where only a code registers names | { type: "searched"; label: string; hold: Hold | null; minLength: number | null } - | { type: "answered"; seq: number; label: string; answer: SearchAnswer; mine: boolean; now: number } + | { type: "answered"; seq: number; label: string; answer: SearchAnswer; mine: boolean; now: number; downtime: boolean } | { type: "unanswered"; seq: number } | { type: "search-held"; seq: number; until: number } | { type: "hold-ended" } @@ -44,7 +45,7 @@ export type SearchEvent = export const initialSearch = (): SearchState => ({ opening: "plain", name: "", typed: "", searched: null, seq: 0, searching: null, answer: null, bad: false, - order: null, hold: null, paused: false, ownOrder: null, + order: null, hold: null, paused: false, ownOrder: null, downtime: false, }) // An available name this browser has an order for, under its TLD, is checked again rather than offered while the order is read. @@ -60,7 +61,7 @@ export const searchDue = (s: SearchState): boolean => !s.paused && s.name !== "" function opened(s: SearchState, e: Extract): SearchState { const typed = e.name === s.name ? s.typed : e.name - const next = { ...s, opening: e.opening, name: e.name, typed, order: e.order } + const next = { ...s, opening: e.opening, name: e.name, typed, order: e.order, downtime: e.downtime } const dropped = unsearched(next) ? { answer: null, searching: null, bad: false, seq: s.seq + 1 } : {} if (s.hold || e.hold === null) return { ...next, ...dropped } return { ...next, answer: null, searching: null, bad: false, seq: s.seq + 1, hold: e.hold, paused: true } @@ -81,7 +82,7 @@ function searched(s: SearchState, e: Extract) function answered(s: SearchState, e: Extract): SearchState { if (e.seq !== s.seq) return s const same = s.answer?.kind === "found" && s.answer.label === e.label - return { ...s, searching: null, answer: { kind: "found", label: e.label, answer: e.answer, mine: e.mine, now: e.now }, ownOrder: same ? s.ownOrder : null } + return { ...s, searching: null, answer: { kind: "found", label: e.label, answer: e.answer, mine: e.mine, now: e.now }, ownOrder: same ? s.ownOrder : null, downtime: e.downtime } } export function reduce(s: SearchState, e: SearchEvent): SearchState { diff --git a/webapp/src/session.ts b/webapp/src/session.ts index ac584348..47b534ee 100644 --- a/webapp/src/session.ts +++ b/webapp/src/session.ts @@ -1,5 +1,5 @@ // This tab's checkout in progress, which ends with the tab. -import type { ChainInfo, Community, Method, SignedOrder, Terms } from "./api.ts" +import type { Community, Method, SignedOrder, Terms } from "./api.ts" import type { CheckoutStep } from "./screens/routes.ts" export interface AppliedCode { @@ -10,11 +10,9 @@ export interface AppliedCode { export interface Checkout { label: string - // the search answer's price, for its years or a community name's own, and when the paid years start + // the search answer's price, for its years or a community name's own price: number years: number - termStart: number - chain: ChainInfo terms: Terms community: Community | null contact: string @@ -83,11 +81,11 @@ function write(key: string, value: unknown): void { export const scrolled = (): Record => read>(SCROLLED) ?? {} export const setScrolled = (at: number, y: number) => write(SCROLLED, { ...scrolled(), [at]: y }) -// a checkout without its name, chain, term or terms, or with the terms version an older page kept, is a leftover, not one to +// a checkout without its name or terms, or with the terms version an older page kept, is a leftover, not one to // continue; one kept without its step opens the review, which sends it on export function checkout(): Checkout | null { const c = read(CHECKOUT) - return c?.label && c.chain && typeof c.terms?.hash === "string" && typeof c.termStart === "number" ? { ...c, step: c.step ?? "review" } : null + return c?.label && typeof c.terms?.hash === "string" ? { ...c, step: c.step ?? "review" } : null } export const setCheckout = (c: Checkout | null) => write(CHECKOUT, c) diff --git a/webapp/src/store.ts b/webapp/src/store.ts index 73b07730..556af88f 100644 --- a/webapp/src/store.ts +++ b/webapp/src/store.ts @@ -1,7 +1,7 @@ // What this browser keeps: its orders with their owner codes, and its prepaid codes. // Storage can be missing or full; the page then keeps everything in memory and says so where it matters. -import type { Method } from "./api.ts" +import type { AddressProof, Method } from "./api.ts" export interface OrderRecord { registrationId: string @@ -28,8 +28,11 @@ export interface OrderRecord { // the link of the order that replaced this one with a new invoice; its old link leads there replacedBy?: string createdAt: string + payee?: Payee } +export interface Payee { address: string; addressProof?: AddressProof } + export type CodeRefusal = "code_used" | "code_invalid" | "code_expired" export const invoiceUrl = (invoiceId: string) => `/?order=${invoiceId}` diff --git a/webapp/src/stripe.ts b/webapp/src/stripe.ts index fd97fd69..ddb8f1c9 100644 --- a/webapp/src/stripe.ts +++ b/webapp/src/stripe.ts @@ -1,8 +1,9 @@ -// Stripe's Payment Element for card orders, as the badges webapp mounts it (apps/simplex-badge-service/web/src/stripe.ts). +// Stripe's Payment Element for card orders, as the badges webapp mounts it (apps/simplex-badge-service/web/src/stripe.ts), +// in the card page (card/), and the messages between that page and the names page. // Stripe.js must load from js.stripe.com and may not be bundled or self-hosted, so this is a script tag. const STRIPE_JS_URL = "https://js.stripe.com/dahlia/stripe.js" -const CONFIRM_FAILED = "The card was not accepted. Check the details and try again." +export const CONFIRM_FAILED = "The card was not accepted. Check the details and try again." // a form that neither loads nor fails, as on a stalled network, has failed once this long has gone by export const CARD_FORM_TIMEOUT_MS = 20_000 @@ -15,9 +16,11 @@ interface StripeElements { create(kind: "payment", options: { wallets: Record<"applePay" | "googlePay" | "link", "never"> }): PaymentElement update(options: { appearance: Appearance }): void } +interface PaymentIntent { id: string; amount: number; currency: string; livemode: boolean; payment_method_types: string[]; status?: string } interface StripeInstance { + retrievePaymentIntent(clientSecret: string): Promise<{ paymentIntent?: PaymentIntent; error?: { type?: string } }> elements(options: { clientSecret: string; appearance: Appearance }): StripeElements - confirmPayment(options: { elements: StripeElements; confirmParams: { return_url: string }; redirect: "if_required" }): Promise<{ paymentIntent?: { status?: string }; error?: { type?: string; message?: string } }> + confirmPayment(options: { elements: StripeElements; confirmParams: { return_url: string }; redirect: "if_required" }): Promise<{ paymentIntent?: { id?: string; status?: string }; error?: { type?: string; message?: string } }> } type StripeGlobal = (publishableKey: string) => StripeInstance interface Appearance { @@ -32,10 +35,6 @@ declare global { } } -let key = "" -export const setPublishableKey = (served: string) => { key = served } -export const publishableKey = (): string => key - let loading: Promise | null = null // Firefox holds a page's load event for a script added before it, so a Stripe that never answers would keep the page loading @@ -92,7 +91,7 @@ function appearance(dark: boolean): Appearance { } } -type ConfirmOutcome = { kind: "submitted" } | { kind: "invalid" } | { kind: "error"; message: string } +export type ConfirmOutcome = { kind: "submitted"; id: string } | { kind: "invalid" } | { kind: "error"; message: string } export type MountedCard = { confirm: () => Promise; destroy: () => void } // the page's theme: whether it is dark, and its changes, heard until the returned stop is called export interface Theme { @@ -100,9 +99,28 @@ export interface Theme { watch(follow: (dark: boolean) => void): () => void } -// The form once ready, or null when the script, the SDK or the form fails or is not ready within the bound. The form -// follows the page's theme in place, as mounting it again would lose what was typed. -export async function mountCard(key: string, clientSecret: string, target: HTMLElement, theme: Theme): Promise { +export type ToCard = + | { type: "mount"; clientSecret: string; amount: number; dark: boolean } + | { type: "theme"; dark: boolean } + | { type: "confirm" } +export type FromCard = + | { type: "mounted" } + | { type: "height"; px: number } + | { type: "paid"; id: string } + | { type: "invalid" } + | { type: "declined"; message: string } + | { type: "failed"; reason: "mismatched" | "unloaded" } + +export interface Expected { amount: number; currency: string; live: boolean } +export const MISMATCHED = "mismatched" + +const intentHeld = (pi: PaymentIntent | undefined, { amount, currency, live }: Expected) => + pi !== undefined && pi.amount === amount && pi.currency === currency && pi.livemode === live && pi.payment_method_types.length === 1 && pi.payment_method_types[0] === "card" + +// The form once ready; MISMATCHED when the PaymentIntent is not the one expected, or not of the key's account; null when +// the script, the SDK or the form fails or is not ready within the bound. The form follows the page's theme in place, as +// mounting it again would lose what was typed. +export async function mountCard(key: string, clientSecret: string, expected: Expected, target: HTMLElement, theme: Theme): Promise { let stalled: ReturnType | undefined const late = new Promise((done) => { stalled = setTimeout(done, CARD_FORM_TIMEOUT_MS, false) }) let unwatch: () => void = () => undefined @@ -110,6 +128,9 @@ export async function mountCard(key: string, clientSecret: string, target: HTMLE const stripe = await Promise.race([loadStripeJs(), late]) if (!stripe) return null const sdk = stripe(key) + const read = await Promise.race([sdk.retrievePaymentIntent(clientSecret), late]) + if (!read || (read.error && read.error.type !== "invalid_request_error")) return null + if (!intentHeld(read.paymentIntent, expected)) return MISMATCHED const elements = sdk.elements({ clientSecret, appearance: appearance(theme.dark()) }) unwatch = theme.watch((dark) => elements.update({ appearance: appearance(dark) })) const element = elements.create("payment", { wallets: { applePay: "never", googlePay: "never", link: "never" } }) @@ -129,7 +150,7 @@ export async function mountCard(key: string, clientSecret: string, target: HTMLE if (r.error?.type === "validation_error") return { kind: "invalid" } if (r.error) return { kind: "error", message: r.error.message ?? CONFIRM_FAILED } const status = r.paymentIntent?.status - return status === "succeeded" || status === "processing" ? { kind: "submitted" } : { kind: "error", message: CONFIRM_FAILED } + return status === "succeeded" || status === "processing" ? { kind: "submitted", id: r.paymentIntent?.id ?? "" } : { kind: "error", message: CONFIRM_FAILED } } catch { return { kind: "error", message: CONFIRM_FAILED } } diff --git a/webapp/src/styles.css b/webapp/src/styles.css index 8b4aed46..0d85d4a3 100644 --- a/webapp/src/styles.css +++ b/webapp/src/styles.css @@ -245,8 +245,8 @@ html.framed body > main:empty { min-height: calc(var(--step-h) + var(--screen-to .screen.step:not(:has(> .actions-row)) { grid-template-rows: auto minmax(0, 1fr); } /* the card page is as tall as its content, so Pay and what follows it stay under Stripe's form as the form grows */ .screen.step:has(> .screen-body > .stripe) { height: auto; grid-template-rows: auto; } -/* a step grows under its content to hold a name code's QR, shown under everything */ -.screen.step:has(> .screen-body > .code-qr svg) { height: auto; min-height: calc(var(--step-h) + var(--screen-top)); } +/* the name-is-yours screen grows under its content to hold a long name or a name code's QR, shown under everything */ +.screen.step:has(> .screen-body > .yours-edit) { height: auto; min-height: calc(var(--step-h) + var(--screen-top)); } .screen-head { display: grid; grid-template-columns: var(--back-w) minmax(0, 1fr) var(--back-w); row-gap: 10px; } .screen-head h1 { grid-area: 1 / 2; text-align: center; } /* Back's word 12 px under the heading's top, its tap area 40 px tall */ @@ -508,15 +508,9 @@ html:not(.theming) .notice.name-check { transition: background-color 200ms, bord with Stripe.js dahlia, 221-230 px tall on the 600 px column and 306-320 px on a phone's, in Chromium and Firefox. A phone's layout holds the phone's height; the column from 489 px is taken to draw as the 600 px one, unmeasured. A taller form, with more fields or error lines, grows the box. */ -.stripe:not(:has(> .label)) { min-height: 320px; } -@media (min-width: 521px) { .stripe:not(:has(> .label)) { min-height: 230px; } } -/* the development stand-in, framed as the form it stands in for */ -.stripe:has(> .label) { padding: 18px; border: 1px dashed var(--surface-line); } -.stripe .label { margin-bottom: 4px; font-size: var(--fs-small); letter-spacing: 0; text-transform: none; color: var(--warn-fg); } -.stripe .f { display: block; margin-top: 12px; } -.stripe .f span { display: block; font-size: 13px; font-weight: 700; color: var(--ink-soft); margin-bottom: 6px; } -.stripe .box { padding: 13px 14px; border-radius: 12px; border: 1px solid var(--surface-line); background: var(--surface); color: var(--ink-soft); font-weight: 600; } -.stripe .cols { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; } +.stripe { min-height: 320px; } +@media (min-width: 521px) { .stripe { min-height: 230px; } } +.stripe > .card-frame { display: block; width: 100%; height: 0; border: 0; } /* the stages as bars, the active one filling as its wait goes by; --done is the wait's share gone by, which the page sets each second */ .stages { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; list-style: none; } @@ -544,7 +538,9 @@ html:not(.theming) .notice.name-check { transition: background-color 200ms, bord .code-display .masked { color: var(--ink-soft); } .code-buttons { display: flex; gap: 6px; } .screen-body > .ref { text-align: center; } -.card.use { display: grid; gap: 12px; } +/* the name-is-yours screen tighter, so it fits a phone's window under a name of 25 wide letters with its name address */ +.screen-body:has(> .yours-edit) { --body-gap: 10px; } +.card.use { display: grid; gap: 12px; padding-block: 16px; } .card.use h2 { font: 700 19px/1.3 var(--body); } .card.use p { color: var(--ink-soft); } @@ -608,7 +604,9 @@ html:not(.theming) .notice.name-check { transition: background-color 200ms, bord .balance-row .main { flex-basis: 0; min-width: auto; } .row-code { flex-basis: 100%; display: grid; gap: 12px; } .row-code > .qr, .code-qr > .qr { justify-self: center; } -.code-qr { display: grid; } +.code-qr { display: grid; gap: 12px; } +.code-qr:empty { display: none; } +.name-address .mono { overflow-wrap: anywhere; } .danger-link { font-size: var(--fs-small); } /* Forget's question comes into view with room below it; its answers are an equal pair, side by side when each gets the 220 px that holds "Forget everything" */ @@ -719,8 +717,6 @@ a[aria-disabled="true"] { opacity: .6; cursor: default; } .screen:has(> .screen-body > .stripe) .lead { line-height: 1.3; } .screen-body:has(> .stripe) { gap: 6px; } .screen-body:has(> .stripe) > .name-check { padding-block: 5px; line-height: 1.4; } - /* the name-is-yours screen tighter, so Edit links fits its frame under a name of 63 m letters, the widest */ - .screen-body:has(> .yours-edit) { --body-gap: 12px; } /* a QR is for another device; a phone opens its wallet from the link under the address */ .qr-grid { grid-template-columns: minmax(0, 1fr); } .qr-grid > .qr { display: none; } diff --git a/webapp/src/views/checkout.ts b/webapp/src/views/checkout.ts index 473ab57f..2adc91e3 100644 --- a/webapp/src/views/checkout.ts +++ b/webapp/src/views/checkout.ts @@ -1,6 +1,7 @@ // The checkout's steps: the links the name opens, its name code, a community name's community terms, and Check your order // with how it pays, and Pay. import * as api from "../api.ts" +import { SITE } from "../config.ts" import { alertBox, announce, btn, codeDisplay, el, type Kid, line, link, nameText, setAction } from "../dom.ts" import * as flow from "../flow.ts" import { bonusDays, bonusHint, dateOf, dollars, freeDays, methodName, termEnd } from "../format.ts" @@ -21,15 +22,14 @@ import { asStep, type Builder, currentRoute, draw, focusOn, go, goFrom, isRedraw, isRoute, kept, keptLive, limitScreen, outcome, redirect, refresh, screen, searchLink, supportVia, whenLeaving, } from "./shell.ts" import { holdEnd, holdEnder, holdFrom, holding, holdNotice, tabHold } from "./hold.ts" +import { nameAddressLine } from "./name-address.ts" import { openedInstead, REFUSED_LINK, REPLACE_LINK } from "./order.ts" import { readOrder } from "./search.ts" -import { loadNextRouteAfresh } from "./served-mode.ts" +import { inDowntime, loadNextRouteAfresh, NEW_ORDERS_SOON } from "./served-mode.ts" import { CANT_SHOW, commitLink, communityCheck, NO_ORDERS, rowName, termsBox, termsChangedLine, termsText } from "./terms.ts" const CHECKOUT_NOTE = "checkout-note" const SAVED_LABEL = "I have saved my name code" -// the dApp that registers a name paid for in ETH -const DAPP_URL = "https://app.simplex.domains" // the service takes a signed order's timestamp within this many seconds; an older one is signed anew const SIGNED_WINDOW_S = 600 @@ -57,14 +57,14 @@ export function checkoutPage(asked: CheckoutStep): void { session.setCheckout({ ...stored, step, ownerCode: stored.ownerCode ?? (step === "code" ? flow.newOwnerCode() : null) }) const c = session.checkout()! // a name code that already has an order, as one ordered again, is no pending code - if (c.ownerCode && !store.orders().some((o) => o.ownerCode === c.ownerCode)) store.addPending({ ownerCode: c.ownerCode, label: c.label, tld: c.chain.tld, createdAt: new Date().toISOString() }) + if (c.ownerCode && !store.orders().some((o) => o.ownerCode === c.ownerCode)) store.addPending({ ownerCode: c.ownerCode, label: c.label, tld: SITE.tld, createdAt: new Date().toISOString() }) if (!isRedraw() || shown === null || state.checkout.label !== c.label) { state = initialState(c, step, codesOnly()) shown = null } pageRoute = currentRoute() // a wait met elsewhere in the tab holds this page's actions too - dispatch({ type: "opened", step, checkout: c, sending: session.isSending(c), waiting: waitingCardOrder(), hold: tabHold() }) + dispatch({ type: "opened", step, checkout: c, sending: session.isSending(c), waiting: waitingCardOrder(), hold: tabHold(), downtime: inDowntime() }) if (step !== "review" && step !== "community") return const reads = new AbortController() whenLeaving(() => reads.abort()) @@ -75,7 +75,7 @@ export function checkoutPage(asked: CheckoutStep): void { // the community terms' text for their step async function readTerms(c: session.Checkout, signal: AbortSignal): Promise { - const text = await api.termsText(c.terms, c.chain.chainId, signal).catch(() => null) + const text = await api.termsText(c.terms, signal).catch(() => null) if (!signal.aborted) dispatch({ type: "community-read", hash: c.terms.hash, text }) } @@ -110,10 +110,10 @@ const setLink = (kind: LinkKind, link: string) => { } // Follows an invoice, each answer once it moves on from the one seen, while `followed` returns true; an invoice the service forgot is null. -async function follow(invoiceId: string, signal: AbortSignal, followed: (seen: api.InvoiceView | null) => boolean, seen?: api.InvoiceView): Promise { +async function follow(invoiceId: string, sign: api.OrderSigner, signal: AbortSignal, followed: (seen: api.InvoiceView | null) => boolean, seen?: api.InvoiceView): Promise { while (!signal.aborted) { try { - seen = await api.readInvoice(invoiceId, seen && api.seenOf(seen), signal) + seen = await api.readInvoice(invoiceId, sign, seen && api.seenOf(seen), signal) } catch (e) { // the service forgets an unpaid invoice some time after it closes; other errors are waited out if (e instanceof api.ApiError && e.code === "not_found") return void followed(null) @@ -126,7 +126,10 @@ async function follow(invoiceId: string, signal: AbortSignal, followed: (seen: a } // The card order blocks a second one only while its invoice is open, so checkout follows it and opens up when it settles or closes. -const settleWaiting = (waiting: WaitingOrder, signal: AbortSignal) => follow(waiting.invoiceId, signal, (seen) => seen?.status === "open" || settled(waiting, signal)) +async function settleWaiting(waiting: WaitingOrder, signal: AbortSignal): Promise { + const record = store.orderByRegistration(waiting.registrationId) + if (record) await follow(waiting.invoiceId, flow.orderSigner(record), signal, (seen) => seen?.status === "open" || settled(waiting, signal)) +} function settled(waiting: WaitingOrder, signal: AbortSignal): false { store.updateOrder(waiting.registrationId, { cardSubmittedAt: undefined }) @@ -143,8 +146,9 @@ const unpaid = (i: api.InvoiceView | null): i is api.InvoiceView => i?.status == // An unpaid invoice this browser made is pointed at, not blocking a new order, and followed until paid or closed; only the newest few are asked. async function showOpenOrder(signal: AbortSignal): Promise { const recent = store.orders().filter((o) => o.invoiceId && !o.cancelled && !o.replacedBy).slice(0, OPEN_ORDER_LOOKBACK) - const invoices = await Promise.all(recent.map((o) => api.readInvoice(o.invoiceId!).catch(() => null))) - const open = invoices.find(unpaid) + const invoices = await Promise.all(recent.map((o) => api.readInvoice(o.invoiceId!, flow.orderSigner(o)).catch(() => null))) + const at = invoices.findIndex(unpaid) + const open = invoices[at] if (!open || signal.aborted) return const show = (seen: api.InvoiceView | null) => { const order = unpaid(seen) ? { invoiceId: open.invoiceId } : null @@ -152,7 +156,7 @@ async function showOpenOrder(signal: AbortSignal): Promise { return order !== null } show(open) - void follow(open.invoiceId, signal, show, open) + void follow(open.invoiceId, flow.orderSigner(recent[at]), signal, show, open) } const row = (what: string, value: Kid, cls?: string) => el("div", { class: `trow${cls ? ` ${cls}` : ""}` }, el("span", {}, what), el("span", {}, value)) @@ -178,14 +182,14 @@ function term(years: number, termStart: number, now: number): Kid { function orderCard(c: session.Checkout, codesOnly: boolean): HTMLElement { const y = years(c) const now = api.serviceNow() / 1000 - const name = `${c.label}.${c.chain.tld}` + const name = `${c.label}.${SITE.tld}` const chats = api.LINK_KINDS.filter((kind) => c[kind]).map((kind) => linkChat(c[kind], kind, name, `chat-${kind}`)) const side = chats.length ? el("span", { class: "chats" }, chats) : null return el("section", { class: "card order" }, - el("div", { class: "row" }, rowName(c.label, c.chain.tld, c.community, "community"), side), + el("div", { class: "row" }, rowName(c.label, SITE.tld, c.community, "community"), side), el("div", { class: "table" }, - row("Term", term(y, c.termStart, now)), - row("Registered until", dateOf(termEnd(y, c.termStart, now))), + row("Term", term(y, SITE.termStart, now)), + row("Registered until", dateOf(termEnd(y, SITE.termStart, now))), c.code || codesOnly || c.order?.method === "code" ? el("div", { class: "trow total" }, el("span", {}, "Free SimpleX name")) : row("Total", c.order?.paid === c.price ? "Paid" : dollars(c.price), "total"), c.code && y < c.code.years ? el("p", { class: "hint" }, `A community name is registered for ${y} years, not your code's ${c.code.years}.`) : null)) @@ -288,7 +292,7 @@ function payButton(s: CheckoutState, blocked: boolean): HTMLButtonElement { function agreement({ checkout: c, sending }: CheckoutState): HTMLElement | null { if (c.community) return null const agree = (agreed: boolean) => { if (!state.sending && !act({ type: "agreed", agreed })) refresh() } - return termsBox({ terms: c.terms, community: c.community, agreed: c.agreed, changed: c.termsChanged === true, label: c.label, tld: c.chain.tld, chainId: c.chain.chainId, disabled: sending }, agree, "pay") + return termsBox({ terms: c.terms, community: c.community, agreed: c.agreed, changed: c.termsChanged === true, label: c.label, disabled: sending }, agree, "pay") } function payNote(s: CheckoutState, blocked: boolean, signal: AbortSignal): HTMLElement { @@ -337,9 +341,10 @@ function buildCode(s: CheckoutState): HTMLElement { const c = s.checkout const box = el("input", { type: "checkbox", checked: c.saved, disabled: s.sending, "data-focus": "saved" }) box.addEventListener("change", () => { if (!state.sending && !act({ type: "saved", saved: box.checked })) refresh() }) - return screen({ title: "Save your name code", lead: ["It is the only key to ", nameText(c.label, c.chain.tld, "."), " If you lose it, it cannot be recovered."], back: checkoutUrl("links"), + return screen({ title: "Save your name code", lead: ["It is the only key to ", nameText(c.label, SITE.tld, "."), " If you lose it, it cannot be recovered."], back: checkoutUrl("links"), action: continueButton(() => go(checkoutUrl("review")), !c.saved) }, codeDisplay(c.ownerCode!, "owner-code", true), + nameAddressLine(c.ownerCode!), store.canPersist() ? el("p", { class: "note center" }, "It may be lost when the window is closed.") : alertBox("danger", "alert", "This code could not be saved in this browser", "Please save a copy now."), el("label", { class: "check" }, box, el("span", { class: "box" }), SAVED_LABEL)) @@ -353,12 +358,12 @@ function buildCommunity(s: CheckoutState): HTMLElement { const accept = (accepted: boolean) => { if (!state.sending && !act({ type: "accepted", accepted })) refresh() } const text = !read ? el("p", { class: "note center" }, "Loading the terms…") : read.text === null ? line("bad", "alert", CANT_SHOW) - : [termsText(read.text), commitLink(c.terms, c.chain.chainId)] - return screen({ title: "Community terms", lead: [nameText(c.label, c.chain.tld), " is a community name. Its owner accepts these conditions."], back: checkoutUrl("code"), + : [termsText(read.text), commitLink(c.terms)] + return screen({ title: "Community terms", lead: [nameText(c.label, SITE.tld), " is a community name. Its owner accepts these conditions."], back: checkoutUrl("code"), action: continueButton(() => go(checkoutUrl("review")), !c.accepted) }, c.termsChanged ? termsChangedLine("continue") : null, text, - communityCheck({ ...c, community, changed: false, tld: c.chain.tld, chainId: c.chain.chainId, disabled: s.sending || !read?.text }, accept, true)) + communityCheck({ ...c, community, changed: false, disabled: s.sending || !read?.text }, accept, true)) } function buildReview(s: CheckoutState, signal: AbortSignal): HTMLElement { @@ -366,7 +371,7 @@ function buildReview(s: CheckoutState, signal: AbortSignal): HTMLElement { const blocked = blockedBy(s) const paid = !(c.code || c.order || codeEntry(c, s.codesOnly) === "field") // the other way to pay ends the note under the methods - const eth = el("a", { class: "nowrap", href: DAPP_URL, target: "_blank", rel: "noopener" }, "Pay with ETH") + const eth = el("a", { class: "nowrap", href: SITE.appOrigin, target: "_blank", rel: "noopener" }, "Pay with ETH") return screen({ title: "Check your order", back: checkoutUrl(c.community ? "community" : "code"), action: payButton(s, blocked !== null), alt: removeLink(s) }, el("div", { class: "review" }, orderCard(c, s.codesOnly), !c.codeError ? null : c.order ? line("bad", "alert", c.codeError) : s.codesOnly ? line("bad", "alert", `${c.codeError} Enter another code.`) @@ -380,7 +385,7 @@ function buildReview(s: CheckoutState, signal: AbortSignal): HTMLElement { function buildPriceChanged({ checkout: c }: CheckoutState): HTMLElement { return outcome({ tone: "warn", icon: "alert", title: "The price changed", - text: ["The price of ", nameText(c.label, c.chain.tld), ` changed to ${dollars(c.price)}.`], + text: ["The price of ", nameText(c.label, SITE.tld), ` changed to ${dollars(c.price)}.`], action: btn("Search again", "", () => go(searchLink(c.label, c.order?.registrationId))) }) } @@ -390,7 +395,7 @@ function buildTooMany({ checkout: c, hold }: CheckoutState, signal: AbortSignal) } function buildTaken({ checkout: c }: CheckoutState): HTMLElement { - return outcome({ tone: "info", icon: "info", title: "This name is no longer available", text: [nameText(c.label, c.chain.tld), " is no longer available."], + return outcome({ tone: "info", icon: "info", title: "This name is no longer available", text: [nameText(c.label, SITE.tld), " is no longer available."], action: btn("Search another name", "", () => go(searchLink("", c.order?.registrationId))) }) } @@ -411,6 +416,11 @@ function buildUnavailable(s: CheckoutState): HTMLElement { action: retry, alt: link("Back", () => go(searchLink(s.checkout.label, s.checkout.order?.registrationId))) }) } +function buildDowntime({ checkout: c }: CheckoutState): HTMLElement { + return outcome({ tone: "info", icon: "clock", title: NEW_ORDERS_SOON, text: "Nothing was charged.", + action: btn("Search again", "", () => go(searchLink(c.label, c.order?.registrationId))) }) +} + // a page opened before the service took codes only; the code entered there registers the name searched again for free function buildCodesOnly(): HTMLElement { return outcome({ tone: "info", icon: "key", title: CODES_ONLY_TITLE, text: CODES_ONLY_LINE, action: btn("Enter a code", "", () => go(CODE_URL)) }) @@ -427,6 +437,7 @@ const BUILDERS: Record> = { "status:taken": buildTaken, "status:unavailable": buildUnavailable, "status:codes-only": buildCodesOnly, + "status:downtime": buildDowntime, "status:link-contact": buildRefusedLink("contact"), "status:link-channel": buildRefusedLink("channel"), } @@ -467,7 +478,7 @@ async function sendOrder(): Promise { } const method = c.method const chosen = c.code ? "code" : c.order?.method ?? method - const draft: flow.Draft = { label: c.label, links, chain: c.chain, years: years(c), termStart: c.termStart, ownerCode: c.ownerCode!, terms, method: chosen } + const draft: flow.Draft = { label: c.label, links, years: years(c), ownerCode: c.ownerCode!, terms, method: chosen } const of = JSON.stringify([draft, c.code?.display ?? method, c.price]) try { const fresh = c.sent?.of === of && api.serviceNow() / 1000 - c.sent.request.timestamp < SIGNED_WINDOW_S @@ -486,15 +497,14 @@ async function sendOrder(): Promise { return done(store.orderUrl(taken)) } if (c.code) { - const res = await api.registerWithCode(built.request, c.code.display, c.chain.chainId) + const res = await api.registerWithCode(built.request, c.code.display) // the code is the order's now, so this tab registers no other name with it session.dropActiveCode(c.code.display) store.saveOrder({ ...flow.recordFor(draft, built, "code", 0, { registrationId: res.registrationId, invoiceId: null }), years: c.code.years, prepaidCode: c.code.display }) return done(store.orderUrl({ invoiceId: null, registrationId: res.registrationId })) } - const res = await api.createOrder(built.request, method, c.price, c.chain.chainId) - const paidBy = flow.paidWith(res) - store.saveOrder({ ...flow.recordFor(draft, built, paidBy.method, paidBy.paid, { registrationId: res.registration.id, invoiceId: res.invoiceId }), years: c.years }) + const res = await api.createOrder(built.request, method, c.price) + store.saveOrder({ ...flow.recordFor(draft, built, method, res.registration.price, { registrationId: res.registration.id, invoiceId: res.invoiceId }), years: c.years, ...flow.payeeOf(res) }) done(store.orderUrl({ invoiceId: res.invoiceId, registrationId: res.registration.id })) } catch (e) { if (!(e instanceof api.ApiError && e.code === "order_exists")) throw e @@ -538,7 +548,8 @@ function orderError(e: unknown, c: session.Checkout): void { } if (code === "invalid_link" && e instanceof api.ApiError && (e.body.kind === "contact" || e.body.kind === "channel")) return void act({ type: "order-refused", reason: `link-${e.body.kind}` }) if (code === "provider_unavailable") return void act({ type: "order-refused", reason: "method" }) - if (code === "terms_unavailable") return void act({ type: "order-refused", reason: "unavailable" }) + if (code === "terms_unavailable" || e instanceof flow.Unsignable) return void act({ type: "order-refused", reason: "unavailable" }) + if (code === "downtime") return void act({ type: "order-refused", reason: "downtime" }) if (code === CODES_ONLY) { loadNextRouteAfresh() return dispatch({ type: "order-refused", reason: "codes-only" }) diff --git a/webapp/src/views/name-address.ts b/webapp/src/views/name-address.ts new file mode 100644 index 00000000..c72d947b --- /dev/null +++ b/webapp/src/views/name-address.ts @@ -0,0 +1,15 @@ +import { SITE } from "../config.ts" +import { checksumAddress } from "../crypto/wallet.ts" +import { el } from "../dom.ts" +import { walletOf } from "../flow.ts" + +const nameAddressOf = (code: string) => checksumAddress(walletOf(code)!.address) + +const nameAddressText = (code: string) => ["Your name address is public. Please include it in any support request. ", el("span", { class: "mono" }, nameAddressOf(code))] + +export const nameAddressLine = (code: string) => el("p", { class: "note name-address" }, ...nameAddressText(code)) + +export const nameAddressAndApp = (code: string) => + el("p", { class: "note" }, el("span", { class: "name-address" }, ...nameAddressText(code)), " ", el("span", { class: "app-names" }, "Please ", + el("a", { href: `${SITE.appOrigin}/${nameAddressOf(code)}`, target: "_blank", rel: "noopener" }, "open your names in the SimpleX Names app"), + " and check that this name is listed. If it is not, please contact support.")) diff --git a/webapp/src/views/names.ts b/webapp/src/views/names.ts index 165fc9ac..1aeee25e 100644 --- a/webapp/src/views/names.ts +++ b/webapp/src/views/names.ts @@ -1,6 +1,5 @@ // Your names: this browser's orders and codes, restoring an order with its name code, and editing a name's links. import * as api from "../api.ts" -import { namesSite, readSite } from "../config.ts" import { alertBox, announce, btn, chip, codeDisplay, copyButton, el, type Kid, nameCodeQr, nameText, nameTitle, reducedMotion, setAction, waitOut } from "../dom.ts" import * as flow from "../flow.ts" import { dateOf, dollars, SEP } from "../format.ts" @@ -10,6 +9,7 @@ import { initialRestore, lapsed, lateLine, ranOut, moneyReached, nameRows, ORDER_CHIP_WORDS, paidLine, type ListEvent, type ListState, NOT_SAVED, phaseChip, reduceEdit, reduceList, reduceRestore, REFUSALS, registrableAgain, ROW_CHIPS, rowsDrawn, unanswered, type RestoreEvent, type RestoreState, type RowSeen, type CodeCheck, screenOfEdit, type Stored, waitsToSign, } from "../screens/names.ts" +import { PLEASE_LEAD } from "../screens/hold.ts" import { checkoutUrl, CODE_URL, editUrl } from "../screens/routes.ts" import * as session from "../session.ts" import type { AppliedCode } from "../session.ts" @@ -23,6 +23,7 @@ import { } from "./shell.ts" import { after } from "./effects.ts" import { holdEnd, holdEnder, holdFrom, holding, holdNotice, secondsLeft, tabHold } from "./hold.ts" +import { nameAddressAndApp, nameAddressLine } from "./name-address.ts" import { rowName } from "./terms.ts" const UNREAD_RETRY_MS = 5_000 @@ -94,7 +95,7 @@ function showList(): void { lastChecked = list.checked if (!isRoute(listRoute)) return draw("names", (signal) => buildNames(list, signal)) - readRows() + requestAnimationFrame(() => setTimeout(readRows)) } const answerList = (route: number, event: ListEvent) => { if (isRoute(route)) dispatchList(event) } @@ -149,11 +150,11 @@ async function readOrder(id: string, route: number): Promise { let view: api.RegistrationView let invoice: api.InvoiceView | null = null try { - await namesSite() + const sign = flow.orderSigner(o) if (o.invoiceId) { - invoice = await api.readInvoice(o.invoiceId) + invoice = await api.readInvoice(o.invoiceId, sign) view = invoice.registration - } else view = await api.readRegistration(o.registrationId) + } else view = await api.readRegistration(o.registrationId, sign) } catch (e) { // the service forgets an unpaid order some time after it closes if (e instanceof api.ApiError && e.code === "not_found" && await replaceWithNewer(o, route)) return @@ -168,7 +169,7 @@ async function readOrder(id: string, route: number): Promise { if (!isRoute(route)) return dispatchList({ type: "row-read", id, view, invoice, now: api.serviceNow() }) if (view.phase.type !== "registered") return - const answer = await api.searchName(view.labelHash, (view.label ?? synced.label).length, readSite().chainId).catch(() => null) + const answer = await api.searchName(synced.request.labelHash, synced.label.length).catch(() => null) answerList(route, { type: "row-answered", id, answer }) } @@ -202,6 +203,7 @@ function removePending(p: store.PendingCode): void { function forgetEverything(): void { store.forgetEverything() + flow.forgetWallets() session.setCheckout(null) dispatchList({ type: "forget-confirmed" }) focusHeading() @@ -302,13 +304,12 @@ export const NAME_CODE_NOTE = "You need this code to control your name and edit const rowCode = (code: string) => el("div", { class: "row-code" }, el("p", { class: "note" }, NAME_CODE_NOTE), - codeDisplay(code), nameCodeQr(code)) + codeDisplay(code), nameAddressAndApp(code), nameCodeQr(code)) function orderRow(o: store.OrderRecord, s: ListState): HTMLElement { const id = o.registrationId const seen = s.seen[id] - // another name may have been selected for the order since it was stored - const label = seen?.view.label ?? o.label + const label = o.label const tld = o.tld // a registered row takes its final shape at once; its name's answer, read after it, only takes Edit links away const registered = seen?.view.phase.type === "registered" @@ -374,10 +375,9 @@ const BALANCE_FROM: Record = { // Support refunds a balance. function balanceRow(b: BalanceRow, s: ListState): HTMLElement { const o = s.orders.find((r) => r.registrationId === b.id)! - const { view } = s.seen[b.id] - const acts = b.amount > 0 ? [small("Refund", `${b.id}-refund`, () => showRefund(o.invoiceId ?? o.registrationId, `${b.id}-refund`), true)] : [] + const acts = b.amount > 0 ? [small("Refund", `${b.id}-refund`, () => showRefund(o.invoiceId ?? o.registrationId, `${b.id}-refund`, o.invoiceId ? o.payee?.addressProof : undefined), true)] : [] const from = BALANCE_FROM[b.from] - const sub = ["From ", nameText(view.label ?? o.label, o.tld), from && [", ", el("span", { class: "nowrap" }, from)], + const sub = ["From ", nameText(o.label, o.tld), from && [", ", el("span", { class: "nowrap" }, from)], b.refunded ? `${SEP}refunded ${dollars(b.refunded)} by support` : null] const node = row(`balance-${b.id}`, el("b", { class: "price" }, dollars(b.amount)), sub, null, acts) if (from) node.classList.add("balance-row") @@ -457,7 +457,7 @@ async function addNameCode(verdict: Extract): Pr if (!isRoute(checkRoute)) return if (e instanceof api.ApiError && e.code === "not_found") return refuse("none") // the service asks for a wait before the next lookup; the button stays off until then, whatever is typed meanwhile - if (holdFrom(e)) return dispatchRestore({ type: "held", until: holdEnd(), lead: "Please " }) + if (holdFrom(e)) return dispatchRestore({ type: "held", until: holdEnd(), lead: PLEASE_LEAD }) refuse(e instanceof api.ApiError ? "unasked" : "other") } } @@ -484,7 +484,7 @@ function buildCheck(c: typeof check, signal: AbortSignal): HTMLElement { const note = c.restore.hold ? holdNotice(c.restore.hold, signal) : refusal ? alertBox("danger", "alert", refusal.title, refusal.text) : c.verdict?.kind === "prepaid" ? el("p", { class: "note center" }, "Search for a name; it shows as Free.") : null return screen({ title: "Check your code", lead: checkLead(), back: HOME, action: checkAction(c) }, - codeField(`${CHECK_CODE}-field`, "Code", heard), keptLive("check-note", undefined, note)) + codeField(`${CHECK_CODE}-field`, "Code", heard), c.verdict?.kind === "owner" ? nameAddressLine(c.verdict.found.code) : null, keptLive("check-note", undefined, note)) } let edit: EditState = initialEdit("", null) @@ -517,9 +517,10 @@ async function readEdit(route: number): Promise { let answer: api.SearchAnswer let record = stored try { - view = stored.invoiceId ? (await api.readInvoice(stored.invoiceId)).registration : await api.readRegistration(stored.registrationId) + const sign = flow.orderSigner(stored) + view = stored.invoiceId ? (await api.readInvoice(stored.invoiceId, sign)).registration : await api.readRegistration(stored.registrationId, sign) record = await flow.syncRecord(stored, view) ?? stored - answer = await api.searchName(record.request.labelHash, record.label.length, (await namesSite()).chainId) + answer = await api.searchName(record.request.labelHash, record.label.length) } catch (e) { // a forgotten unpaid order may have a newer one, found with the code const newer = e instanceof api.ApiError && e.code === "not_found" ? await flow.newerOrder(stored).catch(() => null) : null @@ -594,7 +595,7 @@ async function saveLinks(links: LinkFields): Promise { const { record, form } = edit if (!form?.saving) return try { - await flow.saveLinks(record!, readSite(), form.nonce, form.changes) + await flow.saveLinks(record!, form.nonce, form.changes) answerEdit(route, { type: "save-done", at: api.serviceSeconds() }) } catch (e) { // no answer is not a refusal: the edit may still be mined, and sending it again would pay for it twice @@ -607,7 +608,7 @@ async function saveLinks(links: LinkFields): Promise { if (holdFrom(e)) return answerEdit(route, { type: "save-held", until: holdEnd() }) // A refused edit may mean the nonce moved: an earlier save, from a page reloaded before it was mined, or from // another browser. The next save signs with the fresh one, and the page says why this one did not go. - const fresh = await api.searchName(record!.request.labelHash, record!.label.length, readSite().chainId).catch(() => null) + const fresh = await api.searchName(record!.request.labelHash, record!.label.length).catch(() => null) if (!isRoute(route)) return const now = edit.form! const own = fresh?.found.type === "registered" && fresh.found.records.type === "own" ? fresh.found.records : null diff --git a/webapp/src/views/order.ts b/webapp/src/views/order.ts index 4bb1d869..3579c000 100644 --- a/webapp/src/views/order.ts +++ b/webapp/src/views/order.ts @@ -1,15 +1,15 @@ // An order's page (?order=) or a code registration's (?registration=): payment, registration, and every ending. import * as api from "../api.ts" -import { namesSite, readSite } from "../config.ts" +import { SITE } from "../config.ts" import { alertBox, announce, btn, codeDisplay, copyButton, el, gradName, icon, type Kid, link, nameCodeQr, nameText, refill, setAction, type Tone, waitOut } from "../dom.ts" import * as flow from "../flow.ts" -import { clock, dateOf, dollars, methodName, SEP, shortAddress, timeOf } from "../format.ts" +import { clock, dateOf, dollars, methodName, SEP, timeOf } from "../format.ts" import { paymentUri, qrSvg } from "../qr.ts" import { closedBalance, type ClosedCase, closedCase, coinOf, costOf, failedAlert, failedLead, finished, supportCase, type SupportCase, initialState, type Note, type OrderEvent, type OrderKind, - type OrderState, readToSign, reduce, refusalsOf, RETRY_MS, retryDue, REVEAL_ATTEMPTS, revealDue, revealKey, screenOf, stalledAt, unpaidOrClosed, unreadDelay, wakeAt, askAgainDue, termsAskedAgain, termsToAgree, + type OrderState, paymentChecked, readToSign, reduce, refusalsOf, RETRY_MS, retryDue, REVEAL_ATTEMPTS, revealDue, revealKey, screenOf, stalledAt, unpaidOrClosed, unreadDelay, wakeAt, askAgainDue, termsAskedAgain, termsToAgree, } from "../screens/order.ts" -import { LIMITED_LEAD } from "../screens/hold.ts" +import { PLEASE_LEAD } from "../screens/hold.ts" import { termsToSign, ticked } from "../screens/terms.ts" import { CODES_ONLY, codesOnly } from "../mode.ts" import type { LinkKind } from "../names.ts" @@ -17,11 +17,13 @@ import { checkoutUrl, CODE_FROM_ORDER_URL, CODE_URL, editUrl } from "../screens/ import { hasLinks, linksAction } from "../screens/names.ts" import * as session from "../session.ts" import * as store from "../store.ts" -import { type MountedCard, mountCard, publishableKey } from "../stripe.ts" +import { mountCardFrame } from "../card-frame.ts" +import { nameAddressAndApp } from "./name-address.ts" +import { type MountedCard, MISMATCHED } from "../stripe.ts" import { CODES_ONLY_LINE, CODES_ONLY_TITLE } from "./codes.ts" import { NAME_CODE_NOTE, seenRegistered } from "./names.ts" import { holdEnd, holdEnder, holdFrom, holdNotice, tabHold } from "./hold.ts" -import { loadNextRouteAfresh, UNKEPT_TICKS } from "./served-mode.ts" +import { downtimeNow, inDowntime, loadNextRouteAfresh, NEW_ORDERS_SOON, PAYMENT_SOON, SIGNING_SOON, UNKEPT_TICKS } from "./served-mode.ts" import { NO_ORDERS, termsBox } from "./terms.ts" import { asStep, type Builder, contactSupport, currentRoute, draw, drawLoading, focusOn, go, historyPlace, isRedraw, isRoute, kept, keptLive, outcome, pageTheme, redirect, referenceLine, refresh, screen, @@ -84,7 +86,7 @@ function dispatch(event: OrderEvent): void { if (kind === "registered") seenRegistered(state.view!, state.invoice) if (revealDue(state)) reveal(state.view!, state.record!) else if (askAgainDue(state) && askingAgain !== opened) askAgain(state.record!) - else if (retryDue(state)) retryLapsed(state.view!) + else if (retryDue(state)) retryLapsed(state.view!, state.record!) wakeOnTime() } @@ -111,8 +113,9 @@ const cardSubmittedAt = (invoice: api.InvoiceView | null, record: store.OrderRec record?.cardSubmittedAt ?? (invoice ? store.cardSubmittedAt(invoice.invoiceId) : undefined) ?? null async function follow(mine: number, invoiceId: string | null, registrationId: string | null, signal: AbortSignal): Promise { - let invoice: api.InvoiceView | null = null - let view: api.RegistrationView | null = null + let invoice = null as api.InvoiceView | null + let view = null as api.RegistrationView | null + let downtime = inDowntime() let drawn = "" let drawnRecord = "" // siblings that could not be read are asked again even when the order's own answer has not changed @@ -125,16 +128,34 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st invoice = null view = null } + let linked = invoiceId ? store.orderByInvoice(invoiceId) : store.orderByRegistration(registrationId!) + while (!linked && isRoute(mine)) { + try { + linked = await flow.orderOfCodes(invoiceId ?? registrationId!) ?? undefined + break + } catch (e) { + const wait = api.retryDelay(e, RETRY_MS) + if (!isRoute(mine) || wait === null) break + dispatch({ type: "read-failed" }) + await sleep(wait) + } + } + if (!isRoute(mine)) return + if (!linked) return dispatch({ type: "no-code" }) + const sign = flow.orderSigner(linked) while (isRoute(mine)) { const asked = Date.now() const seq = ++reads try { - await namesSite() if (invoiceId) { - invoice = await api.readInvoice(invoiceId, invoice ? api.seenOf(invoice) : undefined, signal) - view = invoice.registration + const [read, down]: [api.InvoiceView, boolean] = await Promise.all([api.readInvoice(invoiceId, sign, invoice ? api.seenOf(invoice) : undefined, signal), downtimeNow()]) + invoice = read + view = read.registration + downtime = down } else { - view = await api.readRegistration(registrationId!, view?.version, signal) + const [read, down]: [api.RegistrationView, boolean] = await Promise.all([api.readRegistration(registrationId!, sign, view?.version, signal), downtimeNow()]) + view = read + downtime = down } } catch (e) { if (!isRoute(mine)) return @@ -171,7 +192,7 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st forget() return true } - const answered = JSON.stringify(invoice ?? view) + const answered = JSON.stringify([invoice ?? view, downtime]) if (answered === drawn && !again) { // one answered unchanged at once would otherwise poll in a tight loop if (!await paced() && Date.now() - asked < RETRY_MS) await sleep(RETRY_MS) @@ -184,15 +205,11 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st if (!isRoute(mine)) return record = synced ?? undefined } - // A late payment to a replaced invoice keeps its page, which says that it is kept as the order's balance. Only a browser without this - // order's record looks for its successor among its records, so two empty invoices never lead to each other. + // A late payment to a replaced invoice keeps its page, which says that it is kept as the order's balance. let unread: number | null = null try { const closedEmpty = invoice !== null && api.closedEmpty(invoice) - const successor = closedEmpty && !record ? await nextOrder(view, invoice!) : undefined - let replacement = successor && store.orderUrl(successor) - if (!replacement && !record && invoice) record = await adoptSibling(view, invoice) - if (!replacement && closedEmpty) replacement = record?.replacedBy + let replacement = closedEmpty ? record?.replacedBy : undefined // another browser may have made a newer invoice that this one never opened if (!replacement && closedEmpty && record) { const newer = await flow.newerOrder(record) @@ -201,7 +218,7 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st if (!isRoute(mine)) return if (replacement) return redirect(replacement) } catch (e) { - // a sibling's invoice could not be read; the page shows the order as this browser knows it and reads it again + // the code's newer orders could not be asked for; the page shows the order as this browser knows it and reads it again unread = api.retryDelay(e, RETRY_MS) } if (!isRoute(mine)) return @@ -212,6 +229,7 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st store.updateOrder(record.registrationId, { cardSubmittedAt: undefined }) record = { ...record, cardSubmittedAt: undefined } } + if (invoice?.address !== undefined && record?.invoiceId === invoice.invoiceId && record.payee === undefined) store.updateOrder(record.registrationId, flow.payeeOf(invoice)) record = (record && store.orderByRegistration(record.registrationId)) ?? record const recorded = JSON.stringify(record ?? null) if (answered !== drawn || recorded !== drawnRecord) { @@ -221,7 +239,7 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st status = await statusNow(view, record ?? null) if (!isRoute(mine)) return } - dispatch({ type: "answered", seq, now: api.serviceNow(), invoice, view, record: record ?? null, cardSubmittedAt: cardSubmittedAt(invoice, record), nameStatus: status ?? null }) + dispatch({ type: "answered", seq, now: api.serviceNow(), invoice, view, record: record ?? null, cardSubmittedAt: cardSubmittedAt(invoice, record), nameStatus: status ?? null, downtime }) } // A failed order is drawn before its code is checked, saying nothing of the code until the check answers; a rate // limit is waited out, counting down, as often as it is met. @@ -259,61 +277,17 @@ async function follow(mine: number, invoiceId: string | null, registrationId: st async function statusNow(view: api.RegistrationView, record: store.OrderRecord | null): Promise { const label = labelOf(view, record) if (label === null) return null - const answer = await api.searchName(view.labelHash, label.length, readSite().chainId).catch(() => null) + const answer = await api.searchName(record?.request.labelHash ?? view.labelHash, label.length).catch(() => null) return answer?.found.type ?? null } -// Another order of the same buyer: one of this commitment, or of the code's wallet once another name was selected for it. -const siblingOf = (view: api.RegistrationView) => (o: store.OrderRecord) => o.registrationId !== view.id && - (o.request.commitment === view.commitment || o.owner.toLowerCase() === view.owner.toLowerCase()) - -// The same order with a later invoice. Only an invoice that closes later can have replaced this one; expiry times are -// whole seconds, so a tie counts. -async function nextOrder(view: api.RegistrationView, invoice: api.InvoiceView): Promise { - const candidates = store.orders().filter((o) => o.invoiceId && !o.replacedBy && siblingOf(view)(o)) - for (const o of candidates) { - // a sibling the service has forgotten replaced nothing; any other failure leaves the answer unknown - const other = await api.readInvoice(o.invoiceId!).catch((e) => { if (e instanceof api.ApiError && e.code === "not_found") return null; throw e }) - if (other && Date.parse(other.expiresAt) >= Date.parse(invoice.expiresAt)) return o - } - return undefined -} - -// A browser holding the code of another invoice of this order holds this one too: another browser may have made a newer -// invoice, or money may have reached an older one late. The code reopens the name when another name was selected for the order. -async function adoptSibling(view: api.RegistrationView, invoice: api.InvoiceView): Promise { - const sibling = store.orders().find(siblingOf(view)) - if (!sibling) return undefined - const closed = invoice.status !== "open" && unpaidOrClosed(view) - const next = closed ? await nextOrder(view, invoice) : undefined - const record: store.OrderRecord = { ...sibling, registrationId: view.id, invoiceId: invoice.invoiceId, - method: invoice.cryptoCurrency ?? "card", paid: view.price, - cancelled: false, cardSubmittedAt: undefined, prepaidCode: undefined, replacedBy: next && store.orderUrl(next), - // a replaced invoice came just before its replacement; otherwise the code asks the service when the order was made, - // which a later search for a newer order compares against - createdAt: next ? new Date(Date.parse(next.createdAt) - 1).toISOString() : await flow.createdAtOf(sibling, view.id).catch(() => null) ?? new Date(api.serviceNow()).toISOString() } - const adopted = await flow.syncRecord(record, view) - if (adopted === record) store.saveOrder(record) - if (adopted && !adopted.replacedBy) await replaceOlder(view, invoice) - return adopted ?? undefined -} - -// The older invoices of an order adopted here were replaced by it, as if this browser had asked for the new invoice. -async function replaceOlder(view: api.RegistrationView, invoice: api.InvoiceView): Promise { - for (const o of store.orders().filter((r) => r.invoiceId && !r.replacedBy && siblingOf(view)(r))) { - const old = await api.readInvoice(o.invoiceId!).catch(() => null) - if (old && old.status !== "open" && unpaidOrClosed(old.registration) && Date.parse(old.expiresAt) <= Date.parse(invoice.expiresAt)) { - store.updateOrder(o.registrationId, { replacedBy: store.orderUrl({ invoiceId: invoice.invoiceId, registrationId: view.id }) }) - } - } -} - function reveal(view: api.RegistrationView, record: store.OrderRecord): void { const key = revealKey(view) const reference = state.reference + const agreed = termsAskedAgain(state) ? api.currentTerms(state.ask!) : record.terms dispatch({ type: "reveal-sent", key }) - flow.revealOrder(view, record).catch((e) => { - const refused = e instanceof api.ApiError && e.code === "bad_request" + flow.revealOrder(view, record, agreed).then(() => keepAgreed(record, agreed), (e) => { + const refused = e instanceof flow.Unsignable || (e instanceof api.ApiError && (e.code === "bad_request" || e.code === "not_found")) setTimeout(() => { dispatch({ type: refused ? "reveal-refused" : "reveal-failed", key }) if (isRoute(pageRoute) && state.reference === reference) refresh() @@ -321,10 +295,14 @@ function reveal(view: api.RegistrationView, record: store.OrderRecord): void { }) } -function retryLapsed(view: api.RegistrationView): void { +const keepAgreed = (record: store.OrderRecord, agreed: string | undefined) => { + if (agreed !== record.terms) store.updateOrder(record.registrationId, { terms: agreed }) +} + +function retryLapsed(view: api.RegistrationView, record: store.OrderRecord): void { const gen = opened dispatch({ type: "retry-started" }) - api.retry(view.id).then(() => reread(gen), (e) => { + api.retry(view.id, flow.orderSigner(record)).then(() => reread(gen), (e) => { if (holdOn(e, "", gen)) return setTimeout(() => { answer(gen, { type: "retry-ended", note: null }) @@ -340,17 +318,14 @@ function askAgain(record: store.OrderRecord): void { const gen = opened askingAgain = gen const done = () => { if (askingAgain === gen) askingAgain = null } - // after a pause, a search that failed for now is made again, and after terms the service no longer has for the view's - // hash, the view is read again + // after a pause, a search that failed for now is made again const later = (delay: number, again: () => void) => setTimeout(() => { done(); again() }, delay) const tick = () => answer(gen, { type: "tick", now: api.serviceNow() }) - const { chainId } = readSite() - api.searchName(state.view!.labelHash, record.label.length, chainId).then(async (searched) => { - const terms = await api.currentTermsOf(readToSign(state.view!)!.acceptance.termsHash, chainId).catch(() => null) + api.searchName(record.request.labelHash, record.label.length).then((searched) => { if (!isOpen(gen) || !askAgainDue(state)) return done() - if (terms === null) return later(RETRY_MS, () => reread(gen)) done() - askTerms(gen, record.label, { terms, community: searched.community }, true) + const { acceptance } = readToSign(state.view!)! + askTerms(gen, record.label, { terms: api.heldTerms(acceptance.termsHash, acceptance.community)!, community: searched.community }, true) // the notice is focused only while the focus is on the page, not in the header, the footer or a dialog const active = document.activeElement if (active === document.body || active?.closest("body > main")) focusOn("reveal") @@ -390,7 +365,7 @@ function buildPaidByInvoice({ view, record }: OrderState): HTMLElement { } // a browser without the order's record learns the name only once it is revealed on chain -const labelOf = (view: api.RegistrationView, record: store.OrderRecord | null) => view.label ?? record?.label ?? null +const labelOf = (view: api.RegistrationView, record: store.OrderRecord | null) => record?.label ?? view.label ?? null const UNKNOWN_NAME = "The name shows once it is registered" // what the order is for and what it cost, after its name where the screen has not said it already @@ -404,7 +379,7 @@ function termLine({ view, invoice }: OrderState): Kid[] { // the order in one line, the lead of each screen that pays or registers it function orderLine(s: OrderState): Kid[] { const label = labelOf(s.view!, s.record) - return [label ? nameText(label, readSite().tld) : UNKNOWN_NAME, SEP, ...termLine(s)] + return [label ? nameText(label, SITE.tld) : UNKNOWN_NAME, SEP, ...termLine(s)] } const TICKER: Record<"btc" | "xmr", string> = { btc: "BTC", xmr: "XMR" } @@ -450,14 +425,14 @@ function watchName(s: OrderState): void { const invoiceId = s.invoice!.invoiceId if (nameWatch?.invoiceId === invoiceId) return stopWatchingName() - const { labelHash } = s.view! + const labelHash = s.record?.request.labelHash ?? s.view!.labelHash const { length } = labelOf(s.view!, s.record)! const watch: NonNullable = { invoiceId } nameWatch = watch const check = async () => { let next = NAME_CHECK_MS try { - const answer = await api.searchName(labelHash, length, readSite().chainId) + const answer = await api.searchName(labelHash, length) if (nameWatch !== watch) return nameCheck = { invoiceId, taken: answer.found.type === "registered" || answer.found.type === "taken", at: Date.now() } showNameCheck() @@ -574,13 +549,23 @@ function cancelLink(s: OrderState): HTMLAnchorElement { return cancel } +const UNCHECKED_DETAILS = "Sorry, the payment details of this order could not be checked, so they are not shown. Please contact support with the order reference." +const proofOf = ({ record, invoice }: Pick) => invoice !== null && record?.invoiceId === invoice.invoiceId ? record.payee?.addressProof : undefined + +const withheld = (s: OrderState, title: string, alt: HTMLElement | null) => screen({ title, lead: orderLine(s), alt }, + paymentChecked(s) ? alertBox("info", "clock", null, `${PAYMENT_SOON}.`) : alertBox("danger", "alert", null, UNCHECKED_DETAILS), referenceLine(s.invoice!.invoiceId, proofOf(s)), actionNote(s, null)) + function buildPayCrypto(s: OrderState, signal: AbortSignal): HTMLElement { const inv = s.invoice! const coin = coinOf(inv)! const partial = Number(inv.cryptoAmountPaid ?? "0") > 0 + holdEnds(signal)(s.hold !== null) + if (s.downtime || !paymentChecked(s)) { + payDetails = null + return withheld(s, `Pay with ${methodName(coin)}`, partial || !s.record ? null : cancelLink(s)) + } const due = partial ? inv.cryptoAmountDue! : inv.cryptoAmount! const uri = paymentUri(coin, inv.address!, due) - holdEnds(signal)(s.hold !== null) // the QR's link shows on a laptop only, as styles.css draws the phone's layout without the QR const qr = uri ? el("div", { class: "qr" }, qrSvg(uri, `${methodName(coin)} payment`), el("a", { href: paymentUri(coin, inv.address!, due, true)! }, WALLET)) : null // labels in sentence case, as their copy buttons say them; the label style draws them in capitals @@ -610,8 +595,6 @@ let card: MountedCard | null = null let cardIn: HTMLElement | null = null let cardMounts = 0 let payButton: HTMLButtonElement | null = null -// without a Stripe key in development, Pay does what a submitted card does; the mock's controls settle it -const STAND_IN: MountedCard = { confirm: async () => ({ kind: "submitted" }), destroy: () => undefined } function dropCard(): void { cardMounts += 1 @@ -625,14 +608,9 @@ function dropCard(): void { function mountInto(form: HTMLElement, invoice: api.InvoiceView): void { const mine = ++cardMounts cardIn = form - const key = publishableKey() - if (!key && import.meta.env.DEV) { - cardStandIn(form) - card = STAND_IN - return - } - void mountCard(key, invoice.clientSecret ?? "", form, pageTheme).then((mounted) => { - if (mine !== cardMounts) return mounted?.destroy() + void mountCardFrame(invoice.clientSecret ?? "", invoice.amount, form, pageTheme).then((mounted) => { + if (mine !== cardMounts) return mounted !== null && mounted !== MISMATCHED ? mounted.destroy() : undefined + if (mounted === MISMATCHED) return dispatch({ type: "card-mismatched" }) if (!mounted) return dispatch({ type: "card-failed" }) card = mounted showCard() @@ -640,7 +618,7 @@ function mountInto(form: HTMLElement, invoice: api.InvoiceView): void { } const cardStays = (before: OrderState, kind: OrderKind) => - payButton !== null && kind === "pay-card" && screenOf(before) === "pay-card" && before.invoice?.invoiceId === state.invoice?.invoiceId + payButton !== null && kind === "pay-card" && screenOf(before) === "pay-card" && before.invoice?.invoiceId === state.invoice?.invoiceId && paymentChecked(state) function showCard(): void { if (!payButton) return @@ -668,6 +646,7 @@ const STRIPE_NOTE = "The card form is provided by Stripe. Your card will be char function buildPayCard(s: OrderState): HTMLElement { const invoice = s.invoice! + if ((s.downtime && cardIn === null) || !paymentChecked(s)) return withheld(s, "Pay by card", s.record ? cancelLink(s) : null) const form = kept("stripe-form", () => el("div", { class: "stripe" })) if (cardIn !== form) mountInto(form, invoice) const notice = nameNote(s) @@ -679,12 +658,6 @@ function buildPayCard(s: OrderState): HTMLElement { return screen({ title: "Pay by card", lead: orderLine(s), action: payButton, alt }, notice, form) } -function cardStandIn(form: HTMLElement): void { - const f = (text: string, value: string) => el("label", { class: "f" }, el("span", {}, text), el("div", { class: "box" }, value)) - form.append(el("p", { class: "label" }, "Test card form: no Stripe key is set, so Pay simulates a payment."), - f("Card number", "4242 4242 4242 4242"), el("div", { class: "cols" }, f("Expiry", "12 / 30"), f("CVC", "123"), f("Country", "Portugal"))) -} - // what a browser without the order's record can do: take in the name code const withoutRecord = (cls: string, text = "Enter your name code") => btn(text, cls, () => go(CODE_FROM_ORDER_URL)) // in codes-only mode a prepaid code is the only way to a name: nothing here orders or pays again @@ -698,7 +671,7 @@ const partlyPaid = (invoice: api.InvoiceView) => Number(invoice.cryptoAmountPaid function buildClosed(s: OrderState, signal: AbortSignal): HTMLElement { const inv = s.invoice! const closed = closedCase(s)! - if (closed === "reversed") return outcome({ tone: "info", icon: "alert", title: CLOSED_TITLE, text: "The payment for this order was reversed, so the order is cancelled.", reference: inv.invoiceId, + if (closed === "reversed") return outcome({ tone: "info", icon: "alert", title: CLOSED_TITLE, text: "The payment for this order was reversed, so the order is cancelled.", reference: inv.invoiceId, proof: proofOf(s), action: btn("Search a name", "quiet", () => go(searchLink(""))) }) const [tone, text] = closedWords(closed, inv, s.view!) const kept = closedBalance(s) @@ -706,7 +679,7 @@ function buildClosed(s: OrderState, signal: AbortSignal): HTMLElement { const reorders = !codesOnly() && (kept === "offer" || ((closed === "received" || closed === "expired") && s.record !== null && !s.record.replacedBy)) holdEnds(signal)(s.hold !== null) const replaced = kept === "replaced" ? el("p", { class: "note" }, "What reached this invoice is kept as your balance.") : null - return outcome({ tone, icon: "alert", title: CLOSED_TITLE, text, reference: inv.invoiceId, + return outcome({ tone, icon: "alert", title: CLOSED_TITLE, text, reference: inv.invoiceId, proof: proofOf(s), extra: [replaced, actionNote(s, reorders ? signal : null)], agreement: reorders ? agreement(s, "reorder") : null, ...kept === "offer" ? balanceActions(s, newInvoiceButton(s, "", reorder)) : { action: closedAction(s, closed) } }) } @@ -717,7 +690,7 @@ function agreement({ ask, view, busy, reveal }: OrderState, focus: string): HTML const accept = (accepted: boolean) => dispatch({ type: "terms-accepted", accepted, now: api.serviceNow() }) // a reveal on its way has signed the ticked terms already const signing = reveal?.sending === true && reveal.key === revealKey(view!) - const box = termsBox({ ...ask, tld: readSite().tld, chainId: readSite().chainId, disabled: busy !== null || signing }, agree, focus, accept) + const box = termsBox({ ...ask, disabled: busy !== null || signing }, agree, focus, accept) box.setAttribute(UNKEPT_TICKS, "") return box } @@ -737,13 +710,13 @@ function termsOrAsk(gen: number, record: store.OrderRecord, signed: string | nul } // nothing is cancelled before the buyer has agreed to the terms the new invoice would sign -async function agreedFirst(gen: number, record: store.OrderRecord, invoice: api.InvoiceView): Promise { +async function agreedFirst(gen: number, record: store.OrderRecord): Promise { try { const quote = await flow.quoteOf(record.label) if (!quote) return true - return termsOrAsk(gen, record, api.signedTermsOf(invoice.registration.terms), quote) !== null + return termsOrAsk(gen, record, record.terms, quote) !== null } catch (e) { - if (!holdOn(e, LIMITED_LEAD, gen)) { + if (!holdOn(e, PLEASE_LEAD, gen)) { answer(gen, { type: "reorder-failed", note: termsUnavailable(e) ? NO_ORDERS_NOTE : warning("A new invoice was not created. Please try again in a moment.") }) } return false @@ -792,13 +765,13 @@ async function orderAgain(record: store.OrderRecord): Promise { try { quote = await flow.quoteOf(record.label) } catch (e) { - if (holdOn(e, LIMITED_LEAD, gen)) return + if (holdOn(e, PLEASE_LEAD, gen)) return return answer(gen, { type: "reorder-failed", note: termsUnavailable(e) ? NO_ORDERS_NOTE : warning("A new invoice was not created. Please try again in a moment.") }) } if (!isOpen(gen)) return if (!quote) return go(searchLink(record.label)) session.setCheckout({ - label: record.label, price: quote.price, years: quote.years, termStart: readSite().termStart, chain: flow.chainOf(readSite()), contact: record.contact, channel: record.channel, + label: record.label, price: quote.price, years: quote.years, contact: record.contact, channel: record.channel, terms: quote.terms, community: quote.community, method: record.method === "code" ? "btc" : record.method, code: null, ownerCode: record.ownerCode, saved: true, agreed: false, searchAt: historyPlace(), step: "review", }) @@ -845,29 +818,31 @@ async function reorderAfterCancel(method: api.Method = "card"): Promise { const gen = opened const invoice = state.invoice! const record = store.orderByInvoice(invoice.invoiceId) + if (!record) return dispatch({ type: "reorder-started" }) - if (record && !await agreedFirst(gen, record, invoice)) return - if (await cancelBeforeReorder(invoice, gen)) return newInvoice(invoice, record, gen, method) + if (state.downtime) return dispatch({ type: "reorder-failed", note: { tone: "warn", icon: "clock", title: null, text: `${NEW_ORDERS_SOON}. Nothing was charged.` } }) + if (!await agreedFirst(gen, record)) return + if (await cancelBeforeReorder(invoice, record, gen)) return newInvoice(invoice, record, gen, method) if (store.orderByInvoice(invoice.invoiceId)?.cancelled) reread(gen) } // The old invoice is cancelled before a new one is ordered; true when ordering again cannot charge twice. -async function cancelBeforeReorder(invoice: api.InvoiceView, gen: number): Promise { +async function cancelBeforeReorder(invoice: api.InvoiceView, record: store.OrderRecord, gen: number): Promise { const say = (text: string) => answer(gen, { type: "reorder-failed", note: warning(text) }) + const sign = flow.orderSigner(record) let after: api.InvoiceView try { - after = await api.cancelInvoice(invoice.invoiceId) - const record = store.orderByInvoice(invoice.invoiceId) - if (record && after.status !== "paid") store.updateOrder(record.registrationId, { cancelled: true }) + after = await api.cancelInvoice(invoice.invoiceId, sign) + if (after.status !== "paid") store.updateOrder(record.registrationId, { cancelled: true }) } catch (e) { const code = e instanceof api.ApiError ? e.code : "network" - if (holdOn(e, LIMITED_LEAD, gen)) return false + if (holdOn(e, PLEASE_LEAD, gen)) return false if (code !== "not_open") { say(code === "funded" ? "A payment was received, so the invoice cannot be cancelled." : "The invoice was not cancelled. Please try again in a moment.") return false } try { - after = await api.readInvoice(invoice.invoiceId) + after = await api.readInvoice(invoice.invoiceId, sign) } catch { say("The invoice could not be read now. Try again in a moment.") return false @@ -886,10 +861,11 @@ async function cancelInvoice(): Promise { if (state.busy || state.hold) return const gen = opened const { invoice, record } = state + if (!record) return dispatch({ type: "cancel-started" }) try { - const after = await api.cancelInvoice(invoice!.invoiceId) - if (record && after.status !== "paid") store.updateOrder(record.registrationId, { cancelled: true }) + const after = await api.cancelInvoice(invoice!.invoiceId, flow.orderSigner(record)) + if (after.status !== "paid") store.updateOrder(record.registrationId, { cancelled: true }) answer(gen, { type: "cancel-answered" }) reread(gen) } catch (e) { @@ -899,7 +875,7 @@ async function cancelInvoice(): Promise { return reread(gen) } if (e instanceof api.ApiError && e.code === "funded") return answer(gen, { type: "cancel-failed", note: warning("A payment was received, so the invoice cannot be cancelled.") }) - if (holdOn(e, LIMITED_LEAD, gen)) return + if (holdOn(e, PLEASE_LEAD, gen)) return answer(gen, { type: "cancel-failed", note: warning("The invoice was not cancelled. Please try again in a moment.") }) } } @@ -911,8 +887,8 @@ function buildConfirming(s: OrderState): HTMLElement { ? alertBox("info", "clock", confirmations(invoice.requiredConfirmations ?? 1), "Payment received. Waiting for network confirmations.") : alertBox("info", "clock", "Waiting for Stripe to\u00a0confirm", "Payment received. Waiting for Stripe, usually under a minute.") // a card Stripe has not confirmed can still be cancelled while nothing is paid, as an unpaid crypto invoice can - const cancel = !coin && !invoice.amountPaid ? cancelLink(s) : null - return screen({ title: coin ? "Confirming your payment" : "Paying by card", lead: orderLine(s), alt: cancel }, notice, referenceLine(invoice.invoiceId), actionNote(s, null)) + const cancel = !coin && !invoice.amountPaid && s.record ? cancelLink(s) : null + return screen({ title: coin ? "Confirming your payment" : "Paying by card", lead: orderLine(s), alt: cancel }, notice, referenceLine(invoice.invoiceId, proofOf(s)), actionNote(s, null)) } function enterCardAgain(): void { @@ -932,34 +908,34 @@ function reorder(): void { function buildPriceChanged({ record, invoice, price }: OrderState): HTMLElement { const { label } = record! - return outcome({ tone: "warn", icon: "alert", title: "The price changed", text: ["The price of ", nameText(label, readSite().tld), ` changed to ${dollars(price!)}.`], - action: btn("Search again", "", () => go(searchLink(label))), reference: invoice!.invoiceId }) + return outcome({ tone: "warn", icon: "alert", title: "The price changed", text: ["The price of ", nameText(label, SITE.tld), ` changed to ${dollars(price!)}.`], + action: btn("Search again", "", () => go(searchLink(label))), reference: invoice!.invoiceId, proof: proofOf({ record, invoice }) }) } -async function newInvoice(invoice: api.InvoiceView, record: store.OrderRecord | undefined, gen: number, method: api.Method = invoice.cryptoCurrency ?? "card"): Promise { - if (!isOpen(gen) || !record) return +async function newInvoice(invoice: api.InvoiceView, record: store.OrderRecord | undefined, gen: number, asked?: api.Method): Promise { + if (!isOpen(gen) || !record || record.method === "code") return + const method = asked ?? record.method try { // the invoice as it is now: one still open, or paid into a registration, is the order; one paid after it closed // registered nothing, so the name is ordered again and the late payment is kept as the old order's balance - const now = await api.readInvoice(invoice.invoiceId) + const now = await api.readInvoice(invoice.invoiceId, flow.orderSigner(record)) if (now.status === "open" || (now.status === "paid" && !unpaidOrClosed(now.registration))) { if (isOpen(gen)) go(store.invoiceUrl(invoice.invoiceId)) return } - // a new invoice is a new order of the same name code, at the price this one was made for + // a new invoice is a new order of the same name code, at the price the page holds for the name const quote = await flow.quoteOf(record.label) if (!quote) { if (isOpen(gen)) go(searchLink(record.label)) return } - const signed = api.signedTermsOf(now.registration.terms) - const terms = termsOrAsk(gen, record, signed, quote) + const terms = termsOrAsk(gen, record, record.terms, quote) if (terms === null) return const built = await flow.orderRequest(flow.draftAgain(record, quote, terms, method)) - const res = await api.createOrder(built.request, method, invoice.amount, readSite().chainId) + const res = await api.createOrder(built.request, method, quote.price) const next = store.orderUrl({ invoiceId: res.invoiceId, registrationId: res.registration.id }) // the old record is the stored owner code until the new one is stored too - store.saveOrder({ ...record, request: built.request, terms, registrationId: res.registration.id, invoiceId: res.invoiceId, ...flow.paidWith(res), cancelled: false, cardSubmittedAt: undefined, replacedBy: undefined, createdAt: new Date(api.serviceNow()).toISOString() }) + store.saveOrder({ ...record, request: built.request, terms, registrationId: res.registration.id, invoiceId: res.invoiceId, method, paid: res.registration.price, ...flow.payeeOf(res), cancelled: false, cardSubmittedAt: undefined, replacedBy: undefined, createdAt: new Date(api.serviceNow()).toISOString() }) // Your names lists the old order only while money it received needs its reference; its page leads to the new one if (res.registration.id !== record.registrationId) store.updateOrder(record.registrationId, { replacedBy: next }) if (isOpen(gen)) go(next) @@ -975,7 +951,8 @@ async function newInvoice(invoice: api.InvoiceView, record: store.OrderRecord | } if (e instanceof api.ApiError && e.code === "catalog_changed" && typeof e.body.price === "number") return dispatch({ type: "price-changed", price: e.body.price }) if (e instanceof api.TermsChanged) return askTerms(gen, record.label, e, true) - if (termsUnavailable(e)) return dispatch({ type: "reorder-failed", note: NO_ORDERS_NOTE }) + if (termsUnavailable(e) || e instanceof flow.Unsignable) return dispatch({ type: "reorder-failed", note: NO_ORDERS_NOTE }) + if (e instanceof api.ApiError && e.code === "downtime") return dispatch({ type: "reorder-failed", note: { tone: "warn", icon: "clock", title: null, text: `${NEW_ORDERS_SOON}. Nothing was charged.` } }) if (e instanceof api.ApiError && e.code === CODES_ONLY) { loadNextRouteAfresh() return dispatch({ type: "reorder-failed", note: CODES_ONLY_NOTE }) @@ -984,7 +961,7 @@ async function newInvoice(invoice: api.InvoiceView, record: store.OrderRecord | return dispatch({ type: "reorder-failed", note: { tone: "warn", icon: "alert", title: `${methodName(method)} is unavailable right now`, text: "Please ", link: { text: "order the name again", href: searchLink(record.label), after: " to pay another way." } } }) } - if (holdOn(e, LIMITED_LEAD, gen)) return + if (holdOn(e, PLEASE_LEAD, gen)) return dispatch({ type: "reorder-failed", note: { tone: "warn", icon: "alert", title: "The order could not be placed", text: "A new invoice was not created. Please try again in a moment." } }) } } @@ -1016,7 +993,7 @@ const stagesOf = (view: api.RegistrationView): StageState[] => view.phase.type = function headingOf({ view, record }: OrderState): Kid { const label = labelOf(view!, record) - return label ? ["Registering ", gradName(label, readSite().tld)] : "Registering the name" + return label ? ["Registering ", gradName(label, SITE.tld)] : "Registering the name" } function leadOf(s: OrderState): Kid { @@ -1056,7 +1033,7 @@ function buildRegistering(s: OrderState, signal: AbortSignal): HTMLElement { if (stalled !== null && api.serviceNow() >= stalled) return say(note, STALL_NOTE) if (view.phase.type !== "committed") return say(note, WAIT_NOTE) waitsSeen.delete(view.id) - if (view.label === null && (refused || termsToAgree(s))) say(note, "The registration is not signed yet.") + if (view.label === null && (refused || termsToAgree(s) || s.downtime)) say(note, "The registration is not signed yet.") else say(note, WAIT_NOTE) } onTheSecond(() => waitLeft(view), tick, signal) @@ -1065,7 +1042,7 @@ function buildRegistering(s: OrderState, signal: AbortSignal): HTMLElement { // the note keeps the height of its longest words, so the page keeps still as they change el("div", { class: "countdown" }, clockNode, el("p", {}, note, el("span", { class: "sizer", "aria-hidden": "true" }, STALL_NOTE))), refused ? alertBox("danger", "alert", "The name could not be signed", "Please try again.") : null, - referenceLine(s.invoice?.invoiceId ?? view.id), + referenceLine(s.invoice?.invoiceId ?? view.id, proofOf(s)), termsAskedAgain(s) ? agreement(s, "reveal") : null) } @@ -1103,9 +1080,9 @@ export const REFUSED_LINK: Record = { export const REPLACE_LINK = "Replace or remove it to register the name." -function buildNotOnDevice({ view, invoice }: OrderState): HTMLElement { +function buildNoCode({ reference }: OrderState): HTMLElement { return outcome({ tone: "info", icon: "key", title: "The name code is not in this browser", text: "Please enter the name code you saved for this order.", - action: btn("Enter your name code", "", () => go(CODE_FROM_ORDER_URL)), reference: invoice?.invoiceId ?? view!.id }) + action: btn("Enter your name code", "", () => go(CODE_FROM_ORDER_URL)), reference }) } // a name of this browser's code needs nothing more from here; one of another browser's restores its code @@ -1117,9 +1094,9 @@ function buildRegistered(s: OrderState): HTMLElement { const code = s.record?.ownerCode ?? null // the code's QR is under everything, there only while the code is shown const qr = el("div", { class: "code-qr" }) - const { tld } = readSite() - return screen({ title: [label ? gradName(label, tld) : "The name", " is\u00a0yours"], lead: registeredLead(view, s.record), action: registeredAction(s.record) }, - code ? [el("div", { class: "card use" }, el("h2", {}, "Use your name in the app"), + const { tld } = SITE + return screen({ title: [label ? gradName(label, tld) : "The name", " is\u00a0yours"], lead: registeredLead(view), action: registeredAction(s.record) }, + code ? [nameAddressAndApp(code), el("div", { class: "card use" }, el("h2", {}, "Use your name in the app"), el("p", {}, "In SimpleX, open Your SimpleX address, tap Set SimpleX name and enter ", nameText(label ?? "", tld, "."), " For a channel, set it in the channel's profile.")), el("p", { class: "note center" }, NAME_CODE_NOTE), codeDisplay(code, "owner-code", true, (shown) => refill(qr, shown && nameCodeQr(code))), @@ -1127,17 +1104,16 @@ function buildRegistered(s: OrderState): HTMLElement { el("div", { class: "yours-edit center" }, btn(linksAction(hasLinks(s.record!, null)), "quiet small", () => go(editUrl(view.id)))), qr] : null) } -function registeredLead(view: api.RegistrationView, record: store.OrderRecord | null): string { +function registeredLead(view: api.RegistrationView): string { const expiresAt = api.expiresAtOf(view) - const until = expiresAt ? dateOf(expiresAt) : "" - return record ? `Registered until ${until}.` : `Registered until ${until} to ${shortAddress(view.owner)}. Its name code is not in this browser.` + return `Registered until ${expiresAt ? dateOf(expiresAt) : ""}.` } function buildEnded({ view, record, invoice }: OrderState): HTMLElement { const label = labelOf(view!, record) return outcome({ tone: "warn", icon: "alert", title: "Registration cancelled", - text: ["The registration of ", label ? nameText(label, readSite().tld) : "the name", " was cancelled because its payment was disputed or refunded."], - action: codesOnly() ? codeAction() : btn("Search a name", "", () => go(searchLink(""))), reference: invoice?.invoiceId ?? view!.id }) + text: ["The registration of ", label ? nameText(label, SITE.tld) : "the name", " was cancelled because its payment was disputed or refunded."], + action: codesOnly() ? codeAction() : btn("Search a name", "", () => go(searchLink(""))), reference: invoice?.invoiceId ?? view!.id, proof: proofOf({ record, invoice }) }) } // An order taken first keeps its payment or its code: a name is selected for the order, or support refunds the payment; @@ -1151,13 +1127,13 @@ function buildTaken(s: OrderState): HTMLElement { ? el("div", { class: "notice plain" }, el("b", {}, "What you paid is in your balance."), uses) : el("div", { class: "notice plain" }, el("b", {}, "What you paid went to your balance."), " It has been refunded since; Your names shows it.") const reserved = s.nameStatus === "reserved" - const title = label ? [gradName(label, readSite().tld), reserved ? " is\u00a0reserved" : " is no longer available"] : reserved ? "The name is reserved" : "The name is no longer available" + const title = label ? [gradName(label, SITE.tld), reserved ? " is\u00a0reserved" : " is no longer available"] : reserved ? "The name is reserved" : "The name is no longer available" return screen({ title, lead: reserved ? "It was reserved meanwhile, so it can't be registered." : undefined, ...balanceActions(s) }, api.takenByOrder(view) ? stages(["failed", "", ""]) : stages(["done", "done", "failed"], reserved ? "Reserved" : "Taken"), note, record ? null : alertBox("info", "key", "The name code is not in this browser", `Add it in Check your code to ${invoice ? "use the balance" : "choose another name"}.`), - referenceLine(invoice?.invoiceId ?? view.id)) + referenceLine(invoice?.invoiceId ?? view.id, proofOf(s))) } const REFUND = "refund" @@ -1168,7 +1144,7 @@ const REFUND = "refund" function balanceActions({ view, invoice, record }: OrderState, same?: HTMLButtonElement): { action: HTMLButtonElement; alt: HTMLElement | null } { const kept = same !== undefined || api.paymentKept(view!) const another = () => go(searchLink("", api.selectable(view!) ? view!.id : undefined)) - const refund = record && kept ? link("Get a refund", () => showRefund(invoice?.invoiceId ?? view!.id, REFUND)) : null + const refund = record && kept ? link("Get a refund", () => showRefund(invoice?.invoiceId ?? view!.id, REFUND, proofOf({ record, invoice }))) : null refund?.setAttribute("data-focus", REFUND) refund?.setAttribute("aria-haspopup", "dialog") if (codesOnly() && invoice) return { action: codeAction(), alt: refund } @@ -1180,7 +1156,8 @@ function buildFailed(s: OrderState, signal: AbortSignal): HTMLElement { const { view: failed, invoice } = s const view = failed! const settled = supportCase(s) - const continued = setAction(btn("Continue", "", () => void continueOrder()), s.busy === "continue", s.hold !== null) + const continues = settled === "unread" && s.record !== null + const continued = setAction(btn("Continue", "", () => void continueOrder()), s.busy === "continue", s.hold !== null || s.downtime || unagreed(s)) // with a code refused for good the order registers no name, so the page offers another search as the other endings do const action = settled === "unread" ? (s.record ? continued : withoutRecord("")) : s.codeRefused ? btn("Search a name", "quiet", () => go(searchLink(""))) : null @@ -1191,8 +1168,10 @@ function buildFailed(s: OrderState, signal: AbortSignal): HTMLElement { el("p", { class: "note center" }, ...orderLine(s)), stages(failedAt), alertBox("danger", "alert", failedAlert(s), settled ? supportText(settled, view, reference) : [...contactSupport("Please contact", reference), "."]), + continues && s.downtime ? alertBox("info", "clock", null, `${SIGNING_SOON}.`) : null, actionNote(s, signal), - referenceLine(reference)) + referenceLine(reference, proofOf(s)), + continues && s.ask?.label === s.record!.label ? agreement(s, TERMS_AGAIN) : null) } function supportText(settled: SupportCase, view: api.RegistrationView, reference: string): Kid[] { @@ -1209,20 +1188,39 @@ function supportText(settled: SupportCase, view: api.RegistrationView, reference } async function continueOrder(): Promise { + if (unagreed(state)) return const gen = opened const record = state.record! const view = state.view! dispatch({ type: "continue-started" }) try { - await api.reveal(view.id, await flow.revealFor(record, view.duration, await api.signFor(view.labelHash, view.owner))) + const toSign = await api.signFor(record.request.labelHash, record.owner) + const agreed = await continuedTerms(gen, record, toSign.acceptance) + if (agreed === null) return + await api.reveal(view.id, flow.revealFor(record, view, toSign, agreed), flow.orderSigner(record)) + keepAgreed(record, agreed) reread(gen) } catch (e) { - if (holdOn(e, LIMITED_LEAD, gen)) return + if (holdOn(e, PLEASE_LEAD, gen)) return answer(gen, { type: "continue-failed", note: warning("That did not work. Please try again in a moment.") }) reread(gen) } } +const TERMS_AGAIN = "terms-again" + +async function continuedTerms(gen: number, record: store.OrderRecord, acceptance: api.Acceptance): Promise { + const held = api.heldTerms(acceptance.termsHash, acceptance.community) + if (acceptance.termsHash === api.signedHash(record.terms) || !held) return record.terms + const { community } = await api.searchName(record.request.labelHash, record.label.length) + const quote = { terms: held, community } + const terms = termsToSign(record.label, api.currentTerms(quote), record.terms, state.ask) + if (terms !== null) return terms + askTerms(gen, record.label, quote, true) + if (isOpen(gen)) focusOn(TERMS_AGAIN) + return null +} + // Another order may have spent the code since this one failed, which Continue would only find out. A code revoked or // expired may still be held by this registration, whose Continue the service then takes, so only a spent one is refused. // A code the service does not know (code_invalid), or revoked, was not spent; null when the service did not answer, and @@ -1246,7 +1244,7 @@ const BUILDERS: Record> = { ended: buildEnded, taken: buildTaken, failed: buildFailed, - "not-on-device": buildNotOnDevice, + "status:no-code": buildNoCode, "status:closed": buildClosed, "status:card-unconfirmed": buildCardUnconfirmed, "status:paid-by-invoice": buildPaidByInvoice, diff --git a/webapp/src/views/search.ts b/webapp/src/views/search.ts index 0e01b2f3..5a039589 100644 --- a/webapp/src/views/search.ts +++ b/webapp/src/views/search.ts @@ -1,6 +1,6 @@ // The home: the landing's headline, the search box and every answer it can show. import * as api from "../api.ts" -import { loadedSite, namesSite, readSite } from "../config.ts" +import { heldPrice, SITE } from "../config.ts" import { labelHash } from "../crypto/registration.ts" import { hex } from "../crypto/wallet.ts" import { btn, el, icon, type Kid, line, link, NO_AUTOFILL, setAction, waitOut } from "../dom.ts" @@ -21,6 +21,7 @@ import { type Builder, CONTACT_EMAIL, currentRoute, draw, go, historyPlace, isRe import { chatButton } from "./chats.ts" import { CODES_ONLY_LINE, useCodeFor } from "./codes.ts" import { holdEnd, holdEnder, holdFrom, holdNotice, secondsLeft, tabHold } from "./hold.ts" +import { downtimeNow, inDowntime, NEW_ORDERS_SOON } from "./served-mode.ts" import { NO_ORDERS, rowName } from "./terms.ts" // word joiners keep "a–z" and "0–9" whole: a line may otherwise break after their dash @@ -46,12 +47,12 @@ export function searchPage(params: URLSearchParams): void { const fresh = !isRedraw() || shown === null || state.opening !== opening const returned = fresh && throughHistory() if (fresh) { - state = returned ? returnedTo(state, opening, name, loadedSite()?.tld, store.orders()) : initialSearch() + state = returned ? returnedTo(state, opening, name, SITE.tld, store.orders()) : initialSearch() shown = null opens += 1 } pageRoute = currentRoute() - dispatch({ type: "opened", opening, name, order, hold: tabHold() }) + dispatch({ type: "opened", opening, name, order, hold: tabHold(), downtime: inDowntime() }) if (state.order) void checkOrder(state.order) if (searchDue(state)) submit() else if (returned && state.answer) void runSearch(state.name, state.seq) @@ -96,15 +97,16 @@ async function runSearch(label: string, seq: number): Promise { const awaited = () => onPage(page) && seq === state.seq const hash = hex(labelHash(label)) let answer: api.SearchAnswer + let downtime: boolean try { - answer = await api.searchName(hash, label.length, (await namesSite()).chainId) + [answer, downtime] = await Promise.all([api.searchName(hash, label.length), downtimeNow()]) } catch (e) { if (!awaited()) return if (holdFrom(e)) return dispatch({ type: "search-held", seq, until: holdEnd() }) return dispatch({ type: "unanswered", seq }) } if (!awaited()) return - dispatch({ type: "answered", seq, label, answer, mine: mineFor(hash, answer) !== undefined, now: api.serviceNow() }) + dispatch({ type: "answered", seq, label, answer, mine: mineFor(hash, answer) !== undefined, now: api.serviceNow(), downtime }) if (answer.found.type === "available" || answer.found.type === "taken") void pointAtOwnOrder(label, hash, page) } @@ -120,8 +122,9 @@ let ownRead: { label: string; orders: Promise } | null = null async function pointAtOwnOrder(label: string, hash: string, page: number): Promise { const read = async (o: store.OrderRecord): Promise => { if (!onPage(page)) return null - const invoice = o.invoiceId ? await api.readInvoice(o.invoiceId).catch(() => null) : null - const reg = invoice?.registration ?? (o.invoiceId ? null : await api.readRegistration(o.registrationId).catch(() => null)) + const sign = flow.orderSigner(o) + const invoice = o.invoiceId ? await api.readInvoice(o.invoiceId, sign).catch(() => null) : null + const reg = invoice?.registration ?? (o.invoiceId ? null : await api.readRegistration(o.registrationId, sign).catch(() => null)) return reg && { phase: reg.phase.type, failure: reg.phase.type === "failed" ? reg.phase.reason : null, invoice: invoice?.status ?? null } } const orders = ownOrders(store.orders().filter((r) => r.request.labelHash === hash), read) @@ -133,7 +136,8 @@ async function pointAtOwnOrder(label: string, hash: string, page: number): Promi } export async function readOrder(record: store.OrderRecord): Promise<{ view: api.RegistrationView; synced: store.OrderRecord } | null> { - const view = await (record.invoiceId ? api.readInvoice(record.invoiceId).then((i) => i.registration) : api.readRegistration(record.registrationId)).catch(() => null) + const sign = flow.orderSigner(record) + const view = await (record.invoiceId ? api.readInvoice(record.invoiceId, sign).then((i) => i.registration) : api.readRegistration(record.registrationId, sign)).catch(() => null) if (!view) return null const synced = await flow.syncRecord(record, view) ?? record return { view, synced: { ...synced, paid: view.price } } @@ -163,26 +167,25 @@ function offered({ answer }: SearchState): { label: string; answer: flow.Availab async function register(): Promise { const shown = offered(state) - if (!shown || !flow.orderable(shown.answer)) return + if (!shown || state.downtime || !orderableBy(state, shown.label, shown.answer)) return const page = opens const closed = ownRead?.label === shown.label ? (await ownRead.orders).closed : null const still = offered(state) // an order of the name that the reads found still open is the buyer's, which the page points at instead - if (!onPage(page) || still?.label !== shown.label || state.ownOrder !== null || !flow.orderable(still.answer)) return + if (!onPage(page) || still?.label !== shown.label || state.ownOrder !== null || state.downtime || !orderableBy(state, still.label, still.answer)) return checkOut(state, still.label, still.answer, closed?.ownerCode ?? null) } function checkOut(s: SearchState, label: string, answer: flow.Quote, closedCode: string | null): void { - const site = readSite() - const chain = flow.chainOf(site) const code = codeFor(s, label) const taken = s.order const { ownerCode, saved } = taken ? { ownerCode: taken.ownerCode, saved: true } : orderCode(closedCode) const order = taken ? { registrationId: taken.registrationId, method: taken.method, paid: taken.paid } : undefined const started = session.checkout() - const quote = { price: answer.price, years: taken?.years ?? answer.years, termStart: site.termStart, chain, terms: answer.terms, community: answer.community } + const price = heldPrice(label.length) + const quote = { price, years: taken?.years ?? answer.years, terms: answer.terms, community: answer.community } const sameCode = !ownerCode || started?.ownerCode == null || started.ownerCode === ownerCode - if (started && started.label === label && started.price === answer.price && started.chain.chainId === chain.chainId && !session.isSending(started) && sameCode) { + if (started && started.label === label && started.price === price && !session.isSending(started) && sameCode) { const agreed = started.agreed && api.currentTerms(started) === api.currentTerms(answer) const accepted = started.accepted && api.currentTerms(started) === api.currentTerms(answer) session.updateCheckout(label, { @@ -259,7 +262,7 @@ function buildSearch(s: SearchState, signal: AbortSignal): HTMLElement { // the answer's room is kept from the start, so the headline and the field never move as an answer comes return el("section", { class: "home" }, el("h1", {}, HEADLINE), el("p", { class: "sub" }, SUB), - el("div", { class: "search" }, box, keptLive("search-answer", "answer", locked ? codesOnlyAnswer() : answerOf(s, retry, signal)))) + el("div", { class: "search" }, box, keptLive("search-answer", "answer", locked ? codesOnlyAnswer() : answerOf(s, retry, signal), s.downtime ? line("", "clock", `${NEW_ORDERS_SOON}.`) : null))) } function answerOf(s: SearchState, retry: () => void, signal: AbortSignal): Kid { @@ -277,7 +280,7 @@ function answerOf(s: SearchState, retry: () => void, signal: AbortSignal): Kid { function reservedAnswer(label: string, answer: api.SearchAnswer): Kid[] { return [ - el("div", { class: "card row" }, rowName(label, readSite().tld, answer.community, "community"), el("span", { class: "soft" }, "Reserved")), + el("div", { class: "card row" }, rowName(label, SITE.tld, answer.community, "community"), el("span", { class: "soft" }, "Reserved")), line("info", "info", "If you want to use this name, please contact us via ", el("a", { class: "nowrap", href: `mailto:${CONTACT_EMAIL}` }, CONTACT_EMAIL), " or ", el("a", { href: SIMPLEX_SUPPORT, target: "_blank", rel: "noopener" }, "SimpleX"), "."), ] @@ -302,26 +305,28 @@ const codeFor = (s: SearchState, label: string) => { const code = session.activeCode() return code && usesCode(s) && label.length >= code.minLength ? code : null } +const freeBy = (s: SearchState, label: string) => codeFor(s, label) ?? (s.order && codeCover(s.order)) +const orderableBy = (s: SearchState, label: string, answer: flow.Available): answer is flow.Quote => + flow.orderable(answer) && (freeBy(s, label) !== null || answer.price === heldPrice(label.length)) function availableAnswer(s: SearchState, label: string, answer: flow.Available, signal: AbortSignal): Kid[] { const cover = s.order && codeCover(s.order) const own = s.ownOrder - const code = codeFor(s, label) - const free = code ?? cover - const paid = s.order && !cover && s.order.paid === answer.price ? s.order : null + const free = freeBy(s, label) + const paid = s.order && !cover && s.order.paid === heldPrice(label.length) ? s.order : null const unpaid = s.order && !free && !paid ? s.order : null const short = usesCode(s) ? session.activeCode() : cover - const orderable = flow.orderable(answer) - const button = setAction(btn("Register", "small", () => void register()), false, own !== null || s.hold !== null || !orderable || unpaid !== null) - button.dataset.focus = "register" - const deal = [el("b", { class: "price" }, free ? "Free" : paid ? "Paid" : dollars(answer.price)), + const orderable = orderableBy(s, label, answer) + const button = s.downtime ? null : setAction(btn("Register", "small", () => void register()), false, own !== null || s.hold !== null || !orderable || unpaid !== null) + if (button) button.dataset.focus = "register" + const deal = [el("b", { class: "price" }, free ? "Free" : paid ? "Paid" : dollars(heldPrice(label.length))), el("span", { class: "soft" }, ` / ${api.termYears(answer.community, (free ?? paid)?.years ?? answer.years)} years`)] return [ - el("div", { class: "card row buy" }, rowName(label, readSite().tld, answer.community, "community"), el("div", { class: "offer" }, el("span", { class: "deal" }, deal), button)), + el("div", { class: "card row buy" }, rowName(label, SITE.tld, answer.community, "community"), el("div", { class: "offer" }, el("span", { class: "deal" }, deal), button)), !free && short ? el("p", { class: "hint" }, `${letters(label.length)}. ${useCodeFor(short.minLength)}.`) : null, unpaid ? el("p", { class: "hint" }, `Your payment covers names at ${dollars(unpaid.paid)} for ${unpaid.years} years.`) : null, own ? line("", "info", "You already have an order for this name. ", el("a", { class: "nowrap", href: own }, "Open that order")) : null, - orderable ? null : line("warn", "alert", `${NO_ORDERS}. Please try again later.`), + orderable || s.downtime ? null : line("warn", "alert", `${NO_ORDERS}. Please try again later.`), own || !s.hold ? null : holdNotice(s.hold, signal), ] } @@ -340,7 +345,7 @@ function takenAnswer(s: SearchState, found: Found, answer: api.SearchAnswer): Ki const own = answer.found.type === "taken" ? s.ownOrder : null const whose = own ? null : mine && again?.when !== "taken" ? (lapsed ? el("span", { class: "soft" }, "Expired") : el("a", { class: "nowrap", href: "/#/names" }, "Your name")) : el("span", { class: "soft" }, "Taken") - const { tld } = readSite() + const { tld } = SITE const name = `${label}.${tld}` const entities = registered?.entities ?? [] return [ diff --git a/webapp/src/views/served-mode.ts b/webapp/src/views/served-mode.ts index d2cf3016..6c7f83fe 100644 --- a/webapp/src/views/served-mode.ts +++ b/webapp/src/views/served-mode.ts @@ -1,17 +1,8 @@ -// A page drawn in a mode the service no longer serves loads again from the service: at once when that loses nothing, -// otherwise at its next route, which leaves the screen on show anyway. import { changeOnItsWay } from "../api.ts" -import { readConfig } from "../config.ts" -import { type Mode, pageMode } from "../mode.ts" +import { readConfig, type SiteConfig } from "../config.ts" import * as session from "../session.ts" import * as store from "../store.ts" -// Past the HTTP cache; the worker answers from the network while it is there. -async function servedMode(): Promise { - const config = await readConfig({ cache: "no-store" }) - return config && (config.names?.codesOnly ? "codes" : "open") -} - // a field typed into since it was drawn holds what the page has not kept const typedInto = () => [...document.querySelectorAll("input")].some((i) => i.type === "text" && i.value !== i.defaultValue) // a tick that only the page's memory holds, as an order page's terms agreed to again @@ -22,6 +13,11 @@ const cardForm = () => document.querySelector("body > main iframe") !== null // what a reload would lose besides the screen: an order or change on its way, or what storage did not take const reloadKeeps = () => !changeOnItsWay() && !session.anySending() && session.allKept() && store.canPersist() && !cardForm() +export const NEW_ORDERS_SOON = "You will be able to order names again soon" +export const PAYMENT_SOON = "You will be able to pay again soon" +export const SIGNING_SOON = "You will be able to continue the registration soon" + +let downtime = false let afresh = false // The page at its next route, as the screen on show is left: true when it loads the document again instead of drawing it. @@ -36,20 +32,26 @@ export function loadNextRouteAfresh(): void { afresh = true } -async function compare(): Promise { - const served = await servedMode() - if (served === null) return - afresh = served !== pageMode() - if (afresh && reloadKeeps() && !typedInto() && !tickedUnkept()) location.reload() +export const inDowntime = () => downtime + +function served(config: SiteConfig | null): void { + if (config === null) return + const ended = downtime && !config.downtime + downtime = config.downtime + if (!ended) return + if (reloadKeeps() && !typedInto() && !tickedUnkept()) return location.reload() + afresh = true } let comparing: Promise | null = null -function check(): void { - comparing ??= compare().finally(() => { comparing = null }) +function check(): Promise { + return comparing ??= readConfig({ cache: "no-store" }).then(served).finally(() => { comparing = null }) } -// A load reads the mode before the page draws (src/config.ts), so only a return to a page drawn earlier checks it. -export function followServedMode(): void { - document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") check() }) - addEventListener("pageshow", (e) => { if (e.persisted) check() }) +export const downtimeNow = () => check().then(inDowntime) + +export function followServedMode(loaded: SiteConfig | null): void { + served(loaded) + document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") void check() }) + addEventListener("pageshow", (e) => { if (e.persisted) void check() }) } diff --git a/webapp/src/views/shell.ts b/webapp/src/views/shell.ts index 9a26e2dc..2c2c220e 100644 --- a/webapp/src/views/shell.ts +++ b/webapp/src/views/shell.ts @@ -1,7 +1,9 @@ // The page's frame: theme switch and navigation between views; index.html draws the header and footer. +import type { AddressProof } from "../api.ts" import { alertBox, announce, btn, copyButton, el, fitNames, icon, type Kid, liveRegion, reducedMotion, refill, type Tone, waitOut } from "../dom.ts" +import { SEP } from "../format.ts" import type { IconName } from "../icons.ts" -import { type Hold, LIMITED_LEAD } from "../screens/hold.ts" +import { type Hold, PLEASE_LEAD } from "../screens/hold.ts" import * as session from "../session.ts" import * as store from "../store.ts" import { secondsLeft } from "./hold.ts" @@ -147,7 +149,7 @@ export type Builder = (state: S, signal: AbortSignal) => HTMLElement // a screen's main action and its text-link alternative, which a step holds at one place on every step interface Actions { action?: Node | null; alt?: Node | null } interface ScreenHead extends Actions { title: Kid; lead?: Kid; back?: string } -interface Outcome extends Actions { tone: Tone; icon: IconName; title: string; text: Kid; reference?: string; extra?: Kid; agreement?: Kid; back?: string } +interface Outcome extends Actions { tone: Tone; icon: IconName; title: string; text: Kid; reference?: string; proof?: AddressProof; extra?: Kid; agreement?: Kid; back?: string } export function kept(key: string, make: () => T): T { const known = keptNodes.get(key) @@ -275,17 +277,17 @@ export function asStep(screen: HTMLElement): HTMLElement { export function outcome(o: Outcome): HTMLElement { return el("section", { class: "screen outcome" }, screenHead(o.title, o.back), - el("div", { class: "screen-body" }, o.text === null ? null : alertBox(o.tone, o.icon, null, o.text), o.extra ?? null, o.reference ? referenceLine(o.reference) : null, o.agreement ?? null), + el("div", { class: "screen-body" }, o.text === null ? null : alertBox(o.tone, o.icon, null, o.text), o.extra ?? null, o.reference ? referenceLine(o.reference, o.proof) : null, o.agreement ?? null), actionsOf(o)) } export function limitScreen(hold: Hold | null, again: () => void, back: string, signal: AbortSignal): HTMLElement { - const line = el("span", {}, `${LIMITED_LEAD}try again.`) + const line = el("span", {}, `${PLEASE_LEAD}try again.`) const tryAgain = btn("Try again", "", again) tryAgain.disabled = hold !== null const shown = outcome({ tone: "warn", icon: "clock", title: "Too many attempts", text: line, action: tryAgain, back }) // the count goes in once the line is in its notice, where its spoken copy goes beside it - if (hold) waitOut(line, Math.max(1, secondsLeft(hold)), (left) => `${LIMITED_LEAD}try again in ${left}.`, () => undefined, signal) + if (hold) waitOut(line, Math.max(1, secondsLeft(hold)), (left) => `${PLEASE_LEAD}try again in ${left}.`, () => undefined, signal) return shown } @@ -315,8 +317,8 @@ export function showPopup(key: string, kids: Kid[], first: HTMLElement | null): } // Support refunds a balance by hand, on a message that quotes the order's reference. -export function showRefund(reference: string, key: string): void { - const copy = copyButton(reference, "field-copy", "Copy reference") +export function showRefund(reference: string, key: string, proof?: AddressProof): void { + const copy = proof === undefined ? copyButton(reference, "field-copy", "Copy reference") : copyButton(withProof(reference, proof), "field-copy", WITH_PROOF) showPopup(key, [ el("h2", { id: POPUP_TITLE }, "Refund"), el("p", {}, ...contactSupport("Please contact", reference), ". Support refunds what is left of your balance."), @@ -324,7 +326,11 @@ export function showRefund(reference: string, key: string): void { ], copy) } -export const referenceLine = (reference: string) => el("p", { class: "note ref" }, "Reference ", el("span", { class: "mono" }, reference)) +const WITH_PROOF = "Copy the order reference and address proof for support" +const withProof = (reference: string, proof: AddressProof) => `Order reference ${reference}, address proof ${JSON.stringify(proof)}` + +export const referenceLine = (reference: string, proof?: AddressProof) => el("p", { class: "note ref" }, "Reference ", el("span", { class: "mono" }, reference), + ...proof === undefined ? [] : [SEP, copyButton(withProof(reference, proof), "text-link", WITH_PROOF, "Copy for support")]) // shown only before a document's first draw, placed as the screen after it will be, so its heading stays put export function drawLoading(title: string, place = (screen: HTMLElement) => screen): void { diff --git a/webapp/src/views/terms.ts b/webapp/src/views/terms.ts index 5c2c1924..15f2b5f2 100644 --- a/webapp/src/views/terms.ts +++ b/webapp/src/views/terms.ts @@ -1,4 +1,5 @@ import * as api from "../api.ts" +import { SITE } from "../config.ts" import { el, icon, line, nameText, nameTitle } from "../dom.ts" import { blocksOf, spansOf } from "../markdown.ts" import { POPUP_TITLE, showPopup } from "./shell.ts" @@ -29,16 +30,16 @@ export function termsText(text: string): HTMLDivElement { : el(b.ordered ? "ol" : "ul", {}, b.items.map((item) => el("li", {}, inline(item)))))) } -export function commitLink(terms: api.Terms, chainId: number): HTMLElement | null { - const commit = api.termsLink(terms.link, chainId)?.commit +export function commitLink(terms: api.Terms): HTMLElement | null { + const commit = api.termsLink(terms.link, SITE.chainId)?.commit return commit ? el("p", { class: "note center" }, el("a", { href: api.readerUrl(terms.link), target: "_blank", rel: "noopener" }, `View at commit ${commit.slice(0, 7)}`)) : null } // the community terms' text as the service fetches it by the chain's link -function showTerms(terms: api.Terms, chainId: number, key: string): void { +function showTerms(terms: api.Terms, key: string): void { const reading = el("p", { class: "note" }, "Loading the terms…") showPopup(key, [el("h2", { id: POPUP_TITLE }, "Community terms"), reading], null) - api.termsText(terms, chainId).then((read) => reading.replaceWith(termsText(read), commitLink(terms, chainId) ?? ""), () => { reading.textContent = CANT_SHOW }) + api.termsText(terms).then((read) => reading.replaceWith(termsText(read), commitLink(terms) ?? ""), () => { reading.textContent = CANT_SHOW }) } // `listed` marks a community name whose entry is not read yet, so the marker takes its place before the entry comes @@ -56,8 +57,6 @@ export interface Agreement { accepted?: boolean changed: boolean label: string - tld: string - chainId: number disabled: boolean } @@ -75,10 +74,10 @@ export function communityCheck(a: Agreement, accept: (accepted: boolean) => void const box = el("input", { type: "checkbox", checked: a.accepted, disabled: a.disabled, "data-focus": "accepted" }) box.addEventListener("change", () => accept(box.checked)) const terms = shown ? "Names Conditions" : el("button", { class: "text-link", type: "button", "aria-haspopup": "dialog", "data-focus": TERMS_KEY, - onclick: () => showTerms(a.terms, a.chainId, TERMS_KEY) }, "Names Conditions") + onclick: () => showTerms(a.terms, TERMS_KEY) }, "Names Conditions") return el("label", { class: "check terms" }, box, el("span", { class: "box" }), el("span", {}, "I accept the ", terms, " and will use this name to benefit its community.", el("button", { class: "cinfo", type: "button", "aria-label": "Which community this name is for", "aria-haspopup": "dialog", "data-focus": INFO_KEY, - onclick: () => showCommunity(a.label, a.tld, community, INFO_KEY) }, icon("info")))) + onclick: () => showCommunity(a.label, SITE.tld, community, INFO_KEY) }, icon("info")))) } // the general terms' box, or a community name's own tick in its place, as its community terms include the general terms diff --git a/webapp/sw/plugin.ts b/webapp/sw/plugin.ts index e093c155..e510054d 100644 --- a/webapp/sw/plugin.ts +++ b/webapp/sw/plugin.ts @@ -5,14 +5,14 @@ import { readdirSync, readFileSync, statSync } from "node:fs" import { join } from "node:path" import type { Plugin } from "vite" -export interface WorkerBuild { build: string; entry: string; precache: string[] } +export interface WorkerBuild { build: string; entry: string; precache: string[]; api: string } export const WORKER_TEMPLATE = new URL("./worker.js", import.meta.url) // the shell is fetched and checked on its own; the rest the page never asks for const NOT_PRECACHED = /^(index\.html|robots\.txt|sw\.js)$|\.map$/ const BUILD_ID_LENGTH = 16 -export function workerSource(template: string, { build, entry, precache }: WorkerBuild): string { +export function workerSource(template: string, { build, entry, precache, api }: WorkerBuild): string { let source = template const set = (name: string, value: unknown) => { const line = new RegExp(`^const ${name} = .*$`, "m") @@ -22,6 +22,7 @@ export function workerSource(template: string, { build, entry, precache }: Worke set("BUILD", build) set("ENTRY", entry) set("PRECACHE", precache) + set("API", api) return source } @@ -33,7 +34,7 @@ function filesIn(dir: string, under = ""): string[] { }) } -export function serviceWorker(): Plugin { +export function serviceWorker(api: string): Plugin { let publicDir = "" return { name: "service-worker", @@ -59,7 +60,7 @@ export function serviceWorker(): Plugin { } if (!entry) this.error("sw: the build has no entry module") const build = hash.digest("hex").slice(0, BUILD_ID_LENGTH) - this.emitFile({ type: "asset", fileName: "sw.js", source: workerSource(readFileSync(WORKER_TEMPLATE, "utf8"), { build, entry, precache: precache.sort() }) }) + this.emitFile({ type: "asset", fileName: "sw.js", source: workerSource(readFileSync(WORKER_TEMPLATE, "utf8"), { build, entry, precache: precache.sort(), api }) }) }, } } diff --git a/webapp/sw/worker.js b/webapp/sw/worker.js index 06ddf6bc..4fc1258c 100644 --- a/webapp/sw/worker.js +++ b/webapp/sw/worker.js @@ -1,6 +1,6 @@ // The service worker: the page and its files from this browser's cache when the network is not there, so the page, // and Your names read from this browser's storage, open offline. A classic worker script, so its export is the -// worker's own global. sw/plugin.ts writes the three constants below into the built copy; test/sw.test.ts runs that +// worker's own global. sw/plugin.ts writes the four constants below into the built copy; test/sw.test.ts runs that // copy in a Node vm with a fake Cache API and reads self.sw. const BUILD = "dev" @@ -8,6 +8,7 @@ const BUILD = "dev" const ENTRY = "/src/main.ts" // every file of the build but the shell, each named by its content or kept under this build's cache const PRECACHE = [] +const API = "" // one cache per build, so clearing out is "everything that is not this one" const CACHE = `names-${BUILD}` @@ -17,7 +18,7 @@ const PRECACHED = new Set(PRECACHE) // The whole routing decision, from the URL alone. function strategyFor(url) { - if (url.origin !== self.location.origin) return "bypass" + if (url.origin !== self.location.origin) return API && url.origin === API && url.pathname === CONFIG ? "config" : "bypass" if (url.pathname === CONFIG) return "config" // before anything that could reach a cache: an order, a name or a code read from a cache would show a past state if (/^\/(api|control)(\/|$)/.test(url.pathname)) return "network-only" @@ -98,15 +99,14 @@ async function keepShell(shell) { if (await isThisBuildsShell(shell)) await (await caches.open(CACHE)).put(SHELL, shell) } -// Network first, as the mode decides what a page offers; offline, the service's last answer, so the page opens in -// the mode it gave then. async function configFirst(event) { let fresh try { fresh = await fetch(event.request) } catch {} if (fresh?.ok) { - event.waitUntil(caches.open(CACHE).then((cache) => cache.put(CONFIG, fresh.clone()))) + const kept = fresh.clone() + event.waitUntil(caches.open(CACHE).then((cache) => cache.put(CONFIG, kept))) return fresh } const hit = await (await caches.open(CACHE)).match(CONFIG, MATCH) @@ -123,4 +123,4 @@ self.addEventListener("fetch", (event) => { event.respondWith(strategy === "config" ? configFirst(event) : strategy === "shell" ? shellFirst(event) : fromPrecache(request)) }) -self.sw = { BUILD, CACHE, CONFIG, ENTRY, PRECACHE, SHELL, strategyFor } +self.sw = { API, BUILD, CACHE, CONFIG, ENTRY, PRECACHE, SHELL, strategyFor } diff --git a/webapp/test/addresses.test.ts b/webapp/test/addresses.test.ts index 00eb49df..7a3acd9d 100644 --- a/webapp/test/addresses.test.ts +++ b/webapp/test/addresses.test.ts @@ -1,87 +1,63 @@ -import { ed25519 } from "@noble/curves/ed25519" -import { keccak_256 } from "@noble/hashes/sha3" +import { bytesToHex, hexToBytes } from "@noble/hashes/utils" +import { HDKey } from "@scure/bip32" import { describe, expect, it } from "vitest" -import { addressFor } from "../dev/mock/addresses.ts" +import { bitcoinPayee, DEV_MONERO_PRIMARY, DEV_XPUB, devReceiving, moneroPayee, payeeFor, TESTNET_VERSIONS } from "../dev/mock/addresses.ts" +import { LOCAL } from "../src/config.ts" +import { bitcoinProven, moneroProven, p2wpkh } from "../src/crypto/payees.ts" +import { BIP32, BIP84, DEV_BITCOIN, DEV_MONERO } from "./payee-vectors.ts" -const BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" -const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +const proven = ({ address, addressProof: p }: ReturnType) => p.type === "btc" + ? bitcoinProven(address, p.keyTweak, LOCAL.bitcoinReceiveKeys, LOCAL.bitcoinHrp) + : moneroProven(address, p.spendTweak, p.viewProof, LOCAL.moneroPrimaryAddresses, LOCAL.moneroSubaddressPrefix) -// BIP-173's reference decoder: the checksum over the expanded prefix and the data is 1 for bech32 -function bech32Decode(address: string): { hrp: string; data: number[] } { - const at = address.lastIndexOf("1") - const hrp = address.slice(0, at) - const data = [...address.slice(at + 1)].map((c) => BECH32.indexOf(c)) - const generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] - let chk = 1 - for (const v of [...[...hrp].map((c) => c.charCodeAt(0) >> 5), 0, ...[...hrp].map((c) => c.charCodeAt(0) & 31), ...data]) { - const top = chk >>> 25 - chk = ((chk & 0x1ffffff) << 5) ^ v - generator.forEach((g, i) => { if ((top >>> i) & 1) chk ^= g }) - } - expect(chk, `${address}'s checksum`).toBe(1) - return { hrp, data: data.slice(0, -6) } -} +describe("the mock's invoice addresses", () => { + const ids = ["q7ZpL2dN9xWc4KfR8tYb1A", "2RWx7gmoLy73IvifBS1V5Q", "x"] -function fromFiveBits(values: number[]): number[] { - const out: number[] = [] - let acc = 0 - let bits = 0 - for (const v of values) { - acc = (acc << 5) | v - bits += 5 - if (bits >= 8) { - bits -= 8 - out.push((acc >>> bits) & 255) - } - } - return out -} + it("derive from the dev keys the page holds", () => { + expect(DEV_XPUB).toBe(DEV_BITCOIN.xpub) + expect(LOCAL.bitcoinReceiveKeys).toEqual([`0x${bytesToHex(devReceiving.publicKey!)}`]) + expect(LOCAL.moneroPrimaryAddresses).toEqual([DEV_MONERO_PRIMARY]) + }) -// Monero's base58: 11 characters a full block of 8 bytes, fewer for the last -function moneroDecode(address: string): Uint8Array { - const sizes = [0, 2, 3, 5, 6, 7, 9, 10, 11] - const out: number[] = [] - for (let at = 0; at < address.length; at += 11) { - const chunk = address.slice(at, at + 11) - const bytes = sizes.indexOf(chunk.length) - let n = [...chunk].reduce((acc, c) => acc * 58n + BigInt(BASE58.indexOf(c)), 0n) - const block = new Array(bytes) - for (let i = bytes - 1; i >= 0; i--) { - block[i] = Number(n % 256n) - n /= 256n - } - out.push(...block) - } - return new Uint8Array(out) -} + it("derive a child's key and its tweak as BIP-32 does", () => { + const child = HDKey.fromExtendedKey(BIP32.xpub).deriveChild(BIP32.index) + expect([bytesToHex(child.publicKey!), bytesToHex(child.chainCode!)]).toEqual([BIP32.publicKey, BIP32.chainCode]) + const parent = HDKey.fromExtendedKey(BIP32.xpub) + const payee = bitcoinPayee(parent, "bc", BIP32.index) + expect(payee.address).toBe(p2wpkh("bc", hexToBytes(BIP32.publicKey))) + expect(bitcoinProven(payee.address, payee.addressProof.keyTweak, [`0x${bytesToHex(parent.publicKey!)}`], "bc")).toBe(true) + }) -describe("the mock's invoice addresses", () => { - const ids = ["q7ZpL2dN9xWc4KfR8tYb1A", "2RWx7gmoLy73IvifBS1V5Q", "x"] + it("are the store service's recorded addresses and proofs, for BIP-84's wallet and the dev wallets", () => { + const bip84 = HDKey.fromExtendedKey(BIP84.xpub).deriveChild(0) + expect(`0x${bytesToHex(bip84.publicKey!)}`).toBe(BIP84.receiveKey) + for (const { index, address, keyTweak } of BIP84.invoices) expect(bitcoinPayee(bip84, "bc", index)).toEqual({ address, addressProof: { type: "btc", keyTweak } }) + expect(`0x${bytesToHex(HDKey.fromExtendedKey(DEV_BITCOIN.xpub, TESTNET_VERSIONS).deriveChild(0).publicKey!)}`).toBe(DEV_BITCOIN.receiveKey) + for (const { index, address, keyTweak } of DEV_BITCOIN.invoices) expect(bitcoinPayee(devReceiving, "bcrt", index)).toEqual({ address, addressProof: { type: "btc", keyTweak } }) + for (const { accountIndex, addressIndex, address, spendTweak, viewProof } of DEV_MONERO.invoices) { + expect(moneroPayee(accountIndex, addressIndex)).toEqual({ address, addressProof: { type: "xmr", spendTweak, viewProof } }) + } + }) - it.each(ids)("gives a Bitcoin regtest P2WPKH address with a valid bech32 checksum (%s)", (id) => { - const address = addressFor("btc", id) - expect(address).toMatch(/^bcrt1q[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{38}$/) - const { hrp, data } = bech32Decode(address) - expect(hrp).toBe("bcrt") - expect(data[0], "witness version").toBe(0) - expect(fromFiveBits(data.slice(1)), "a 20-byte key hash").toHaveLength(20) + it.each(ids)("give each invoice a regtest address and a stagenet subaddress the page proves from its keys (%s)", (id) => { + const btc = payeeFor("btc", id) + const xmr = payeeFor("xmr", id) + expect(btc.address).toMatch(/^bcrt1q[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{38}$/) + expect(xmr.address).toHaveLength(95) + expect([proven(btc), proven(xmr)]).toEqual([true, true]) }) - it.each(ids)("gives a Monero stagenet standard address whose checksum and keys hold (%s)", (id) => { - const address = addressFor("xmr", id) - expect(address).toHaveLength(95) - expect(address.startsWith("5"), "stagenet standard addresses start with 5").toBe(true) - const bytes = moneroDecode(address) - expect(bytes).toHaveLength(69) - expect(bytes[0], "the stagenet network byte").toBe(24) - expect([...keccak_256(bytes.slice(0, 65)).slice(0, 4)], "the checksum").toEqual([...bytes.slice(65)]) - // the spend and view keys are points of the curve - for (const key of [bytes.slice(1, 33), bytes.slice(33, 65)]) expect(() => ed25519.Point.fromBytes(key)).not.toThrow() + it("give each invoice its own address, the same each time it is asked", () => { + expect(payeeFor("btc", ids[0])).toEqual(payeeFor("btc", ids[0])) + expect(payeeFor("btc", ids[0]).address).not.toBe(payeeFor("btc", ids[1]).address) + expect(payeeFor("xmr", ids[0]).address).not.toBe(payeeFor("xmr", ids[1]).address) }) - it("gives each invoice its own address, the same each time it is asked", () => { - expect(addressFor("btc", ids[0])).toBe(addressFor("btc", ids[0])) - expect(addressFor("btc", ids[0])).not.toBe(addressFor("btc", ids[1])) - expect(addressFor("xmr", ids[0])).not.toBe(addressFor("xmr", ids[1])) + it.each(ids)("give an address of another wallet, with its proof, which the page's keys do not prove (%s)", (id) => { + for (const method of ["btc", "xmr"] as const) { + const other = payeeFor(method, id, true) + expect(other.address).not.toBe(payeeFor(method, id).address) + expect(proven(other), method).toBe(false) + } }) }) diff --git a/webapp/test/api.test.ts b/webapp/test/api.test.ts index 9575fcaf..002101cf 100644 --- a/webapp/test/api.test.ts +++ b/webapp/test/api.test.ts @@ -1,11 +1,13 @@ import { afterEach, describe, expect, it, vi } from "vitest" import { keccak256, sha256, toHex, zeroHash } from "viem" import { - ApiError, cancelInvoice, checkCode, createOrder, currentTerms, editRecords, EditLimited, previewLink, readInvoice, readRegistration, registerWithCode, retryDelay, searchName, seenOf, selectName, TermsChanged, - communityAgreed, readerUrl, type RegistrationView, selectable, signedHash, termsFor, termsLink, termsText, termYears, + addressProven, ApiError, cancelInvoice, checkCode, createOrder, currentTerms, editRecords, EditLimited, previewLink, readInvoice, readRegistration, registerWithCode, retry, retryDelay, reveal, searchName, seenOf, selectName, TermsChanged, + communityAgreed, type OrderSigner, readerUrl, type RegistrationView, selectable, signedHash, termsFor, termsLink, termsText, termYears, } from "../src/api.ts" +import { LOCAL } from "../src/config.ts" const HASH = "ab".repeat(32) +const SIGN: OrderSigner = (id, action) => ({ timestamp: 7, signature: `0x${id}${action}` }) const COMMIT = "4cb24444a1f2e3d4c5b6a7980716253443526170" const FORGEJO = `https://git.simplex.chat/simplex-chat/simplex-chat/raw/commit/${COMMIT}` const GITHUB = `https://raw.githubusercontent.com/simplex-chat/simplex-chat/${COMMIT}` @@ -15,15 +17,14 @@ function answerWith(status: number, body: string, headers: Record new Response(body, { status, headers }))) } -const CHAIN_ID = 31337 const REVEAL = { label: "alicebakery", secret: `0x${"11".repeat(32)}`, records: { contact: null, channel: null }, nonce: 0, deadline: 1800000000, signature: "0x", acceptance: { termsHash: `0x${"ab".repeat(32)}`, nonce: 0, signature: "0x" }, } const REGISTERED = { type: "registered", owner: "0x1", resolver: "0x2", expiresAt: 1, gracePeriod: 2, entities: [], records: { type: "other" } } -async function errorOf(chainId = CHAIN_ID): Promise { - const e = await searchName(HASH, 8, chainId).then(() => null, (e: unknown) => e) +async function errorOf(): Promise { + const e = await searchName(HASH, 8).then(() => null, (e: unknown) => e) expect(e).toBeInstanceOf(ApiError) return e as ApiError } @@ -81,7 +82,7 @@ describe("termsText", () => { it("asks the service for the terms by their hash and reads the text once it is the file their link names", async () => { const fetched = vi.fn(async () => new Response(JSON.stringify({ link: LINK, text: TEXT }), { status: 200 })) vi.stubGlobal("fetch", fetched) - await expect(termsText(terms, 1)).resolves.toBe(TEXT) + await expect(termsText(terms)).resolves.toBe(TEXT) expect((fetched.mock.calls[0] as unknown as [string])[0]).toBe(`/api/terms/${terms.hash}`) }) it("is no answer for another text or link, terms whose hash is not their link's, or a link the page does not take", async () => { @@ -90,14 +91,14 @@ describe("termsText", () => { [{ link: LINK, text: TEXT }, { ...terms, hash: zeroHash }], [{ link: LINK.replace("https:", "http:"), text: TEXT }, termsOf(LINK.replace("https:", "http:"))], ] as const) { answerWith(200, JSON.stringify(body)) - await expect(termsText(asked, 1), JSON.stringify(body)).rejects.toMatchObject({ code: "network" }) + await expect(termsText(asked), JSON.stringify(body)).rejects.toMatchObject({ code: "network" }) } }) it("passes the service's refusal, with its wait", async () => { answerWith(404, JSON.stringify({ type: "not_found" })) - await expect(termsText(terms, 1)).rejects.toMatchObject({ code: "not_found" }) + await expect(termsText(terms)).rejects.toMatchObject({ code: "not_found" }) answerWith(503, JSON.stringify({ type: "terms_unavailable" }), { "retry-after": "30" }) - await expect(termsText(terms, 1)).rejects.toMatchObject({ code: "terms_unavailable", retryAfter: 30 }) + await expect(termsText(terms)).rejects.toMatchObject({ code: "terms_unavailable", retryAfter: 30 }) }) }) @@ -140,6 +141,13 @@ describe("service errors", () => { expect((await errorOf()).code).toBe("order_exists") }) + it("reads the service's downtime, which refuses new orders, as its own refusal and not a gateway's failure", async () => { + answerWith(503, JSON.stringify({ type: "downtime" })) + const e = await createOrder({ labelHash: HASH, length: 8, duration: 1, owner: "0x1", commitment: HASH, sealed: "s", terms: HASH, timestamp: 1, signature: "0x", reveal: REVEAL }, "btc", 10000) + .then(() => null, (e: unknown) => e) + expect([(e as ApiError).code, (e as ApiError).status]).toEqual(["downtime", 503]) + }) + it("takes a refusal the page does not know as the service's own failure, or the network's under a gateway status", async () => { answerWith(409, JSON.stringify({ type: "weird" })) expect((await errorOf()).code).toBe("internal") @@ -188,7 +196,7 @@ describe("service errors", () => { for (const [edits, read] of [[{ left: 3 }, { left: 3, nextAt: null }], [{ left: 0, nextAt: "2027-10-23T00:00:00Z" }, { left: 0, nextAt: 1824249600 }], [{ left: 1, nextAt: "2027-10-23T00:00:00Z" }, { left: 1, nextAt: 1824249600 }]] as const) { answerWith(200, JSON.stringify({ found: { ...REGISTERED, records: { ...own, edits } } })) - expect(await searchName(HASH, 8, CHAIN_ID), JSON.stringify(edits)).toMatchObject({ found: { records: { ...own, edits: read } } }) + expect(await searchName(HASH, 8), JSON.stringify(edits)).toMatchObject({ found: { records: { ...own, edits: read } } }) } for (const edits of [{ left: 0 }, { left: -1 }, { left: 1.5 }, {}, { left: 2, nextAt: "soon" }, { left: 2, nextAt: 1824249600 }, 3, undefined]) { answerWith(200, JSON.stringify({ found: { ...REGISTERED, records: { ...own, edits } } })) @@ -211,7 +219,7 @@ describe("service errors", () => { } }) - const TERMS = termsOf(`${FORGEJO}/docs/general-terms.md#sha256=${"0b".repeat(32)}`) + const TERMS = LOCAL.generalTerms[0] const GROUP = { kind: "channel", displayName: "Alice", fullName: "Alice's news", subscribers: 12 } const channelPreview = (profile: Record = GROUP) => ({ kind: "channel", profile: { type: "ok", linkProfile: profile } }) const PREVIEW = channelPreview() @@ -223,14 +231,14 @@ describe("service errors", () => { it("passes a search answer the page can draw", async () => { const available = { type: "available", price: 10000, years: 2, terms: TERMS } answerWith(200, JSON.stringify({ found: available })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID)).toEqual({ found: available, community: null }) + expect(await searchName("ab".repeat(32), 8)).toEqual({ found: available, community: null }) answerWith(200, JSON.stringify({ found: { type: "available", price: 10000, years: 2 } })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID), "terms that can't be read now").toEqual({ found: { type: "available", price: 10000, years: 2, terms: null }, community: null }) + expect(await searchName("ab".repeat(32), 8), "terms that can't be read now").toEqual({ found: { type: "available", price: 10000, years: 2, terms: null }, community: null }) answerWith(200, registeredWith({ preview: PREVIEW, ...LINK })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID)).toEqual({ found: { ...REGISTERED, entities: [{ ...DRAWN, ...LINK }] }, community: null }) + expect(await searchName("ab".repeat(32), 8)).toEqual({ found: { ...REGISTERED, entities: [{ ...DRAWN, ...LINK }] }, community: null }) for (const type of ["taken", "reserved"]) { answerWith(200, JSON.stringify({ found: { type } })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID)).toEqual({ found: { type }, community: null }) + expect(await searchName("ab".repeat(32), 8)).toEqual({ found: { type }, community: null }) } }) @@ -252,14 +260,14 @@ describe("service errors", () => { for (const [kind, type] of [["contact", "address"], ["channel", "channel"]]) { for (const profile of ["unread", "unavailable"]) { answerWith(200, registeredWith({ preview: { kind, profile: { type: profile } }, ...LINK })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID), `${kind} ${profile}`).toMatchObject({ found: { entities: [{ type, kind, displayName: "", fullName: "", image: null, subscribers: null, profile, ...LINK }] } }) + expect(await searchName("ab".repeat(32), 8), `${kind} ${profile}`).toMatchObject({ found: { entities: [{ type, kind, displayName: "", fullName: "", image: null, subscribers: null, profile, ...LINK }] } }) } } // an address opens a contact, a business or a bot, as the service tells them apart const contactPreview = (kind: unknown) => ({ kind: "contact", profile: { type: "ok", linkProfile: { kind, displayName: "Alice", fullName: "" } } }) for (const kind of ["contact", "business", "bot"]) { answerWith(200, registeredWith({ preview: contactPreview(kind), ...LINK })) - expect(await searchName("ab".repeat(32), 8, CHAIN_ID), kind).toMatchObject({ found: { entities: [{ type: "address", kind, displayName: "Alice", subscribers: null, ...LINK }] } }) + expect(await searchName("ab".repeat(32), 8), kind).toMatchObject({ found: { entities: [{ type: "address", kind, displayName: "Alice", subscribers: null, ...LINK }] } }) } for (const kind of [undefined, "robot", 5]) { answerWith(200, registeredWith({ preview: contactPreview(kind), ...LINK })) @@ -277,6 +285,17 @@ describe("service errors", () => { expect(await checkCode("SN6-X")).toEqual({ state: "unused", minLength: 6, years: 2 }) }) + it("takes a code check only for the years a code may give", async () => { + for (const years of [LOCAL.minCodeYears, LOCAL.maxCodeYears]) { + answerWith(200, JSON.stringify({ state: "unused", minLength: 6, years })) + expect((await checkCode("SN6-X")).years).toBe(years) + } + for (const years of [LOCAL.minCodeYears - 1, LOCAL.maxCodeYears + 1]) { + answerWith(200, JSON.stringify({ state: "unused", minLength: 6, years })) + expect(((await checkCode("SN6-X").then(() => null, (e: unknown) => e)) as ApiError).code, String(years)).toBe("network") + } + }) + it("takes a success whose body was cut off as no answer", async () => { answerWith(200, '{"status":"avail') expect((await errorOf()).code).toBe("network") @@ -291,22 +310,38 @@ describe("service errors", () => { it("passes an invoice the page can draw, and takes one it cannot, or one that cannot be so, as no answer", async () => { answerWith(200, JSON.stringify(INVOICE)) - expect(await readInvoice("inv1")).toMatchObject({ invoiceId: "inv1", registration: { id: "r1" } }) + expect(await readInvoice("inv1", SIGN)).toMatchObject({ invoiceId: "inv1", registration: { id: "r1" } }) for (const body of [ {}, { ...INVOICE, registration: undefined }, { ...INVOICE, registration: { ...REGISTRATION, phase: { type: "lost" } } }, { ...INVOICE, status: "weird" }, { ...INVOICE, amount: "lots" }, { ...INVOICE, amount: -1 }, { ...INVOICE, cryptoAmount: "a lot" }, { ...INVOICE, registration: { ...REGISTRATION, years: 0 } }, { ...INVOICE, registration: { ...REGISTRATION, version: "4" } }, { ...INVOICE, registration: { ...REGISTRATION, phase: "unpaid" } }, + { ...INVOICE, cryptoCurrency: undefined, address: undefined, clientSecret: 42 }, ]) { answerWith(200, JSON.stringify(body)) - const e = await readInvoice("inv1").then(() => null, (e: unknown) => e) + const e = await readInvoice("inv1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, JSON.stringify(body).slice(0, 120)).toBe("network") } }) + it("keeps an address proof of either coin's shape, and drops one of another shape, which leaves the address unproven", async () => { + const btcProof = { type: "btc", keyTweak: "ab".repeat(32) } + const xmrProof = { type: "xmr", spendTweak: "cd".repeat(32), viewProof: { challenge: "ef".repeat(32), response: "01".repeat(32) } } + for (const addressProof of [btcProof, xmrProof]) { + answerWith(200, JSON.stringify({ ...INVOICE, addressProof })) + expect((await readInvoice("inv1", SIGN)).addressProof).toEqual(addressProof) + } + for (const addressProof of [null, "ab", { keyTweak: "ab" }, { type: "btc", keyTweak: 1 }, { ...xmrProof, viewProof: null }, { ...xmrProof, viewProof: { challenge: "ef" } }, { type: "eth" }]) { + answerWith(200, JSON.stringify({ ...INVOICE, addressProof })) + const read = await readInvoice("inv1", SIGN) + expect(read.addressProof, JSON.stringify(addressProof)).toBeUndefined() + expect(addressProven(read), JSON.stringify(addressProof)).toBe(false) + } + }) + it("takes an overpaid invoice's negative due as nothing left to pay, from every request that answers an invoice", async () => { const overpaid = { ...INVOICE, cryptoAmountPaid: "0.00256", cryptoAmountDue: "-0.001", paidInFull: true } const reads: [string, () => Promise][] = [ - ["a read", () => readInvoice("inv1")], ["a cancel", () => cancelInvoice("inv1")], + ["a read", () => readInvoice("inv1", SIGN)], ["a cancel", () => cancelInvoice("inv1", SIGN)], ] for (const [name, read] of reads) { answerWith(200, JSON.stringify(overpaid)) @@ -314,7 +349,7 @@ describe("service errors", () => { } for (const cryptoAmountDue of ["-", "--0.001", "-0.001x", "- 0.001"]) { answerWith(200, JSON.stringify({ ...overpaid, cryptoAmountDue })) - const e = await readInvoice("inv1").then(() => null, (e: unknown) => e) + const e = await readInvoice("inv1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, cryptoAmountDue).toBe("network") } }) @@ -324,7 +359,7 @@ describe("service errors", () => { it("passes what a late payment waits on", async () => { for (const waiting of ["confirming", "crediting", "support"]) { answerWith(200, JSON.stringify({ ...REGISTRATION, latePayment: waiting })) - expect((await readRegistration("r1")).latePayment).toEqual(waiting) + expect((await readRegistration("r1", SIGN)).latePayment).toEqual(waiting) } }) @@ -340,7 +375,7 @@ describe("service errors", () => { { type: "failed", reason: "monthEnded" }, { type: "failed", reason: "unread" }, ]) { answerWith(200, JSON.stringify({ ...REGISTRATION, phase })) - expect((await readRegistration("r1")).phase, JSON.stringify(phase)).toEqual(phase) + expect((await readRegistration("r1", SIGN)).phase, JSON.stringify(phase)).toEqual(phase) } for (const phase of [ { type: "closed" }, { type: "closed", closedBy: "paid" }, { type: "committed", revealAfter: 1, revealBefore: 2 }, committed({ type: "awaiting" }), @@ -348,7 +383,7 @@ describe("service errors", () => { { ...committed({ type: "signed" }), revealAfter: null }, { type: "registered" }, { type: "failed" }, { type: "failed", reason: "not_registered" }, { type: "failed", reason: "linksRefused" }, ]) { answerWith(200, JSON.stringify({ ...REGISTRATION, phase })) - const e = await readRegistration("r1").then(() => null, (e: unknown) => e) + const e = await readRegistration("r1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, JSON.stringify(phase)).toBe("network") } }) @@ -356,7 +391,7 @@ describe("service errors", () => { it("passes an order's balance and how it was paid, and takes either malformed as no answer", async () => { for (const payment of [{ type: "invoice", method: "btc" }, { type: "code" }]) { answerWith(200, JSON.stringify({ ...REGISTRATION, payment, balance: BALANCE })) - expect(await readRegistration("r1"), JSON.stringify(payment)).toMatchObject({ payment, balance: BALANCE }) + expect(await readRegistration("r1", SIGN), JSON.stringify(payment)).toMatchObject({ payment, balance: BALANCE }) } for (const change of [ { payment: undefined }, { payment: { type: "invoice" } }, { payment: { type: "invoice", method: "eth" } }, @@ -365,21 +400,59 @@ describe("service errors", () => { { latePayment: undefined }, { latePayment: {} }, { latePayment: "later" }, ]) { answerWith(200, JSON.stringify({ ...REGISTRATION, ...change })) - const e = await readRegistration("r1").then(() => null, (e: unknown) => e) + const e = await readRegistration("r1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, JSON.stringify(change)).toBe("network") } }) - it("holds a poll on the registration's version and the payment marks it has seen", async () => { + it("holds a poll on the registration's version and the payment marks it has seen, each read signed in its query", async () => { const fetched = vi.fn(async () => new Response(JSON.stringify(INVOICE), { status: 200 })) vi.stubGlobal("fetch", fetched) - const invoice = await readInvoice("inv1") - await readInvoice("inv1", seenOf({ ...invoice, cryptoAmountPaid: "0.5", paidInFull: true })) + const invoice = await readInvoice("inv1", SIGN) + await readInvoice("inv1", SIGN, seenOf({ ...invoice, cryptoAmountPaid: "0.5", paidInFull: true })) vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify(REGISTRATION), { status: 200 }))) - await readRegistration("r1", 4) - await readRegistration("r1", 0) + await readRegistration("r1", SIGN, 4) + await readRegistration("r1", SIGN, 0) const urls = [...fetched.mock.calls, ...(fetch as unknown as typeof fetched).mock.calls].map((c) => (c as unknown as [string])[0]) - expect(urls).toEqual(["/api/invoice/inv1", "/api/invoice/inv1?wait=open&seenVersion=4&seenPaid=0.5&seenFull=1", "/api/registration/r1?seenVersion=4", "/api/registration/r1?seenVersion=0"]) + expect(urls).toEqual(["/api/invoice/inv1?timestamp=7&signature=0xinv1read", "/api/invoice/inv1?timestamp=7&signature=0xinv1read&wait=open&seenVersion=4&seenPaid=0.5&seenFull=1", + "/api/registration/r1?timestamp=7&signature=0xr1read&seenVersion=4", "/api/registration/r1?timestamp=7&signature=0xr1read&seenVersion=0"]) + }) + + it("signs a cancel and a retry in their bodies, and signs once more when a refused timestamp set the clock", async () => { + const bodies: unknown[] = [] + const answers = [new Response(JSON.stringify({ type: "bad_request" }), { status: 400, headers: { date: new Date(Date.now() + 3_600_000).toUTCString() } }), + new Response(JSON.stringify(INVOICE), { status: 200 }), new Response(JSON.stringify(REGISTRATION), { status: 200, headers: { date: new Date().toUTCString() } })] + vi.stubGlobal("fetch", vi.fn(async (_: string, init: RequestInit) => { + bodies.push(JSON.parse(init.body as string)) + return answers.shift()! + })) + await cancelInvoice("inv1", SIGN) + await retry("r1", SIGN) + expect(bodies).toEqual([{ timestamp: 7, signature: "0xinv1cancel" }, { timestamp: 7, signature: "0xinv1cancel" }, { timestamp: 7, signature: "0xr1retry" }]) + }) + + it("signs a reveal's order request beside its fields, and signs once more when a refused timestamp set the clock", async () => { + const bodies: unknown[] = [] + const answers = [new Response(JSON.stringify({ type: "bad_request" }), { status: 400, headers: { date: new Date(Date.now() + 3_600_000).toUTCString() } }), + new Response("{}", { status: 200 })] + vi.stubGlobal("fetch", vi.fn(async (_: string, init: RequestInit) => { + bodies.push(JSON.parse(init.body as string)) + return answers.shift()! + })) + await reveal("r1", REVEAL, SIGN) + expect(bodies).toEqual([{ ...REVEAL, request: { timestamp: 7, signature: "0xr1reveal" } }, { ...REVEAL, request: { timestamp: 7, signature: "0xr1reveal" } }]) + }) + + it("sends a refused request of a device off by an hour once, when its answer's Date moved the clock by a second", async () => { + const at = (s: number) => ({ date: new Date(Date.now() + s * 1000).toUTCString() }) + const answers = [new Response(JSON.stringify(REGISTRATION), { status: 200, headers: at(3600) }), + new Response(JSON.stringify({ type: "bad_request" }), { status: 400, headers: at(3601) })] + const fetched = vi.fn(async () => answers.shift()!) + vi.stubGlobal("fetch", fetched) + await retry("r1", SIGN) + const e = await reveal("r1", REVEAL, SIGN).then(() => null, (e: unknown) => e) + expect((e as ApiError).code).toBe("bad_request") + expect(fetched).toHaveBeenCalledTimes(2) }) it("takes a link preview whose image is no image the page can show as no answer, and an image the service dropped as none", async () => { @@ -408,8 +481,8 @@ describe("service errors", () => { describe("terms and community names", () => { const COMMUNITY = { for: "bakers and pastry chefs", years: 2 } - const COMMUNITY_TERMS = termsOf(`${FORGEJO}/docs/community-terms.md#sha256=${"c7".repeat(32)}`) - const LOCAL_TERMS = termsOf(`http://127.0.0.1:8098/terms/${"c7".repeat(32)}.md#sha256=${"c7".repeat(32)}`) + const COMMUNITY_TERMS = LOCAL.communityTerms[2] + const LOCAL_TERMS = LOCAL.communityTerms[0] const SIGNED = `community/${COMMUNITY_TERMS.hash.slice(2)}` const OLDER_SIGNED = `2026-10-23/community/${"c7".repeat(32)}` const AVAILABLE = { found: { type: "available", price: 10000, years: 2, terms: COMMUNITY_TERMS }, community: COMMUNITY } @@ -446,10 +519,18 @@ describe("service errors", () => { { ...AVAILABLE, community: { years: 2 } }, { ...availableWith(TERMS), community: null }, availableWith(LOCAL_TERMS), ]) { answerWith(200, JSON.stringify(body)) - expect(await searchName(HASH, 6, CHAIN_ID), JSON.stringify(body)).toEqual(body) + expect(await searchName(HASH, 6), JSON.stringify(body)).toEqual(body) } answerWith(200, JSON.stringify({ found: REGISTERED })) - expect(await searchName(HASH, 6, CHAIN_ID), "a name off the community list").toEqual({ found: REGISTERED, community: null }) + expect(await searchName(HASH, 6), "a name off the community list").toEqual({ found: REGISTERED, community: null }) + }) + + it("reads the terms of an available answer as none unless they are the page's own terms of the name's kind", async () => { + const unheld = termsOf(`${FORGEJO}/docs/general-terms.md#sha256=${"0b".repeat(32)}`) + for (const body of [availableWith(TERMS), availableWith(LOCAL.generalTerms[1]), { ...availableWith(COMMUNITY_TERMS), community: null }, { ...availableWith(unheld), community: null }]) { + answerWith(200, JSON.stringify(body)) + expect((await searchName(HASH, 6)).found, JSON.stringify(body)).toEqual({ ...body.found, terms: null }) + } }) it("takes a community entry that cannot be so, or the available answer with terms whose link the page does not take or whose hash is not their link's, as no answer", async () => { @@ -457,26 +538,24 @@ describe("service errors", () => { { ...AVAILABLE, community: "bakers" }, { ...AVAILABLE, community: { ...COMMUNITY, for: 5 } }, { ...AVAILABLE, community: { ...COMMUNITY, for: "" } }, { ...AVAILABLE, community: { ...COMMUNITY, for: null } }, { ...AVAILABLE, community: { ...COMMUNITY, years: 0 } }, { ...AVAILABLE, community: { for: COMMUNITY.for } }, availableWith({ link: TERMS.link }), availableWith({ hash: TERMS.hash }), availableWith(null), availableWith({ ...TERMS, hash: COMMUNITY_TERMS.hash }), availableWith({ ...TERMS, hash: TERMS.hash.toUpperCase().replace("0X", "0x") }), - availableWith(termsOf(TERMS.link.replace("https:", "http:"))), availableWith(termsOf("https://simplex.chat/terms")), + availableWith(termsOf(COMMUNITY_TERMS.link.replace("https:", "http:"))), availableWith(termsOf("https://simplex.chat/terms")), { found: { type: "registered" } }, { community: COMMUNITY }, ]) { answerWith(200, JSON.stringify(body)) expect((await errorOf()).code, JSON.stringify(body)).toBe("network") } - answerWith(200, JSON.stringify(availableWith(LOCAL_TERMS))) - expect((await errorOf(1)).code, "terms on this machine, on another chain").toBe("network") }) it("passes an order's community entry and the terms it signed", async () => { const agreed = { communityName: true, termsHash: COMMUNITY_TERMS.hash } for (const change of [{ community: COMMUNITY, terms: agreed }, { community: null, terms: { communityName: false, termsHash: TERMS.hash } }]) { answerWith(200, JSON.stringify({ ...REGISTRATION, ...change })) - expect(await readRegistration("r1"), JSON.stringify(change)).toMatchObject(change) + expect(await readRegistration("r1", SIGN), JSON.stringify(change)).toMatchObject(change) } for (const change of [{ community: undefined }, { community: { ...COMMUNITY, for: 1 } }, { terms: undefined }, { terms: null }, { terms: SIGNED }, { terms: { ...agreed, communityName: "yes" } }, { terms: { ...agreed, termsHash: COMMUNITY_TERMS.hash.slice(2) } }, { terms: { communityName: true } }]) { answerWith(200, JSON.stringify({ ...REGISTRATION, ...change })) - const e = await readRegistration("r1").then(() => null, (e: unknown) => e) + const e = await readRegistration("r1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, JSON.stringify(change)).toBe("network") } }) @@ -487,20 +566,20 @@ describe("service errors", () => { signature: { type: "awaiting", toSign: { type: "read", intentNonce: 0, acceptance: accepted } } } }) for (const accepted of [acceptance, { ...acceptance, community: false, termsHash: TERMS.hash }]) { answerWith(200, JSON.stringify(withAcceptance(accepted))) - expect(await readRegistration("r1"), JSON.stringify(accepted)).toMatchObject(withAcceptance(accepted)) + expect(await readRegistration("r1", SIGN), JSON.stringify(accepted)).toMatchObject(withAcceptance(accepted)) } for (const accepted of [undefined, null, { ...acceptance, termsHash: "0x1" }, { ...acceptance, nonce: -1 }, { ...acceptance, nonce: 1.5 }, { ...acceptance, policy: 3 }, { ...acceptance, community: undefined }, { ...acceptance, community: "community" }]) { answerWith(200, JSON.stringify(withAcceptance(accepted))) - const e = await readRegistration("r1").then(() => null, (e: unknown) => e) + const e = await readRegistration("r1", SIGN).then(() => null, (e: unknown) => e) expect((e as ApiError).code, JSON.stringify(accepted)).toBe("network") } }) const SENDS: [string, () => Promise][] = [ - ["an order", () => createOrder(ORDER, "btc", 10000, 31337)], - ["a code order", () => registerWithCode(ORDER, "SN6-X", 31337)], - ["a selection", () => selectName("r1", ORDER, 31337)], + ["an order", () => createOrder(ORDER, "btc", 10000)], + ["a code order", () => registerWithCode(ORDER, "SN6-X")], + ["a selection", () => selectName("r1", ORDER)], ] it.each(SENDS)("sends %s with the terms the buyer agreed to and the reveal", async (_, send) => { @@ -514,7 +593,7 @@ describe("service errors", () => { }) it.each(SENDS)("gives %s refused for changed terms the terms of the name's kind and the community entry as they are now", async (_, send) => { - for (const [terms, community] of [[COMMUNITY_TERMS, COMMUNITY], [TERMS, null], [LOCAL_TERMS, null]] as const) { + for (const [terms, community] of [[COMMUNITY_TERMS, COMMUNITY], [TERMS, null], [LOCAL_TERMS, COMMUNITY]] as const) { answerWith(409, JSON.stringify({ type: "terms_changed", terms, community })) const e = await send().then(() => null, (e: unknown) => e) expect(e).toBeInstanceOf(TermsChanged) @@ -528,6 +607,26 @@ describe("service errors", () => { } }) + it.each(SENDS)("takes %s refused for changed terms as no answer unless they are the page's own terms of the name's kind", async (_, send) => { + const unheld = termsOf(`${FORGEJO}/docs/general-terms.md#sha256=${"0b".repeat(32)}`) + for (const [terms, community] of [[TERMS, COMMUNITY], [COMMUNITY_TERMS, null], [unheld, null]] as const) { + answerWith(409, JSON.stringify({ type: "terms_changed", terms, community })) + const e = await send().then(() => null, (e: unknown) => e) + expect((e as ApiError).code, JSON.stringify(terms)).toBe("network") + } + }) + + it.each(SENDS.filter(([name]) => name !== "a code order"))("takes %s refused for a changed price only at the price the page holds for the name's length", async (_, send) => { + const held = LOCAL.priceExceptions.find((e) => e.labelLength === ORDER.length)!.centsPerYear * LOCAL.paidYears + answerWith(409, JSON.stringify({ type: "catalog_changed", price: held })) + expect(await send().then(() => null, (e: unknown) => e)).toMatchObject({ code: "catalog_changed", body: { price: held } }) + for (const price of [held - 1, LOCAL.priceBaseCentsPerYear * LOCAL.paidYears, undefined]) { + answerWith(409, JSON.stringify({ type: "catalog_changed", price })) + const e = await send().then(() => null, (e: unknown) => e) + expect((e as ApiError).code, String(price)).toBe("network") + } + }) + it.each(SENDS)("passes %s refused while the terms can't be read, with the service's wait", async (_, send) => { answerWith(503, JSON.stringify({ type: "terms_unavailable" }), { "retry-after": "30" }) const e = await send().then(() => null, (e: unknown) => e) diff --git a/webapp/test/build.test.ts b/webapp/test/build.test.ts index 70a1c4e2..c73b774b 100644 --- a/webapp/test/build.test.ts +++ b/webapp/test/build.test.ts @@ -1,34 +1,102 @@ +import { createHash } from "node:crypto" +import { join } from "node:path" import { fileURLToPath } from "node:url" import { build, type Rollup } from "vite" import { describe, expect, it } from "vitest" +import { type Deployment, LOCAL, MAINNET } from "../src/config.ts" const ROOT = fileURLToPath(new URL("..", import.meta.url)) const STAND_IN_LABEL = "Test card form: no Stripe key is set, so Pay simulates a payment." const STRIPE_NOTE = "The card form is provided by Stripe. Your card will be charged only when you press Pay." const BUILD_MS = 120_000 -// the JavaScript a build of the page ships, in the mode given -async function shipped(mode: "development" | "production"): Promise { +// the JavaScript a build of the names page, or of the card page, ships, in the mode given +async function shipped(mode: "development" | "production" | "devchain", configFile?: string): Promise { const env = process.env.NODE_ENV // Vite takes NODE_ENV over the mode, and vitest's "test" would build development code - process.env.NODE_ENV = mode + process.env.NODE_ENV = mode === "development" ? mode : "production" try { - const outputs = await build({ root: ROOT, mode, logLevel: "silent", build: { write: false } }) as Rollup.RollupOutput | Rollup.RollupOutput[] + const outputs = await build({ ...configFile ? { configFile } : { root: ROOT }, mode, logLevel: "silent", build: { write: false } }) as Rollup.RollupOutput | Rollup.RollupOutput[] return [outputs].flat().flatMap((o) => o.output).map((file) => file.type === "chunk" ? file.code : "").join("\n") } finally { process.env.NODE_ENV = env } } +const CARD_CONFIG = join(ROOT, "card", "vite.config.ts") + +async function pageOf(mode: "production" | "devchain"): Promise { + const env = process.env.NODE_ENV + process.env.NODE_ENV = "production" + try { + const outputs = await build({ root: ROOT, mode, logLevel: "silent", build: { write: false } }) as Rollup.RollupOutput | Rollup.RollupOutput[] + const page = [outputs].flat().flatMap((o) => o.output).find((file) => file.fileName === "index.html")! + return page.type === "asset" ? String(page.source) : "" + } finally { + process.env.NODE_ENV = env + } +} +const inlineHashes = (html: string) => [...html.matchAll(/` // the same build's shell, served again after the worker kept it const NEWER_SHELL_HTML = `${SHELL_HTML}` @@ -52,7 +53,7 @@ class FakeNet { serve(path: string, status: number, body: string, redirected = false): void { this.routes.set(path, { status, body, redirected }) } readonly fetch = async (input: unknown, init?: unknown): Promise => { const url = keyOf(input) - const path = url.slice(ORIGIN.length) + const path = url.startsWith(`${ORIGIN}/`) ? url.slice(ORIGIN.length) : url const cache = (init as { cache?: string } | undefined)?.cache ?? (input instanceof FakeRequest ? input.cache : "default") this.requests.push({ path, init, cache }) if (this.offline) throw new TypeError("Failed to fetch") @@ -99,9 +100,11 @@ class FakeCache { class FakeCaches { readonly stores = new Map() + gate: Promise = Promise.resolve() private readonly net: FakeNet constructor(net: FakeNet) { this.net = net } async open(name: string) { + await this.gate if (!this.stores.has(name)) this.stores.set(name, new FakeCache(this.net)) return this.stores.get(name)! } @@ -170,6 +173,12 @@ describe("service worker routing", () => { expect(sw.strategyFor(new URL("/api/config", ORIGIN))).toBe("config") expect(sw.strategyFor(new URL("/apiary", ORIGIN))).toBe("bypass") }) + + it("takes the config from the API's own origin as its own, and leaves the API's other answers and other origins to the network", () => { + const { sw } = startWorker() + expect(sw.strategyFor(new URL("/api/config", API))).toBe("config") + for (const url of [`${API}/api/name/ab`, `${API}/api/configs`, "https://other.example/api/config"]) expect(sw.strategyFor(new URL(url)), url).toBe("bypass") + }) }) describe("service worker install and activate", () => { @@ -298,6 +307,27 @@ describe("service worker answers", () => { expect(await (await w.request("/api/config", "GET", "cors"))!.text(), "a failing service, the last answer").toBe(CODES_CONFIG) }) + it("answers the API origin's config from the network while it answers, and offline with its last answer", async () => { + const w = await installed() + w.net.serve(`${API}/api/config`, 200, CODES_CONFIG) + expect(await (await w.request(`${API}/api/config`, "GET", "cors"))!.text()).toBe(CODES_CONFIG) + await w.settled() + w.net.offline = true + expect(await (await w.request(`${API}/api/config`, "GET", "cors"))!.text(), "offline, the last answer").toBe(CODES_CONFIG) + }) + + it("keeps the config's answer that the page read before the cache opened", async () => { + const w = await installed() + let open!: () => void + w.caches.gate = new Promise((resolve) => { open = resolve }) + w.net.serve("/api/config", 200, CODES_CONFIG) + expect(await (await w.request("/api/config", "GET", "cors"))!.text()).toBe(CODES_CONFIG) + open() + await w.settled() + w.net.offline = true + expect(await (await w.request("/api/config", "GET", "cors"))!.text(), "offline, the answer read").toBe(CODES_CONFIG) + }) + it("answers the config with the service's error, or fails as the network, when it holds no earlier answer", async () => { const w = await installed() w.net.serve("/api/config", 503, "unavailable") @@ -351,7 +381,7 @@ describe("the build's worker", () => { const PUBLIC = new URL("../public/", import.meta.url).pathname // generateBundle as Vite calls it, on a bundle of the given file names const build = (files: { fileName: string; type: "chunk" | "asset"; isEntry?: boolean }[]) => { - const plugin = serviceWorker() as unknown as { configResolved(c: unknown): void; generateBundle(this: unknown, o: unknown, b: unknown): void } + const plugin = serviceWorker(API) as unknown as { configResolved(c: unknown): void; generateBundle(this: unknown, o: unknown, b: unknown): void } plugin.configResolved({ publicDir: PUBLIC }) let emitted = "" const context = { emitFile: (f: { fileName: string; source: string }) => { expect(f.fileName).toBe("sw.js"); emitted = f.source }, error: (m: string) => { throw new Error(m) } } diff --git a/webapp/test/terms-vectors.test.ts b/webapp/test/terms-vectors.test.ts index 8b623b43..f545a3b3 100644 --- a/webapp/test/terms-vectors.test.ts +++ b/webapp/test/terms-vectors.test.ts @@ -6,6 +6,7 @@ import { join } from "node:path" import { hashMessage, recoverMessageAddress, type Hex } from "viem" import { privateKeyToAccount } from "viem/accounts" import { afterEach, describe, expect, it, vi } from "vitest" +import { LOCAL } from "../src/config.ts" import { formatOwnerCode } from "../src/crypto/code.ts" import { commitmentSecret, labelHash, makeCommitment, YEAR_S } from "../src/crypto/registration.ts" import { seal, unseal } from "../src/crypto/seal.ts" @@ -30,7 +31,6 @@ const OWNER = RECORDED?.owner ?? "" const { label: LABEL, duration: DURATION, resolver: RESOLVER, registrationId: REGISTRATION_ID, timestamp: TIMESTAMP, labelHash: LABEL_HASH, commitment: COMMITMENT, sealed: SEALED, sealedHash: SEALED_HASH } = RECORDED?.order ?? { label: "", duration: 0, resolver: "", registrationId: "", timestamp: 0, labelHash: "", commitment: "", sealed: "", sealedHash: "" } const VECTORS: Vector[] = (RECORDED?.messages ?? []).flatMap((m) => m.kind === "find" || m.terms === null ? [] : [{ ...m, kind: m.kind, terms: m.terms }]) -const PLAIN = VECTORS.find((v) => !v.terms.startsWith("community/"))?.terms ?? "" // The contract's formats: `simplex.domains order `, // and for name the registration id after the kind. @@ -80,17 +80,19 @@ describe.skipIf(!RECORDED)("Appendix C vectors", () => { describe.skipIf(!RECORDED)("the page's builders reproduce Appendix C", () => { const YEARS = 2 - const CHAIN = { resolver: RESOLVER, sponsor: "0x9a676e781a523b5d0c0e43731313a708cb607508", chainId: 31337, tld: "simplex" } + const SPONSOR = "0x9a676e781a523b5d0c0e43731313a708cb607508" // the term's start that leaves the vector's free days at its timestamp const TERM_START = TIMESTAMP + DURATION - YEARS * YEAR_S const NO_LINKS = { contact: "", channel: "" } const vector = (kind: Kind, terms: string) => VECTORS.find((v) => v.kind === kind && v.terms === terms)! const TERMS = [...new Set(VECTORS.map((v) => v.terms))] + const COMMUNITY = "community/" + const heldOf = (community: boolean) => TERMS.filter((t) => t.startsWith(COMMUNITY) === community).map((t) => ({ hash: `0x${t.replace(COMMUNITY, "")}`, link: "" })) let sent: Record[] - const TO_SIGN = { type: "read", intentNonce: 0, acceptance: { community: false, policy: CHAIN.sponsor, termsHash: `0x${PLAIN}`, nonce: 0 } } - // the vector's clock and zero IV, storage for the order kept, and a service that answers a selection with its view - async function builders() { + // the vector's clock, zero IV and sealed order, storage for the order kept, and a service that answers a selection with its view + async function builders(terms: string) { + const toSign = { type: "read", intentNonce: 0, acceptance: { community: terms.startsWith(COMMUNITY), policy: LOCAL.namePolicy, termsHash: `0x${terms.replace(COMMUNITY, "")}`, nonce: 0 } } vi.useFakeTimers({ toFake: ["Date"], now: TIMESTAMP * 1000 }) vi.spyOn(crypto, "getRandomValues").mockImplementation((array) => array) const data = new Map() @@ -100,8 +102,7 @@ describe.skipIf(!RECORDED)("the page's builders reproduce Appendix C", () => { } }) sent = [] vi.stubGlobal("fetch", async (path: string, init?: RequestInit) => { - if (path === "/api/config") return new Response(JSON.stringify({ stripePublishableKey: null, names: { codesOnly: false, ...CHAIN, termStart: TERM_START } }), { status: 200 }) - if (path.startsWith(`/api/name/${LABEL_HASH}/sign?`)) return new Response(JSON.stringify(TO_SIGN), { status: 200 }) + if (path.startsWith(`/api/name/${LABEL_HASH}/sign?`)) return new Response(JSON.stringify(toSign), { status: 200 }) const body = JSON.parse(String(init?.body)) as Record sent.push(body) return new Response(JSON.stringify({ @@ -110,24 +111,31 @@ describe.skipIf(!RECORDED)("the page's builders reproduce Appendix C", () => { }), { status: 200 }) }) vi.resetModules() + vi.doMock("../src/config.ts", async (actual) => { + const config = await actual() + return { ...config, SITE: { ...config.LOCAL, resolver: RESOLVER, sponsor: SPONSOR, termStart: TERM_START, generalTerms: heldOf(false), communityTerms: heldOf(true) } } + }) + vi.doMock("../src/crypto/seal.ts", async (actual) => ({ ...await actual(), seal: async () => SEALED })) return { flow: await import("../src/flow.ts"), store: await import("../src/store.ts") } } afterEach(() => { + vi.doUnmock("../src/config.ts") + vi.doUnmock("../src/crypto/seal.ts") vi.useRealTimers() vi.unstubAllGlobals() }) - const draft = (terms: string) => ({ label: LABEL, links: NO_LINKS, chain: CHAIN, years: YEARS, termStart: TERM_START, ownerCode: OWNER_CODE, terms, method: "btc" as const }) + const draft = (terms: string) => ({ label: LABEL, links: NO_LINKS, years: YEARS, ownerCode: OWNER_CODE, terms, method: "btc" as const }) it.each(TERMS)("order with terms %s", async (terms) => { - const { flow } = await builders() + const { flow } = await builders(terms) const { request: { reveal, ...request } } = await flow.orderRequest(draft(terms)) expect(request).toEqual({ labelHash: LABEL_HASH, length: LABEL.length, duration: DURATION, owner: OWNER, commitment: COMMITMENT, sealed: SEALED, terms, timestamp: TIMESTAMP, signature: vector("order", terms).signature }) expect(reveal.label).toBe(LABEL) }) it.each(TERMS)("name with terms %s", async (terms) => { - const { flow, store } = await builders() + const { flow, store } = await builders(terms) const built = await flow.orderRequest(draft(terms)) const record = flow.recordFor(draft(terms), built, "btc", 10000, { registrationId: REGISTRATION_ID, invoiceId: "inv" }) store.saveOrder(record) diff --git a/webapp/tsconfig.json b/webapp/tsconfig.json index e9a6b1a2..4cea68ba 100644 --- a/webapp/tsconfig.json +++ b/webapp/tsconfig.json @@ -15,5 +15,5 @@ "noFallthroughCasesInSwitch": true, "skipLibCheck": true }, - "include": ["src", "test", "dev", "e2e", "sw", "vite.config.ts", "playwright.config.ts"] + "include": ["src", "card", "test", "dev", "e2e", "sw", "vite.config.ts", "playwright.config.ts"] } diff --git a/webapp/vite.config.ts b/webapp/vite.config.ts index f0e197a5..2571fdc3 100644 --- a/webapp/vite.config.ts +++ b/webapp/vite.config.ts @@ -1,16 +1,48 @@ /// -import { defineConfig } from "vite" +import { createHash } from "node:crypto" +import { defineConfig, loadEnv, type Plugin } from "vite" +import { type Deployment, LOCAL, MAINNET } from "./src/config.ts" import { serviceWorker } from "./sw/plugin.ts" const MOCK = process.env.MOCK_URL ?? "http://127.0.0.1:8099" -// README.md's production policy, so the e2e tests run with BASE_URL at the preview meet it -const CSP = "default-src 'self'; script-src 'self' 'sha256-i5ar+ITNdQiucbmin4/AN6DAY5LbAWeq3at+RiFoUoY=' 'sha256-lxURZtAGLIPkeIfIfFjl4UIJp4ElJWSbFqE1ktKB8hk=' 'sha256-djvAKNENifE9sLU9+NrLdzdGftMgCwpvCvH/MAbkElY=' https://js.stripe.com https://*.js.stripe.com; frame-src https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com; connect-src 'self' https://api.stripe.com; img-src 'self' data:; style-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'" -export default defineConfig({ +const siteOf = (mode: string): Deployment => mode === "production" ? MAINNET : { ...LOCAL, apiOrigin: loadEnv(mode, process.cwd(), "VITE_").VITE_API_ORIGIN ?? "" } + +const INLINE_SCRIPT = /