From aaf5d9cf1812ed0e7766af2a6a7cdee0649a60b8 Mon Sep 17 00:00:00 2001 From: tks98 <70284059+tks98@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:40:06 -0600 Subject: [PATCH 1/2] Close the holes a security review of main turned up R could run JavaScript on the app's page through webR's eval_js and through wasm modules loaded with dyn.load, so any program in any project could read the user's other projects. webR is now patched when it is copied in (the build stops if a patch no longer matches), and Opcode refuses an unpatched copy. The rest: - server.mjs: a long path no longer crashes it, folder redirects stay on the site, X-Forwarded-Host only counts with OPCODE_TRUST_PROXY=on, the app can't be framed, and the preview host page is sandboxed (OPCODE_APP_ORIGINS limits who may embed it). - wisp-server.mjs: only real host names reach a --via-proxy CONNECT line, a name learned from DNS is used only if the relay's own lookup agrees, the Wisp window is enforced and reading pauses when too much is waiting, and reused stream ids no longer leak sockets. - Preview: host frames are sandboxed and there is one per server, so a previewed page can't navigate the Opcode tab or see the next project's requests. The Linux bridge's response parser has limits and no longer loops on a negative chunk size. - ?machine= links ask first, aren't cached, and machine files are checked (header, unpacked size, v86 format) before they are saved. An offline machine's page-fetch adapter is turned off before it runs. - Zip import enforces real sizes, export leaves out unsafe names, and the editor mirrors at most 5,000 files and 50 MB. - Build: cached inputs are hashed again, Actions are pinned to commits, Docker publishing has its own job, base images and Alpine inputs are pinned. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 62 +++- .github/workflows/pages.yml | 16 +- Dockerfile | 11 +- compose.yaml | 7 +- deploy/preview-host.wrangler.toml | 3 +- docs/deploying.md | 8 +- docs/development.md | 2 +- docs/limitations.md | 3 +- docs/linux-and-docker.md | 2 +- docs/using-opcode.md | 2 +- public/_headers | 5 +- scripts/copy-npm-toolchains.mjs | 169 ++++++++-- scripts/fetch-csharp.mjs | 29 +- scripts/fetch-java.mjs | 34 +- scripts/fetch-rust.mjs | 25 +- scripts/preview-host.mjs | 73 +++- scripts/server.mjs | 105 +++++- scripts/wasmer-packages.mjs | 23 +- scripts/wisp-server.mjs | 282 +++++++++++++--- src/App.svelte | 95 ++++-- src/lib/components/ConfirmDialog.svelte | 55 +++ src/lib/linux/LinuxMachine.svelte.js | 70 ++-- src/lib/linux/httpBridge.js | 405 +++++++++++++++++++---- src/lib/linux/machineFile.js | 123 ++++++- src/lib/paths.js | 14 +- src/lib/runtime/ProjectSandbox.svelte.js | 84 +++-- src/lib/runtime/rlang.js | 9 + src/lib/runtime/shell.js | 15 + src/lib/runtime/toolchains.js | 198 ++++++++++- src/lib/runtime/wasmer.js | 3 + src/lib/runtime/wasmerMirror.js | 30 +- src/lib/runtime/workspaceSync.js | 58 +++- src/lib/stores/linux.svelte.js | 19 +- src/lib/stores/preview.svelte.js | 33 +- src/lib/stores/projects.svelte.js | 25 +- tests/e2e/linux.spec.js | 9 +- tests/httpBridge.test.js | 108 +++++- tests/rlang.test.js | 11 +- tests/security-guest-sync.test.js | 174 ++++++++++ tests/security-guest-webr.test.js | 153 +++++++++ tests/security-inputs.test.js | 289 ++++++++++++++++ tests/security-preview.test.js | 47 +++ tests/server.test.js | 64 +++- tests/wasmerMirror.test.js | 55 ++- tests/wisp-server.test.js | 276 ++++++++++++++- toolchains/linux/build.sh | 42 ++- toolchains/linux/fetch-images.mjs | 55 ++- vercel.json | 3 +- 48 files changed, 3006 insertions(+), 377 deletions(-) create mode 100644 src/lib/components/ConfirmDialog.svelte create mode 100644 tests/security-guest-sync.test.js create mode 100644 tests/security-guest-webr.test.js create mode 100644 tests/security-inputs.test.js create mode 100644 tests/security-preview.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37f23e5..60272ec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,13 +17,15 @@ jobs: name: Check, test and build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm - run: npm ci - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The JDK scripts/fetch-java.mjs builds Java's runtime files from (~210 MB), # and the NuGet packages scripts/fetch-csharp.mjs builds C#'s from. @@ -31,7 +33,7 @@ jobs: node_modules/.cache/opcode-java node_modules/.cache/opcode-csharp key: toolchains-${{ hashFiles('scripts/fetch-java.mjs', 'scripts/fetch-csharp.mjs') }} - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The Wasmer packages the terminals run (scripts/wasmer-packages.mjs, ~255 MB). path: public/wasmer @@ -46,13 +48,15 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm - run: npm ci - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The JDK scripts/fetch-java.mjs builds Java's runtime files from (~210 MB), # and the NuGet packages scripts/fetch-csharp.mjs builds C#'s from. @@ -60,14 +64,14 @@ jobs: node_modules/.cache/opcode-java node_modules/.cache/opcode-csharp key: toolchains-${{ hashFiles('scripts/fetch-java.mjs', 'scripts/fetch-csharp.mjs') }} - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The Wasmer packages the terminals run (scripts/wasmer-packages.mjs, ~255 MB). path: public/wasmer key: wasmer-packages-${{ hashFiles('wasmer-packages.lock.json') }} - run: npx playwright install --with-deps chromium - run: npm run test:e2e - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 if: failure() with: name: playwright-results @@ -80,13 +84,12 @@ jobs: needs: [check, e2e] runs-on: ubuntu-latest timeout-minutes: 30 - permissions: - contents: read - packages: write # to publish it, from main steps: - - uses: actions/checkout@v4 - - uses: docker/setup-buildx-action@v3 - - uses: docker/build-push-action@v6 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 + - uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2 with: context: . load: true @@ -102,13 +105,36 @@ jobs: curl -sfI -H 'Accept-Encoding: br' "http://localhost:8080/assets/$llvm" | grep -i '^content-encoding: br' - if: failure() run: docker logs opcode - # What's on main is published as ghcr.io//:latest - # (and :sha-), which compose.yaml runs. + # The image the publish job pushes, tested above (only from main). + - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + run: docker save opcode:ci -o opcode.tar + - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: docker-image + path: opcode.tar + retention-days: 1 + + publish: + # What's on main is published as ghcr.io//:latest + # (and :sha-), which compose.yaml runs. A job of its own, so the + # token that can write packages never reaches the build or its actions. + name: Publish the Docker image + needs: [check, e2e, docker] + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + packages: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: docker-image - name: Publish to GitHub's container registry - if: github.event_name == 'push' && github.ref == 'refs/heads/main' env: TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | + docker load -i opcode.tar image=ghcr.io/${GITHUB_REPOSITORY,,} echo "$TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin for tag in latest "sha-${GITHUB_SHA::7}"; do diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 5d3a4ea..a6df8f5 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -24,13 +24,15 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm - run: npm ci - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The JDK scripts/fetch-java.mjs builds Java's runtime files from (~210 MB), # and the NuGet packages scripts/fetch-csharp.mjs builds C#'s from. @@ -38,7 +40,7 @@ jobs: node_modules/.cache/opcode-java node_modules/.cache/opcode-csharp key: toolchains-${{ hashFiles('scripts/fetch-java.mjs', 'scripts/fetch-csharp.mjs') }} - - uses: actions/cache@v4 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # The Wasmer packages the terminals run (scripts/wasmer-packages.mjs, ~255 MB). path: public/wasmer @@ -47,8 +49,8 @@ jobs: env: # A Cloudflare Worker: deploy/preview-host.wrangler.toml. VITE_PREVIEW_HOST: https://preview.opcode-dev.com/ - - uses: actions/configure-pages@v5 - - uses: actions/upload-pages-artifact@v3 + - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0 + - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3.0.1 with: path: dist @@ -64,4 +66,4 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4.0.5 diff --git a/Dockerfile b/Dockerfile index 4959932..8d44b1f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1 +# syntax=docker/dockerfile:1@sha256:572cebbc2b15e6f84c077742952674889cb63cd5e9b80abdffcbe587b6f19183 # # Opcode, ready to deploy: the app, its web preview host and an optional # internet relay, served by one small Node server (scripts/server.mjs). @@ -13,7 +13,12 @@ # The build. The toolchains `npm run build` downloads (pinned and checksummed: # Rust, a JDK for Java, NuGet packages for C#, the Wasmer packages) are cached # between builds. -FROM node:22-bookworm-slim AS build +# +# The base images (and the syntax line above) are pinned by digest, so a +# build uses exactly what was tested. To update one, take the digest from +# `docker buildx imagetools inspect node:22-bookworm-slim` (or node:22-alpine, +# docker/dockerfile:1). +FROM node:22-bookworm-slim@sha256:e9f565d32859f0cbfb52125eafe8be39390f24dac302dc3cdf566e8ba3ab21ee AS build WORKDIR /opcode # Stop if a toolchain can't be downloaded, rather than build without it. ENV CI=1 @@ -28,7 +33,7 @@ RUN --mount=type=cache,target=/opcode/node_modules/.cache \ && node scripts/precompress.mjs dist dist-compressed # What runs: Node, the server (whose relay needs the ws package) and the build. -FROM node:22-alpine +FROM node:22-alpine@sha256:1314fb30ec37592d5845e5a160d522c0e680972aa534549940b8d73bde88481a LABEL org.opencontainers.image.title="Opcode" \ org.opencontainers.image.description="A browser IDE with a real terminal, running on WebAssembly" \ org.opencontainers.image.source="https://github.com/tks98/opcode" \ diff --git a/compose.yaml b/compose.yaml index b1d16d4..14fb146 100644 --- a/compose.yaml +++ b/compose.yaml @@ -8,7 +8,10 @@ # OPCODE_DOMAIN=opcode.example.com docker compose up -d # # It runs the image published from this repository's main branch -# (`docker compose pull` updates it). To run your own build instead: +# (`docker compose pull` updates it). To stay on one tested build instead, +# use its :sha- tag (each push to main publishes one next to +# :latest), or pin a digest: ghcr.io/tks98/opcode@sha256:... To run your own +# build instead: # `docker build -t ghcr.io/tks98/opcode .` first. # # Add OPCODE_RELAY=on to give terminals and Linux machines internet access @@ -20,6 +23,8 @@ services: restart: unless-stopped environment: OPCODE_PREVIEW_HOST: https://preview.${OPCODE_DOMAIN:?set OPCODE_DOMAIN to your domain}/ + # Only the site's own pages may embed its preview host. + OPCODE_APP_ORIGINS: https://${OPCODE_DOMAIN} OPCODE_RELAY: ${OPCODE_RELAY:-off} OPCODE_RELAY_ARGS: ${OPCODE_RELAY_ARGS:-} diff --git a/deploy/preview-host.wrangler.toml b/deploy/preview-host.wrangler.toml index 4c09bac..c93065b 100644 --- a/deploy/preview-host.wrangler.toml +++ b/deploy/preview-host.wrangler.toml @@ -1,6 +1,7 @@ # opcode-dev.com's web preview host: a Cloudflare Worker on its own domain # (see docs/deploying.md, "Web preview host"). Deploy it with -# npm run build:preview-host && npx wrangler deploy -c deploy/preview-host.wrangler.toml +# OPCODE_APP_ORIGINS=https://opcode-dev.com npm run build:preview-host && npx wrangler@4.158.0 deploy -c deploy/preview-host.wrangler.toml +# (OPCODE_APP_ORIGINS: only the app's own pages may then use the host) # and again after updating @wasmer/sdk, whose files it serves. For your own # site, change the name and the domain. name = "opcode-preview" diff --git a/docs/deploying.md b/docs/deploying.md index bd66ccb..f1ac0f7 100644 --- a/docs/deploying.md +++ b/docs/deploying.md @@ -26,6 +26,8 @@ The image is configured with environment variables (`docker run -e`, or `environ | `OPCODE_RELAY` | `off` | `on` gives terminals and Linux machines internet access through a relay on this server, at `/wisp/` (read [Internet relay](deploying.md#internet-relay) first). A `wss://` address uses that relay instead. With `off`, users can still pick a relay in the *Internet* settings. | | `OPCODE_RELAY_ARGS` | | The built-in relay's options, as `scripts/wisp-server.mjs` takes them: `--max-streams 32 --via-proxy http://proxy:3128` | | `OPCODE_RELAY_ORIGINS` | | Other sites whose pages may use the built-in relay (comma-separated). Pages of this site always may. | +| `OPCODE_APP_ORIGINS` | | The site's own address (`https://opcode.example.com`; comma-separate several). Only its pages may then embed the preview host served here. `compose.yaml` sets it. | +| `OPCODE_TRUST_PROXY` | `off` | `on` reads the host name from `X-Forwarded-Host`. Only for a proxy that sets that header itself and replaces any the client sent; Caddy, as in `compose.yaml`, passes `Host` on and doesn't need it. | | `OPCODE_PREVIEW_HOST` | Wasmer's host | Serve the [web preview host](deploying.md#web-preview-host) here, to requests for that address: `https://preview.example.com/`, or `https://*.preview.example.com/` for one address per server (needs wildcard DNS and a wildcard certificate, which `compose.yaml`'s Caddy can't get by itself). Set it: Wasmer's host doesn't work at the moment (see [Web preview host](deploying.md#web-preview-host)). `compose.yaml` sets it to `preview.` your domain. | Everything on one computer, with an address for each preview (Chrome and Firefox resolve every `*.localhost` name without DNS): @@ -70,7 +72,7 @@ VITE_WISP_URL=wss://relay.your-site/ npm run build (or set `relay: 'wss://relay.your-site/'` in `config.js`; the Docker image can also run the relay itself, with `OPCODE_RELAY=on`). -It listens on `127.0.0.1` unless given `--host`. Reachable from the internet, it is an open relay: `--origin` only stops other websites' pages from using it (any other program can send the header it expects), so run it where outgoing traffic from strangers is acceptable. It refuses private and local addresses (your network, cloud metadata endpoints) and outgoing mail ports by default (`--allow-private`, `--block-ports 25,465,587`), and limits streams per connection (`--max-streams`). `--via-proxy http://proxy:3128` sends connections through an HTTP proxy. Students or teachers can also point a copy of Opcode at a relay in the *Internet* settings in the status bar (saved in their browser). `npm run relay` starts one locally on port 8090 for development (`VITE_WISP_URL=ws://localhost:8090/ npm run dev`). +It listens on `127.0.0.1` unless given `--host`. Reachable from the internet, it is an open relay: `--origin` only stops other websites' pages from using it (any other program can send the header it expects), so run it where outgoing traffic from strangers is acceptable. It refuses private and local addresses (your network, cloud metadata endpoints) and outgoing mail ports by default (`--allow-private`, `--block-ports 25,465,587`), and limits streams per connection (`--max-streams`). `--via-proxy http://proxy:3128` sends connections through an HTTP proxy; the proxy is given host names and looks them up itself, so the relay's check of private addresses can't bind it: give the proxy its own rules against private, local and metadata addresses. A client that sends more than the Wisp protocol's window allows has that connection closed. Students or teachers can also point a copy of Opcode at a relay in the *Internet* settings in the status bar (saved in their browser). `npm run relay` starts one locally on port 8090 for development (`VITE_WISP_URL=ws://localhost:8090/ npm run dev`). The production build includes the Wasmer SDK's own dependency for this, the Wisp client [`@mercuryworkshop/wisp-js`](https://github.com/MercuryWorkshop/wisp-client-js) (AGPL-3.0 in the version the SDK uses), bundled as `wasmer-sdk/deps/wisp-client.js`. @@ -78,7 +80,9 @@ The production build includes the Wasmer SDK's own dependency for this, the Wisp The preview reaches servers inside the sandbox through a service worker on a separate origin. A server owns that whole origin, so one origin can show one server at a time. Opcode's default is Wasmer's `https://default.local.wasmer.site/`, but as of October 2026 that host no longer serves the page the preview loads (`/.wasmer/host.html` answers 404), so the preview only works with a host of your own. opcode-dev.com's is `https://preview.opcode-dev.com/`. -To host your own, run `npm run build:preview-host` and deploy `dist-preview-host/` to an origin other than the app's (it includes `_headers`, and `.nojekyll` for GitHub Pages): +To host your own, run `npm run build:preview-host` and deploy `dist-preview-host/` to an origin other than the app's (it includes `_headers`, and `.nojekyll` for GitHub Pages; the app refuses a preview host on its own origin, where a previewed page could read the user's projects). Build it with `OPCODE_APP_ORIGINS=https://opcode.example.com` (comma-separate several) and only that site's pages can use the host; without it, any site can. + +Pages a previewed server serves run on the host's origin. The host's own page is sandboxed so they can't navigate the Opcode tab through it, and each server is routed through a page of its own, so one project's pages don't see the next project's requests. With one origin they still share its cookies and storage: where people preview projects they didn't write, use a wildcard origin. - **One origin** (one preview at a time): build the app with `VITE_PREVIEW_HOST=https://preview.example.com/ npm run build` (or set `previewHost` in `config.js`; the Docker image serves the host itself, with `OPCODE_PREVIEW_HOST`). On Cloudflare, `dist-preview-host/worker.js` serves it as a Worker on its own domain: `deploy/preview-host.wrangler.toml` is opcode-dev.com's. - **A wildcard origin** (one address per server, any number at once): serve the same files on every subdomain, with wildcard DNS and a wildcard certificate, and build with `VITE_PREVIEW_HOST=https://*.preview.example.com/ npm run build`. Each server gets a random name such as `https://p3k9x0q2m.preview.example.com/`. On Cloudflare, deploy `dist-preview-host/worker.js` as a Worker routed to `*.preview.example.com/*` (it holds the files itself). diff --git a/docs/development.md b/docs/development.md index 32b4d4b..6670c28 100644 --- a/docs/development.md +++ b/docs/development.md @@ -95,7 +95,7 @@ scripts/fetch-rust.mjs # Downloads the Rust toolchain (pinned, checksum scripts/wasmer-packages.mjs # Locks and downloads the Wasmer packages (wasmer-packages.lock.json) scripts/fetch-java.mjs # Builds Java's runtime files from a pinned Corretto JDK scripts/fetch-csharp.mjs # Builds the C# toolchain from pinned NuGet packages -scripts/copy-npm-toolchains.mjs # Copies Ruby, TypeScript and webR (R) from their pinned npm packages +scripts/copy-npm-toolchains.mjs # Copies Ruby, TypeScript and webR (R) from their pinned npm packages; patches webR so R can't run JavaScript scripts/make-mono-font.py # Builds the Recursive Mono code font scripts/preview-host.mjs # Builds/serves a self-hosted web preview host (and its Cloudflare Worker) scripts/wisp-server.mjs # Internet relay (Wisp + DNS-over-HTTPS) diff --git a/docs/limitations.md b/docs/limitations.md index 7ea3abc..90aa7dd 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -11,7 +11,7 @@ - **Go** runs on an interpreter. The standard library works, but third-party modules and `go build` don't. - **Java** is Java 21 (javac is JDK 21's), and the JVM is Ristretto, not HotSpot: it interprets bytecode (a loop of 10 million steps takes about a second), and APIs that need native code it doesn't provide, such as Swing and other GUI classes, throw `UnsatisfiedLinkError`. Only `java.base` is included, so `java.sql`, `java.net.http` and other modules aren't available. - **C#** runs .NET 8's class libraries on an interpreter (no JIT): no `Task.Run`, `Task.Delay` or other waiting (the runtime has no thread pool or timers), no NuGet packages or networking, and stack traces don't show line numbers. -- **R** scripts can't read keyboard input (`readline()` returns `""`, as in Rscript), and only packages built for webR install. Plots are PNG images (800×600). +- **R** scripts can't read keyboard input (`readline()` returns `""`, as in Rscript), and only packages built for webR install. R can't run JavaScript: `webr::eval_js()` gives an error, and packages that bring their own JavaScript don't load (R runs on Opcode's own pages, where JavaScript could read every project). Plots are PNG images (800×600). - **Ruby** is 3.2, without `irb` (the build has no `io/console`); gems that need C extensions can't be installed. - **Lua** has no `os.execute`, `io.popen` or temporary files (WASI doesn't provide them). - **TypeScript**'s type errors show when `tsc` runs, not in the editor; the type definitions of packages in `node_modules` are used, but `npm install` itself depends on Node.js (Edge.js). @@ -21,5 +21,6 @@ - **Terminal size**: resizing interrupts programs waiting for input on WASIX, so a new size is applied when the shell returns to its prompt. - **Web pages' console**: `console.log` and errors from a page show in the browser's developer tools (open the page in its own tab with ↗), not in Opcode's terminal. - **Files the terminal creates that aren't text** (such as compiled programs) live only in the running session; they aren't saved or exported. +- **Files the editor doesn't show**: the editor mirrors up to 5,000 files and 50 MB of a project's text files (each up to 1 MB). Files past that, and files whose names a project can't use (a backslash, `..`, control characters, `<>:"|?*`), stay in the terminal only; the terminal says so once. - **Browsers**: works in current Chrome, Edge, Firefox and Safari. Safari needs version 27 or later (iOS and iPadOS 27 on iPhone and iPad), for the Wasmer SDK. - **iPhone and iPad** (every browser there uses Safari's engine): programs that don't set their own memory limit (most, including Bash and Python) can use up to 64 MiB, because iOS lets a page reserve only a few GiB of WebAssembly memory in all; a program that needs more stops with its own out-of-memory error. Rust's compiler sets its own (1 GiB) and keeps it. Python, Bash, Java and Rust are tested there; C and C++, Go and the others are not yet. See [the iPhone and iPad plan](plans/ios.md). diff --git a/docs/linux-and-docker.md b/docs/linux-and-docker.md index b9b51a9..9b8135e 100644 --- a/docs/linux-and-docker.md +++ b/docs/linux-and-docker.md @@ -13,7 +13,7 @@ Pick **Learn the Linux terminal** on the start screen to get a real Linux comput - **Starts in about 2 seconds**: the app ships a snapshot of the booted machine (~42 MB, downloaded once and cached) - **Web preview**: a web server started in the machine (`python3 -m http.server` after `sudo apk add python3`, say) opens in the preview, as in other projects - **Saved automatically**: the whole machine (files, history, even running programs) is stored in your browser and resumes where you left off. *Reset machine* starts fresh. Because the system runs from memory, `sudo reboot` also starts a fresh machine, as it would on a live USB stick. -- **Download and share machines**: *Download* saves the machine to an `.opcode-linux` file (a copy to keep, hand in, or share). *Open a file* (on the start screen, or in the *More* menu) opens one as a new project. A teacher can prepare a machine, put the file online, and share a link: `https://your-opcode-site/?machine=https://…/lab-1.opcode-linux` opens it for each student (the file's server must allow cross-origin requests; a file next to the app works with a relative path, `?machine=labs/lab-1.opcode-linux`). Files open in the same Opcode version's emulator they were saved with. +- **Download and share machines**: *Download* saves the machine to an `.opcode-linux` file (a copy to keep, hand in, or share). *Open a file* (on the start screen, or in the *More* menu) opens one as a new project. A teacher can prepare a machine, put the file online, and share a link: `https://your-opcode-site/?machine=https://…/lab-1.opcode-linux` asks each student whether to open the machine from that site, then opens it (the link must be an `http` or `https` address, and the file's server must allow cross-origin requests; a file next to the app works with a relative path, `?machine=labs/lab-1.opcode-linux`). Files open in the same Opcode version's emulator they were saved with. You log in as `student` (password `student`). With a relay set up (see [Deploying](deploying.md#internet-relay)) the machine is online: `curl`, `git clone`, `ssh`, and `sudo apk add` for anything in Alpine's repositories. `ping` doesn't work (the relay carries TCP and UDP, not ICMP). The tutorial asks Opcode to save the machine after each lesson, and `opcode-save` does so from the command line. diff --git a/docs/using-opcode.md b/docs/using-opcode.md index b9d2835..68586cc 100644 --- a/docs/using-opcode.md +++ b/docs/using-opcode.md @@ -15,7 +15,7 @@ Open Opcode and pick a language: the starter program is one click on **Run** awa - **Web pages**: HTML, CSS and JavaScript projects. Run serves the folder (`serve` in the terminal) and opens the page in the preview, which updates as you type - **`code `** in the terminal opens (or creates) a file in the editor, like VS Code - **Files stay in sync both ways**: edits go to the terminal immediately, and files the terminal creates, changes or deletes show up in the editor (compiled programs appear greyed out) -- **Folders**: nested folders, rename and move, drag-and-drop or upload files, ZIP import and export +- **Folders**: nested folders, rename and move, drag-and-drop or upload files, ZIP import and export (up to 2,000 files and 50 MB at a time) - **Monaco editor**: VS Code's editor, with per-file undo history and syntax highlighting for dozens of languages - **Internet access** (with a relay, see [Deploying](deploying.md#internet-relay)): `pip install`, `git clone`, `curl` and API calls work from terminals and Linux machines. The status bar shows *Internet: on*/*off* and opens the settings. - **Web preview**: start a server in the terminal (`python3 -m http.server`, `php -S localhost:8000`, a Node or Flask app, or `docker run -p 8080:80 nginx` on a Docker machine) and its page opens in a preview panel beside the editor. R's plots show there too. It follows the server as you stop and restart it, and `http://localhost:…` links in the terminal open there too. With a [wildcard preview host](deploying.md#web-preview-host), every server gets its own address, so several can run and be previewed (or opened in their own tabs) at once. diff --git a/public/_headers b/public/_headers index a0ee6dd..e828d9f 100644 --- a/public/_headers +++ b/public/_headers @@ -1,5 +1,8 @@ # Netlify / Cloudflare Pages: Opcode's WebAssembly runtime needs a -# cross-origin isolated page (SharedArrayBuffer). +# cross-origin isolated page (SharedArrayBuffer). No other site may frame the +# app (clickjacking); previews are framed from the preview host, which has its +# own headers (scripts/preview-host.mjs). /* Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp + Content-Security-Policy: frame-ancestors 'none' diff --git a/scripts/copy-npm-toolchains.mjs b/scripts/copy-npm-toolchains.mjs index 9b5c708..878bda8 100644 --- a/scripts/copy-npm-toolchains.mjs +++ b/scripts/copy-npm-toolchains.mjs @@ -11,14 +11,15 @@ // (which it uses), as { path: text } at the paths runtime/tscRunner.js // gives them // public/toolchains/webr/ webR (R compiled to WebAssembly) as published: -// R.wasm, its worker and the R library it loads files of on demand. One -// change: its worker decompresses the library's .data.gz files only if -// they are still compressed (hosts, Vite's dev server among them, may -// serve them with Content-Encoding: gzip, which the browser undoes). +// R.wasm, its worker and the R library it loads files of on demand. Its +// scripts are patched: R can't run JavaScript (see patchWebrWorkerSource +// and below), and the worker decompresses the library's .data.gz files +// only if they are still compressed (hosts, Vite's dev server among them, +// may serve them with Content-Encoding: gzip, which the browser undoes). // // Usage: node scripts/copy-npm-toolchains.mjs [--force] -import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs' import { dirname, join, relative } from 'node:path' import { fileURLToPath } from 'node:url' import { gzipSync } from 'node:zlib' @@ -55,36 +56,140 @@ const COPIES = [ { output: 'typescript/types.json.gz', packages: ['typescript', '@types/node', 'undici-types'], bytes: typesBundle }, ] -// Directories copied (their files load on demand), with small patches. -const GZIP_CHECK = /(\w)\.gzip&&\((\w)=(\w+)\(\2\)\.buffer\)/g -function patchWebrWorker(dir) { - const file = join(dir, 'webr-worker.js') - const source = readFileSync(file, 'utf8') - const patched = source.replace(GZIP_CHECK, (_, metadata, data, inflate) => `${metadata}.gzip&&new Uint8Array(${data})[0]===31&&new Uint8Array(${data})[1]===139&&(${data}=${inflate}(${data}).buffer)`) - if (patched === source) throw new Error('webr-worker.js changed: update patchWebrWorker()') - writeFileSync(file, patched) +// Directories copied (their files load on demand), with patches. + +// webR lets R code run JavaScript (webr::eval_js, and wasm modules it loads +// with dyn.load). Its worker and the page that starts it are on the app's +// origin, so that would give any program in any project the user's other +// projects. These patches close every way we found; each one fails the build +// if webR changes and its pattern no longer matches, and a final check fails +// it if any eval is left over. +const NO_JS = 'eval_js is not available in Opcode' +const throwNoJs = `throw new Error(${JSON.stringify(NO_JS)})` + +// Replace exactly `count` matches of `pattern` in `source`, or throw. +function replaceExactly(source, pattern, replacement, count, what) { + const all = new RegExp(pattern.source, `${pattern.flags.replace('g', '')}g`) + const found = source.match(all)?.length ?? 0 + if (found !== count) throw new Error(`webR changed (${what}: ${found} matches, expected ${count}): update the patches in scripts/copy-npm-toolchains.mjs`) + return source.replace(all, replacement) +} + +// Every eval left in a patched file, outside the allowed ones. +const EVAL = /(? `${metadata}.gzip&&new Uint8Array(${data})[0]===31&&new Uint8Array(${data})[1]===139&&(${data}=${inflate}(${data}).buffer)`, 2, 'gzip check') + // webr::eval_js: both the worker's own eval and the one it asks the page + // for ("eval-await") raise an R error instead. + out = replaceExactly(out, /(evalJs:\((\w+),\w+=!1\)=>\{try\{let (\w+)=null;)if\(\w+\)\{let \w+=\w+\?\.syncRequest\(\{type:"eval-await",data:\w+\.UTF8ToString\(\2\)\}\);[^]*?else \3=\(0,eval\)\(\w+\.UTF8ToString\(\2\)\);/, (_, head) => `${head}${throwNoJs};`, 1, 'evalJs') + // Once R has started (and loaded webR's own module, the only one with + // embedded JavaScript), before any of the program's code runs, modules + // loaded later may not bring any: see patchRSource. + out = replaceExactly(out, /(resolveInit:\(\)=>\{[^]*?)(\w+\?\.resolve\(\),\w+=!0\},setPrompt:)/, (_, head, tail) => `${head}globalThis.Module.opcodeSealed=!0,${tail}`, 1, 'resolveInit') + // Nothing in R needs IndexedDB or the Cache API, and the app keeps its + // projects and downloads there: take them out of the worker (R's IDBFS + // mounts and emscripten_idb_* then fail). + out = replaceExactly(out, /^"use strict";/, '"use strict";for(const k of["indexedDB","caches"])try{Object.defineProperty(globalThis,k,{value:void 0,configurable:!1})}catch{};', 1, 'prologue') + assertNoEval(out, 'webr-worker.js') + return out +} + +/** webr.js (also .mjs/.cjs: the same code), the page's side of webR. */ +export function patchWebrMainSource(source) { + // "eval-await" (webr::eval_js(await = TRUE)) gets an error back. + let out = replaceExactly(source, /(case"eval-await":\{let (\w+)=\w+\.data,(\w+)=\{\};try\{)\3\.result=await\(0,eval\)\(\2\),typeof \3\.result=="function"&&\(\3\.result=String\(\3\.result\)\)/, (_, head) => `${head}${throwNoJs}`, 1, 'eval-await') + // The worker can ask the page to start a Worker from a URL of its choice + // and message it (webR's WorkerProxy). R has no use for it: ignore it. + out = replaceExactly(out, /case"proxyWorker":\{let \w+=\w+;this\.#\w+\.new\(\w+\.data\.uuid,\w+\.data\.url,\w+\.data\.options\);break\}/, 'case"proxyWorker":break;', 1, 'proxyWorker') + assertNoEval(out, 'webr.js') + return out +} + +/** R.js, Emscripten's runtime for R.wasm (it runs in the worker). */ +export function patchRSource(source) { + const sealed = `if(globalThis.Module?.opcodeSealed)throw new Error("wasm modules with JavaScript can't be loaded in Opcode");` + // A module loaded with dyn.load brings its JavaScript as strings, which + // this evals. webR's own module does at startup; later ones may not. + let out = replaceExactly(source, /function addEmAsm\(addr,body\)\{/, (m) => `${m}${sealed}`, 1, 'addEmAsm') + out = replaceExactly(out, /function addEmJs\(name,cSig,body\)\{/, (m) => `${m}${sealed}`, 1, 'addEmJs') + // Functions that run a string as script. webR's own eval_js calls + // emscripten_run_script_int; a loaded module could import any of them. + // They raise an R error instead. + const rError = `globalThis.Module._Rf_error(globalThis.Module.allocateUTF8OnStack(${JSON.stringify(NO_JS)}))` + out = replaceExactly(out, /var _emscripten_run_script=ptr=>\{eval\(UTF8ToString\(ptr\)\)\};/, `var _emscripten_run_script=ptr=>{${rError}};`, 1, 'emscripten_run_script') + out = replaceExactly(out, /var _emscripten_run_script_int=ptr=>eval\(UTF8ToString\(ptr\)\)\|0;/, `var _emscripten_run_script_int=ptr=>{${rError};return 0};`, 1, 'emscripten_run_script_int') + out = replaceExactly(out, /var _emscripten_run_script_string=ptr=>\{var s=eval\(UTF8ToString\(ptr\)\);/, `var _emscripten_run_script_string=ptr=>{${rError};var s;`, 1, 'emscripten_run_script_string') + // And ones that run a script later, load one or start a worker from a URL. + out = replaceExactly(out, /var _emscripten_async_run_script=\(script,millis\)=>\{/, (m) => `${m}${throwNoJs};`, 1, 'emscripten_async_run_script') + out = replaceExactly(out, /var _emscripten_async_load_script=async\(url,onload,onerror\)=>\{/, (m) => `${m}${throwNoJs};`, 1, 'emscripten_async_load_script') + out = replaceExactly(out, /var _emscripten_create_worker=url=>\{/, (m) => `${m}${throwNoJs};`, 1, 'emscripten_create_worker') + // What's left: the two evals above, which refuse once R has started, and + // the unreachable one in emscripten_async_load_script. + assertNoEval(out, 'R.js', 3) + return out } -const TREES = [{ output: 'webr', package: 'webr', dir: 'dist', skip: /\.map$|^(tests|repl)$|^webr\.(mjs|cjs)$|esbuild\.d\.ts$/, patch: patchWebrWorker }] -for (const tree of TREES) { - const target = join(out, tree.output) - const stampFile = `${target}.version` - const stamp = versionOf(tree.package) - if (!force && existsSync(target) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === `${stamp} patched`) continue +export function patchWebr(dir) { + const patches = { 'webr-worker.js': patchWebrWorkerSource, 'webr.js': patchWebrMainSource, 'webr.mjs': patchWebrMainSource, 'webr.cjs': patchWebrMainSource, 'R.js': patchRSource } + for (const [name, patch] of Object.entries(patches)) { + const file = join(dir, name) + if (!existsSync(file)) { + if (['webr-worker.js', 'webr.js', 'R.js'].includes(name)) throw new Error(`webR changed (no ${name}): update the patches in scripts/copy-npm-toolchains.mjs`) + continue + } + writeFileSync(file, patch(readFileSync(file, 'utf8'))) + } +} + +/** webR as the app gets it, for tests: its scripts copied and patched, the rest linked. */ +export function patchedWebrForTests(target) { + const source = join(packageDir('webr'), 'dist') rmSync(target, { recursive: true, force: true }) - cpSync(join(packageDir(tree.package), tree.dir), target, { recursive: true, filter: (path) => !tree.skip.test(path.split('/').pop()) }) - tree.patch?.(target) - writeFileSync(stampFile, `${stamp} patched`) - console.log(` ${tree.output}/: from ${stamp}`) + mkdirSync(target, { recursive: true }) + for (const name of readdirSync(source)) { + if (/\.(js|mjs|cjs)$/.test(name)) cpSync(join(source, name), join(target, name)) + else symlinkSync(join(source, name), join(target, name)) + } + patchWebr(target) + return target } -for (const copy of COPIES) { - const target = join(out, copy.output) - const stampFile = `${target}.version` - const stamp = copy.packages.map(versionOf).join(' ') - if (!force && existsSync(target) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === stamp) continue - mkdirSync(dirname(target), { recursive: true }) - writeFileSync(target, gzipSync(copy.bytes(), { level: 9 })) - writeFileSync(stampFile, stamp) - console.log(` ${copy.output}: from ${stamp} (${(statSync(target).size / 1e6).toFixed(1)} MB)`) +// Bump when the patches change, so existing copies are redone. +const PATCH_VERSION = 'patched 2' +const TREES = [{ output: 'webr', package: 'webr', dir: 'dist', skip: /\.map$|^(tests|repl)$|^webr\.(mjs|cjs)$|esbuild\.d\.ts$/, patch: patchWebr }] + +function main() { + for (const tree of TREES) { + const target = join(out, tree.output) + const stampFile = `${target}.version` + const stamp = versionOf(tree.package) + if (!force && existsSync(target) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === `${stamp} ${PATCH_VERSION}`) continue + rmSync(target, { recursive: true, force: true }) + cpSync(join(packageDir(tree.package), tree.dir), target, { recursive: true, filter: (path) => !tree.skip.test(path.split('/').pop()) }) + tree.patch?.(target) + writeFileSync(stampFile, `${stamp} ${PATCH_VERSION}`) + console.log(` ${tree.output}/: from ${stamp}`) + } + + for (const copy of COPIES) { + const target = join(out, copy.output) + const stampFile = `${target}.version` + const stamp = copy.packages.map(versionOf).join(' ') + if (!force && existsSync(target) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === stamp) continue + mkdirSync(dirname(target), { recursive: true }) + writeFileSync(target, gzipSync(copy.bytes(), { level: 9 })) + writeFileSync(stampFile, stamp) + console.log(` ${copy.output}: from ${stamp} (${(statSync(target).size / 1e6).toFixed(1)} MB)`) + } } + +// Tests import the patches; only running the script copies. +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main() diff --git a/scripts/fetch-csharp.mjs b/scripts/fetch-csharp.mjs index 4143439..2c7b505 100644 --- a/scripts/fetch-csharp.mjs +++ b/scripts/fetch-csharp.mjs @@ -17,7 +17,7 @@ // Usage: node scripts/fetch-csharp.mjs [--force] import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { gzipSync } from 'node:zlib' @@ -38,17 +38,34 @@ const out = join(root, 'public', 'toolchains', 'csharp') const cache = join(root, 'node_modules', '.cache', 'opcode-csharp') const runner = join(root, 'toolchains', 'csharp', 'csharp.dll') const stampFile = join(out, 'packages.json') -const stamp = JSON.stringify({ packages: PACKAGES.map((p) => `${p.id}@${p.version}:${p.sha256}`), runner: createHash('sha256').update(readFileSync(runner)).digest('hex') }) +const inputs = { packages: PACKAGES.map((p) => `${p.id}@${p.version}:${p.sha256}`), runner: createHash('sha256').update(readFileSync(runner)).digest('hex') } const OUTPUTS = ['dotnet.wasm.gz', 'managed.tar.gz'] -function upToDate() { +async function hashFile(file) { + const hash = createHash('sha256') + for await (const chunk of createReadStream(file)) hash.update(chunk) + return hash.digest('hex') +} + +// The stamp also records each output's checksum, so a file swapped in by a +// build cache isn't taken as built from these inputs. +async function upToDate() { try { - return readFileSync(stampFile, 'utf8') === stamp && OUTPUTS.every((file) => existsSync(join(out, file))) + const saved = JSON.parse(readFileSync(stampFile, 'utf8')) + if (JSON.stringify(saved.inputs) !== JSON.stringify(inputs)) return false + for (const file of OUTPUTS) if ((await hashFile(join(out, file))) !== saved.outputs?.[file]) return false + return true } catch { return false } } +async function writeStamp() { + const outputs = {} + for (const file of OUTPUTS) outputs[file] = await hashFile(join(out, file)) + writeFileSync(stampFile, JSON.stringify({ inputs, outputs })) +} + async function download({ id, version, sha256 }) { const file = join(cache, `${id}.${version}.nupkg`) const verify = (bytes) => createHash('sha256').update(bytes).digest('hex') === sha256 @@ -88,7 +105,7 @@ function tar(entries) { return Buffer.concat(blocks) } -if (!process.argv.includes('--force') && upToDate()) process.exit(0) +if (!process.argv.includes('--force') && (await upToDate())) process.exit(0) try { const zips = {} @@ -114,7 +131,7 @@ try { writeFileSync(join(out, 'dotnet.wasm.gz'), gzipSync(await read(wasi, 'runtimes/wasi-wasm/native/dotnet.wasm'), { level: 9 })) const entries = [...managed].sort(([a], [b]) => a.localeCompare(b)).map(([name, data]) => ({ path: name, data })) writeFileSync(join(out, 'managed.tar.gz'), gzipSync(tar(entries), { level: 9 })) - writeFileSync(stampFile, stamp) + await writeStamp() for (const file of OUTPUTS) console.log(` csharp/${file}: ${(readFileSync(join(out, file)).length / 1e6).toFixed(1)} MB`) } catch (error) { console.error(`\nCould not prepare C#: ${error.message}`) diff --git a/scripts/fetch-java.mjs b/scripts/fetch-java.mjs index d19210e..7dd8585 100644 --- a/scripts/fetch-java.mjs +++ b/scripts/fetch-java.mjs @@ -17,7 +17,7 @@ import { createHash } from 'node:crypto' import { execFileSync } from 'node:child_process' -import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs' +import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs' import { dirname, join, relative } from 'node:path' import { fileURLToPath } from 'node:url' import { pipeline } from 'node:stream/promises' @@ -40,21 +40,32 @@ const root = join(dirname(fileURLToPath(import.meta.url)), '..') const out = join(root, 'public', 'toolchains', 'java') const cache = join(root, 'node_modules', '.cache', 'opcode-java') const stampFile = join(out, 'jdk.json') -const stamp = JSON.stringify({ version: VERSION, sha256: SHA256, format: 1 }) +const inputs = { version: VERSION, sha256: SHA256, format: 1 } const OUTPUTS = ['jdk.tar.gz', 'javac-sdk.bin'] -function upToDate() { +async function sha256(file) { + const hash = createHash('sha256') + for await (const chunk of createReadStream(file)) hash.update(chunk) + return hash.digest('hex') +} + +// The stamp also records each output's checksum, so a file swapped in by a +// build cache isn't taken as built from these inputs. +async function upToDate() { try { - return readFileSync(stampFile, 'utf8') === stamp && OUTPUTS.every((file) => existsSync(join(out, file))) + const saved = JSON.parse(readFileSync(stampFile, 'utf8')) + if (JSON.stringify(saved.inputs) !== JSON.stringify(inputs)) return false + for (const file of OUTPUTS) if ((await sha256(join(out, file))) !== saved.outputs?.[file]) return false + return true } catch { return false } } -async function sha256(file) { - const hash = createHash('sha256') - for await (const chunk of createReadStream(file)) hash.update(chunk) - return hash.digest('hex') +async function writeStamp() { + const outputs = {} + for (const file of OUTPUTS) outputs[file] = await sha256(join(out, file)) + writeFileSync(stampFile, JSON.stringify({ inputs, outputs })) } async function downloadJdk() { @@ -118,11 +129,14 @@ function walk(dir) { }) } -if (!process.argv.includes('--force') && upToDate()) process.exit(0) +if (!process.argv.includes('--force') && (await upToDate())) process.exit(0) try { const archive = await downloadJdk() const extracted = join(cache, 'extracted') + // Start empty: DATA's directories are packed whole, so anything left over + // from an earlier run (or a restored cache) would end up in jdk.tar.gz. + rmSync(extracted, { recursive: true, force: true }) mkdirSync(extracted, { recursive: true }) execFileSync('tar', ['-xzf', archive, '-C', extracted, ...[...DATA, 'jmods/java.base.jmod'].map((path) => `${TOP}/${path}`)]) const home = join(extracted, TOP) @@ -154,7 +168,7 @@ try { mkdirSync(out, { recursive: true }) writeFileSync(join(out, 'jdk.tar.gz'), gzipSync(tar(entries), { level: 9 })) writeFileSync(join(out, 'javac-sdk.bin'), teavmArchive(sdk)) - writeFileSync(stampFile, stamp) + await writeStamp() for (const file of OUTPUTS) console.log(` ${file}: ${(statSync(join(out, file)).size / 1e6).toFixed(1)} MB`) } catch (error) { console.error(`\nCould not prepare Java: ${error.message}`) diff --git a/scripts/fetch-rust.mjs b/scripts/fetch-rust.mjs index f4a81ec..29fe430 100644 --- a/scripts/fetch-rust.mjs +++ b/scripts/fetch-rust.mjs @@ -11,7 +11,7 @@ // Usage: node scripts/fetch-rust.mjs [--force] import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { createReadStream, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { brotliDecompressSync, gzipSync } from 'node:zlib' @@ -25,11 +25,22 @@ const FILES = [ const out = join(dirname(fileURLToPath(import.meta.url)), '..', 'public', 'toolchains', 'rust') const stampFile = join(out, 'release.json') -const stamp = JSON.stringify({ release: RELEASE, files: FILES.map((file) => file.sha256) }) +const inputs = { release: RELEASE, files: FILES.map((file) => file.sha256) } -function upToDate() { +async function hashFile(file) { + const hash = createHash('sha256') + for await (const chunk of createReadStream(file)) hash.update(chunk) + return hash.digest('hex') +} + +// The stamp also records each output's checksum, so a file swapped in by a +// build cache isn't taken as the pinned release. +async function upToDate() { try { - return readFileSync(stampFile, 'utf8') === stamp && FILES.every((file) => existsSync(join(out, file.output))) + const saved = JSON.parse(readFileSync(stampFile, 'utf8')) + if (JSON.stringify(saved.inputs) !== JSON.stringify(inputs)) return false + for (const file of FILES) if ((await hashFile(join(out, file.output))) !== saved.outputs?.[file.output]) return false + return true } catch { return false } @@ -52,7 +63,7 @@ async function download(file) { throw new Error(`Could not download ${file.source}:\n ${errors.join('\n ')}`) } -if (!process.argv.includes('--force') && upToDate()) process.exit(0) +if (!process.argv.includes('--force') && (await upToDate())) process.exit(0) mkdirSync(out, { recursive: true }) console.log(`Fetching the Rust toolchain (${RELEASE}, about 40 MB)…`) @@ -67,7 +78,9 @@ try { console.log(` ${file.output}: ${(bytes.length / 1e6).toFixed(1)} MB unpacked`) }), ) - writeFileSync(stampFile, stamp) + const outputs = {} + for (const file of FILES) outputs[file.output] = await hashFile(join(out, file.output)) + writeFileSync(stampFile, JSON.stringify({ inputs, outputs })) } catch (error) { console.error(`${error.message}\nRust projects won't work in this build until the download succeeds (rerun: node scripts/fetch-rust.mjs).`) process.exit(1) diff --git a/scripts/preview-host.mjs b/scripts/preview-host.mjs index 3f00d37..df1b6c5 100644 --- a/scripts/preview-host.mjs +++ b/scripts/preview-host.mjs @@ -13,12 +13,17 @@ // node scripts/preview-host.mjs -> dist-preview-host/ // node scripts/preview-host.mjs --serve 5174 -> also serve it locally, on // http://localhost:5174/ and on every http://.localhost:5174/ +// --out writes it elsewhere. +// +// OPCODE_APP_ORIGINS=https://opcode.example.com limits the host to that app +// (comma-separate several): see appOrigins below. import { copyFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' -import { dirname, extname, join, normalize, resolve } from 'node:path' +import { dirname, extname, join, normalize, resolve, sep } from 'node:path' const root = resolve(dirname(new URL(import.meta.url).pathname), '..') -const out = join(root, 'dist-preview-host') +const outIndex = process.argv.indexOf('--out') +const out = outIndex === -1 ? join(root, 'dist-preview-host') : resolve(process.argv[outIndex + 1]) const sdk = join(root, 'node_modules/@wasmer/sdk/dist') // The host page is embedded by the cross-origin isolated app. @@ -28,29 +33,80 @@ const HEADERS = { 'Cross-Origin-Resource-Policy': 'cross-origin', } +// OPCODE_APP_ORIGINS: the app origins that may use this host, comma-separated +// (https://opcode.example.com,http://localhost:5173). Set, host.html works +// only for them and only they may embed it. Unset, any site may. +const appOrigins = (process.env.OPCODE_APP_ORIGINS ?? '').split(',').map((origin) => origin.trim().replace(/\/+$/, '')).filter(Boolean) +for (const origin of appOrigins) { + let valid = false + try { + valid = new URL(origin).origin === origin + } catch { + // Not a URL. + } + if (!valid) throw new Error(`OPCODE_APP_ORIGINS: "${origin}" is not an origin such as https://opcode.example.com`) +} + +// host.html's own headers. Pages a previewed server serves share its origin +// and can run code in it; sandboxed (keeping its origin, which the service +// worker needs), it can't navigate the app's tab or open windows for them. +// Opcode also sandboxes the frame itself (src/lib/linux/httpBridge.js); the +// header covers other embedders and hosts that can't take it from the frame. +const HOST_PAGE_HEADERS = { + 'Content-Security-Policy': ['sandbox allow-scripts allow-same-origin', ...(appOrigins.length ? [`frame-ancestors ${appOrigins.join(' ')}`] : [])].join('; '), +} + mkdirSync(join(out, '.wasmer'), { recursive: true }) copyFileSync(join(sdk, 'service-worker-host.js'), join(out, '.wasmer/host.js')) copyFileSync(join(sdk, 'service-worker.js'), join(out, 'wasmer-service-worker.js')) +// host.html checks who embeds it before starting the SDK's host.js. With +// ?opcode=handoff (Opcode asks for it, see installSdkHostBroker() in +// src/lib/linux/httpBridge.js), it passes the SDK's connection to the app +// instead, which then runs the host in frames of its own. +const hostScript = `(() => { + const allowed = ${JSON.stringify(appOrigins.length ? appOrigins : null)} + const params = new URLSearchParams(location.search) + const parentOrigin = params.get('parentOrigin') + const connections = (handle) => addEventListener('message', (event) => { + if (event.data?.type === 'wasmer-sdk:http-host-connect' && event.ports[0]) handle(event) + }) + if (allowed && !allowed.includes(parentOrigin)) { + connections(({ ports: [port] }) => { + port.postMessage({ type: 'wasmer-sdk:http-host-error', error: 'This preview host does not serve ' + parentOrigin + '.' }) + port.close() + }) + } else if (params.get('opcode') === 'handoff') { + connections((event) => { + if (event.origin === parentOrigin) parent.postMessage({ type: 'opcode:wasmer-host-handoff' }, parentOrigin, [event.ports[0]]) + }) + } else { + const script = document.createElement('script') + script.type = 'module' + script.src = '/.wasmer/host.js' + document.head.append(script) + } +})()` writeFileSync( join(out, '.wasmer/host.html'), - '\nOpcode preview host\n\n', + `\nOpcode preview host\n\n`, ) writeFileSync( join(out, 'index.html'), '\nOpcode preview\nNo server is being previewed. Start one in an Opcode terminal.\n', ) // Netlify / Cloudflare Pages headers; GitHub Pages must not skip .wasmer/. -writeFileSync(join(out, '_headers'), `/*\n${Object.entries(HEADERS).map(([k, v]) => ` ${k}: ${v}`).join('\n')}\n Cache-Control: no-cache\n`) +const headerLines = (headers) => Object.entries(headers).map(([k, v]) => ` ${k}: ${v}`).join('\n') +writeFileSync(join(out, '_headers'), `/*\n${headerLines(HEADERS)}\n Cache-Control: no-cache\n/.wasmer/host.html\n${headerLines(HOST_PAGE_HEADERS)}\n`) writeFileSync(join(out, '.nojekyll'), '') // The same files as a Cloudflare Worker, for wildcard hosts. const files = { '/': ['index.html', 'text/html; charset=utf-8'], - '/.wasmer/host.html': ['.wasmer/host.html', 'text/html; charset=utf-8'], + '/.wasmer/host.html': ['.wasmer/host.html', 'text/html; charset=utf-8', HOST_PAGE_HEADERS], '/.wasmer/host.js': ['.wasmer/host.js', 'text/javascript; charset=utf-8'], '/wasmer-service-worker.js': ['wasmer-service-worker.js', 'text/javascript; charset=utf-8'], } -const embedded = Object.fromEntries(Object.entries(files).map(([path, [file, type]]) => [path, { body: readFileSync(join(out, file), 'utf8'), type }])) +const embedded = Object.fromEntries(Object.entries(files).map(([path, [file, type, headers = {}]]) => [path, { body: readFileSync(join(out, file), 'utf8'), type, headers }])) writeFileSync( join(out, 'worker.js'), `// Opcode's web preview host as a Cloudflare Worker (generated by @@ -62,7 +118,7 @@ export default { fetch(request) { const file = FILES[new URL(request.url).pathname] if (!file) return new Response('Not found', { status: 404, headers: HEADERS }) - return new Response(file.body, { headers: { ...HEADERS, 'Content-Type': file.type } }) + return new Response(file.body, { headers: { ...HEADERS, ...file.headers, 'Content-Type': file.type } }) }, } `, @@ -87,7 +143,8 @@ if (serveIndex !== -1) { response.writeHead(404, { ...HEADERS, 'Content-Type': 'text/plain' }).end('Not found') return } - response.writeHead(200, { ...HEADERS, 'Content-Type': types[extname(file)] ?? 'application/octet-stream', 'Cache-Control': 'no-cache' }) + const own = path.split(sep).join('/') === '/.wasmer/host.html' ? HOST_PAGE_HEADERS : {} + response.writeHead(200, { ...HEADERS, ...own, 'Content-Type': types[extname(file)] ?? 'application/octet-stream', 'Cache-Control': 'no-cache' }) response.end(readFileSync(file)) }).listen(port, () => console.log(`Preview host on http://localhost:${port}/ and http://*.localhost:${port}/ (build the app with VITE_PREVIEW_HOST=http://*.localhost:${port}/)`)) } diff --git a/scripts/server.mjs b/scripts/server.mjs index 45a341a..16b4e5f 100644 --- a/scripts/server.mjs +++ b/scripts/server.mjs @@ -20,6 +20,15 @@ // https://preview.example.com/, or // https://*.preview.example.com/ for one address per // server. By default the preview uses Wasmer's host. +// OPCODE_APP_ORIGINS the app's own origin (https://opcode.example.com; +// comma-separate several): only its pages may then +// embed the preview host served here +// OPCODE_TRUST_PROXY "on" when a proxy in front of this server sets +// X-Forwarded-Host (replacing any the client sent): +// the host name is then read from it. "off" (the +// default) uses the Host header, which Caddy (as in +// compose.yaml) passes on unchanged, and ignores +// X-Forwarded-Host, since any client can send one. // // With any of these set, /config.js tells the app about them (it would // otherwise come from the build: public/config.js). @@ -59,9 +68,11 @@ const TYPES = { } // The app needs cross-origin isolation (SharedArrayBuffer). +// It is never meant to be framed, by other sites or by itself. const APP_HEADERS = { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', + 'Content-Security-Policy': "frame-ancestors 'none'", 'X-Content-Type-Options': 'nosniff', } // The preview host is embedded by the app (as scripts/preview-host.mjs serves it). @@ -78,6 +89,20 @@ export function configFromEnv(env = process.env) { if (relay && !['on', 'off'].includes(relay) && !/^wss?:\/\//.test(relay)) { throw new Error(`OPCODE_RELAY must be "on", "off" or a ws:// or wss:// address, not "${relay}"`) } + const appOrigins = (env.OPCODE_APP_ORIGINS ?? '').split(',').map((origin) => origin.trim().replace(/\/+$/, '')).filter(Boolean) + for (const origin of appOrigins) { + let valid = false + try { + valid = new URL(origin).origin === origin + } catch { + // Not a URL. + } + if (!valid) throw new Error(`OPCODE_APP_ORIGINS: "${origin}" is not an origin such as https://opcode.example.com`) + } + const trustProxy = (env.OPCODE_TRUST_PROXY ?? '').trim() + if (trustProxy && !['on', 'off'].includes(trustProxy)) { + throw new Error(`OPCODE_TRUST_PROXY must be "on" or "off", not "${trustProxy}"`) + } const previewHost = (env.OPCODE_PREVIEW_HOST ?? '').trim() if (previewHost && !/^https?:\/\/[^/]+\/?$/.test(previewHost)) { throw new Error(`OPCODE_PREVIEW_HOST must be an origin such as https://preview.example.com/, not "${previewHost}"`) @@ -88,12 +113,19 @@ export function configFromEnv(env = process.env) { relayOptions: parseArgs((env.OPCODE_RELAY_ARGS ?? '').split(/\s+/).filter(Boolean)), relayOrigins: (env.OPCODE_RELAY_ORIGINS ?? '').split(',').map((origin) => origin.trim().replace(/\/+$/, '')).filter(Boolean), previewHost: previewHost && !previewHost.endsWith('/') ? `${previewHost}/` : previewHost, + trustProxy: trustProxy === 'on', + appOrigins, } } -/** The host a request was made to, as the browser saw it (also behind a proxy). */ -function publicHost(request) { - return (request.headers['x-forwarded-host']?.split(',')[0] ?? request.headers.host ?? '').trim().toLowerCase() +/** + * The host a request was made to, as the browser saw it. X-Forwarded-Host + * only counts behind a proxy the operator trusts (OPCODE_TRUST_PROXY): anyone + * can send one, and a cache in front could then keep the wrong site's page. + */ +function publicHost(request, trustProxy) { + const forwarded = trustProxy ? request.headers['x-forwarded-host']?.split(',')[0] : undefined + return (forwarded ?? request.headers.host ?? '').trim().toLowerCase() } function splitHost(host) { @@ -106,13 +138,13 @@ function splitHost(host) { } /** Does a request go to the preview host (`https://*.preview.example.com/` or one origin)? */ -function previewMatcher(previewHost) { +function previewMatcher(previewHost, trustProxy) { if (!previewHost) return () => false const wildcard = previewHost.includes('*.') const { hostname, port } = new URL(previewHost.replace('*.', 'any.')) const suffix = hostname.slice('any'.length) // ".preview.example.com" return (request) => { - const host = splitHost(publicHost(request)) + const host = splitHost(publicHost(request, trustProxy)) // The address names a port when the browser uses one, as in development // (http://*.localhost:8080/); behind a proxy on 443 it doesn't. if (port && host.port !== port) return false @@ -149,8 +181,19 @@ function acceptedEncodings(request) { return accepted } +// A file's details, or undefined. statSync throws for some names even with +// throwIfNoEntry: false (ENAMETOOLONG for a long one), and a request must +// never take the server down. +function stat(path) { + try { + return statSync(path, { throwIfNoEntry: false }) + } catch { + return undefined + } +} + /** A static site: `root`, with copies compressed ahead of time in `compressed`. */ -function staticSite(root, compressed, headers, { immutable = () => false } = {}) { +function staticSite(root, compressed, headers, { immutable = () => false, own = () => ({}) } = {}) { root = resolve(root) const encodings = indexCompressed(compressed) return (request, response, pathname) => { @@ -162,14 +205,17 @@ function staticSite(root, compressed, headers, { immutable = () => false } = {}) } let path = resolve(root, `.${decoded}`) if (decoded.includes('\0') || (path !== root && !path.startsWith(root + sep))) return notFound(response, headers) - let stats = statSync(path, { throwIfNoEntry: false }) + let stats = stat(path) if (stats?.isDirectory()) { if (!pathname.endsWith('/')) { - response.writeHead(301, { ...headers, Location: `${pathname}/` }).end() + // Built from the folder found, not from the request: "//evil.example/.." + // must not become a redirect to another site. + const folder = relative(root, path).split(sep).filter(Boolean).map(encodeURIComponent) + response.writeHead(301, { ...headers, Location: `/${folder.map((part) => `${part}/`).join('')}` }).end() return } path = join(path, 'index.html') - stats = statSync(path, { throwIfNoEntry: false }) + stats = stat(path) } if (!stats?.isFile()) return notFound(response, headers) @@ -180,7 +226,7 @@ function staticSite(root, compressed, headers, { immutable = () => false } = {}) let file = path if (encoding) { const copy = join(compressed, `${name}.${encoding === 'br' ? 'br' : 'gz'}`) - const copyStats = statSync(copy, { throwIfNoEntry: false }) + const copyStats = stat(copy) // A copy older than the file is from an earlier build. if (copyStats && copyStats.mtimeMs >= stats.mtimeMs) { file = copy @@ -190,6 +236,7 @@ function staticSite(root, compressed, headers, { immutable = () => false } = {}) const etag = `"${stats.size.toString(36)}-${Math.floor(stats.mtimeMs).toString(36)}${encoding ? `-${encoding}` : ''}"` const head = { ...headers, + ...own(name), 'Content-Type': TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream', 'Cache-Control': immutable(name) ? 'public, max-age=31536000, immutable' : 'no-cache', ETag: etag, @@ -217,8 +264,14 @@ function notFound(response, headers) { */ export function createOpcodeServer(config, { dist = join(ROOT, 'dist'), previewDist = join(ROOT, 'dist-preview-host'), compressed = join(ROOT, 'dist-compressed') } = {}) { const app = staticSite(dist, compressed, APP_HEADERS, { immutable: (name) => name.startsWith('assets/') }) - const preview = staticSite(previewDist, null, { ...PREVIEW_HEADERS, 'Cache-Control': 'no-cache' }) - const isPreview = previewMatcher(config.previewHost) + // The preview host's page is sandboxed: pages a previewed server serves + // share its origin and can run code in it, and sandboxed it can't navigate + // the app's tab for them. Only the app's own pages may embed it, when the + // server knows which they are (OPCODE_APP_ORIGINS). The header goes by the + // file, so no other spelling of its path gets the page without it. + const hostPolicy = ['sandbox allow-scripts allow-same-origin', ...(config.appOrigins?.length ? [`frame-ancestors ${config.appOrigins.join(' ')}`] : [])].join('; ') + const preview = staticSite(previewDist, null, { ...PREVIEW_HEADERS, 'Cache-Control': 'no-cache' }, { own: (name) => (name === '.wasmer/host.html' ? { 'Content-Security-Policy': hostPolicy } : {}) }) + const isPreview = previewMatcher(config.previewHost, config.trustProxy) let relay = null if (config.relay === 'on') { @@ -230,7 +283,7 @@ export function createOpcodeServer(config, { dist = join(ROOT, 'dist'), previewD if (!origin) return true if (origins.includes(origin)) return true try { - return new URL(origin).host.toLowerCase() === publicHost(request) + return new URL(origin).host.toLowerCase() === publicHost(request, config.trustProxy) } catch { return false } @@ -245,7 +298,7 @@ export function createOpcodeServer(config, { dist = join(ROOT, 'dist'), previewD ? `// Written by scripts/server.mjs from its environment (see public/config.js).\nwindow.OPCODE_CONFIG = ${JSON.stringify(settings, null, 2)}\n` : null - const server = http.createServer((request, response) => { + const handle = (request, response) => { const pathname = pathOf(request.url) if (pathname === null) return response.writeHead(400).end() if (isPreview(request)) { @@ -259,11 +312,27 @@ export function createOpcodeServer(config, { dist = join(ROOT, 'dist'), previewD return response.end(request.method === 'HEAD' ? undefined : configScript) } app(request, response, pathname) + } + // Whatever goes wrong with one request, keep serving the others (and the + // relay's WebSockets, which share the process). + const server = http.createServer((request, response) => { + try { + handle(request, response) + } catch (error) { + console.error(`${request.method} ${request.url}: ${error.stack ?? error}`) + if (response.headersSent) response.destroy() + else response.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Server error\n') + } }) server.on('upgrade', (request, socket, head) => { - const pathname = pathOf(request.url) - if (relay && !isPreview(request) && (pathname === RELAY_PATH || pathname === RELAY_PATH.slice(0, -1))) return relay.upgrade(request, socket, head) - socket.end('HTTP/1.1 404 Not Found\r\n\r\n') + try { + const pathname = pathOf(request.url) + if (relay && !isPreview(request) && (pathname === RELAY_PATH || pathname === RELAY_PATH.slice(0, -1))) return relay.upgrade(request, socket, head) + socket.end('HTTP/1.1 404 Not Found\r\n\r\n') + } catch (error) { + console.error(`upgrade ${request.url}: ${error.stack ?? error}`) + socket.destroy() + } }) return server } @@ -278,7 +347,7 @@ function pathOf(url) { } } -if (import.meta.url === pathToFileURL(process.argv[1]).href) { +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { let config try { config = configFromEnv() diff --git a/scripts/wasmer-packages.mjs b/scripts/wasmer-packages.mjs index ad9e30f..0c52e96 100644 --- a/scripts/wasmer-packages.mjs +++ b/scripts/wasmer-packages.mjs @@ -17,7 +17,7 @@ // again and rewrite the lock import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -137,12 +137,31 @@ function pick(name, answer, ranges) { return chosen } +// Streamed, so checking 150 MB of packages doesn't hold them all in memory. +function hashFile(path) { + return new Promise((resolve, reject) => { + const hash = createHash('sha256') + createReadStream(path).on('error', reject).on('data', (chunk) => hash.update(chunk)).on('end', () => resolve(hash.digest('hex'))) + }) +} + async function download() { const { info, packages } = JSON.parse(readFileSync(lockFile, 'utf8')) const registry = `${JSON.stringify({ info, packages: Object.fromEntries(Object.entries(packages).map(([name, item]) => [name, item.answer])) })}\n` const registryFile = join(out, 'registry.json') const file = (item) => join(out, `${item.sha256}.webc`) - const missing = Object.entries(packages).filter(([, item]) => !existsSync(file(item))) + // A file that is already there may come from a CI or Docker build cache, so + // its name is not proof of its contents: hash it, and fetch it again if it + // doesn't match the lock. + const missing = [] + for (const [name, item] of Object.entries(packages)) { + if (existsSync(file(item))) { + if ((await hashFile(file(item))) === item.sha256) continue + console.log(` ${name}@${item.version}: the cached file doesn't match the lock; fetching it again`) + rmSync(file(item), { force: true }) + } + missing.push([name, item]) + } if (!missing.length && existsSync(registryFile) && readFileSync(registryFile, 'utf8') === registry) return mkdirSync(out, { recursive: true }) if (missing.length) { diff --git a/scripts/wisp-server.mjs b/scripts/wisp-server.mjs index 7ab7977..57be7be 100644 --- a/scripts/wisp-server.mjs +++ b/scripts/wisp-server.mjs @@ -19,6 +19,10 @@ // your Opcode site, and run it where outgoing traffic is acceptable. It // refuses private and local addresses (your network, cloud metadata // services) unless --allow-private, and outgoing mail ports by default. +// +// With --via-proxy, the proxy is given host names and looks them up again +// itself, so the relay's private-address check can't bind it: give the proxy +// its own rules against private and local destinations. import dgram from 'node:dgram' import dns from 'node:dns/promises' @@ -32,7 +36,16 @@ const STREAM = { TCP: 0x01, UDP: 0x02 } const REASON = { VOLUNTARY: 0x02, NETWORK_ERROR: 0x03, INVALID: 0x41, UNREACHABLE: 0x42, TIMEOUT: 0x43, REFUSED: 0x44, BLOCKED: 0x48, THROTTLED: 0x49 } const BUFFER_PACKETS = 128 // DATA packets a client may send before a CONTINUE const WS_HIGH_WATER = 1 << 20 // pause sockets while the WebSocket is this far behind +// Clients send each of a program's writes as one DATA packet, so allow big +// ones; memory is bounded by CLIENT_HIGH_WATER below, not by this. +const MAX_PAYLOAD = 16 << 20 +// Stop reading a client's WebSocket while this much of what it sent is still +// waiting to go out (to peers that read slowly, or not yet connected). +const CLIENT_HIGH_WATER = 32 << 20 +const UDP_MAX_PENDING = 1 << 20 // UDP bytes waiting to be sent; more are dropped const CONNECT_TIMEOUT_MS = 15_000 +const DNS_TIMEOUT_MS = 10_000 +const MAX_PROXY_REPLY = 16 << 10 // --------------------------------------------------------------------------- // Options @@ -59,27 +72,67 @@ export function parseArgs(argv) { return options } -// Local and private networks: the relay must not become a way in. +// Local and private networks: the relay must not become a way in. (Also the +// documentation ranges, which no real host uses.) const PRIVATE = new net.BlockList() -for (const [address, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 4], ['240.0.0.0', 4]]) { +for (const [address, prefix] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4]]) { PRIVATE.addSubnet(address, prefix, 'ipv4') } -for (const [address, prefix] of [['::', 128], ['::1', 128], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) PRIVATE.addSubnet(address, prefix, 'ipv6') +// ::/96 holds :: and the old IPv4-compatible addresses; 64:ff9b:1::/48 is +// NAT64 for local use. +for (const [address, prefix] of [['::', 96], ['::1', 128], ['64:ff9b:1::', 48], ['2001:db8::', 32], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) PRIVATE.addSubnet(address, prefix, 'ipv6') + +/** An IPv6 address as its eight 16-bit groups. */ +function ipv6Groups(address) { + let text = address + const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text) + if (dotted) { + const [a, b, c, d] = dotted.slice(1).map(Number) + text = `${text.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}` + } + const [head, tail] = text.split('::') + const left = head ? head.split(':') : [] + const right = tail === undefined ? [] : tail ? tail.split(':') : [] + const groups = [...left, ...Array(8 - left.length - right.length).fill('0'), ...right] + return groups.map((group) => parseInt(group, 16)) +} + +const ipv4Of = (high, low) => `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}` function isPrivate(address) { - const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address) - if (mapped) return PRIVATE.check(mapped[1], 'ipv4') - return PRIVATE.check(address, net.isIPv6(address) ? 'ipv6' : 'ipv4') + if (!net.isIPv6(address)) return PRIVATE.check(address, 'ipv4') + const g = ipv6Groups(address) + // IPv6 addresses that carry an IPv4 one go where that one goes: IPv4-mapped + // (::ffff:0:0/96), NAT64 (64:ff9b::/96) and 6to4 (2002::/16). Checking the + // IPv4 address keeps NAT64 working for relays on IPv6-only hosts. + if (g.slice(0, 5).every((group) => group === 0) && g[5] === 0xffff) return PRIVATE.check(ipv4Of(g[6], g[7]), 'ipv4') + if (g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((group) => group === 0)) return PRIVATE.check(ipv4Of(g[6], g[7]), 'ipv4') + if (g[0] === 0x2002) return PRIVATE.check(ipv4Of(g[1], g[2]), 'ipv4') + return PRIVATE.check(address, 'ipv6') +} + +// Host names as DNS has them: letters, digits, hyphens and underscores, in +// dot-separated labels. Nothing else may reach a proxy's CONNECT line, where +// a space or line break would let a client write its own request. +const LABEL = /^[a-z0-9_-]{1,63}$/i +function isHostname(name) { + if (typeof name !== 'string' || !name || name.length > 254) return false + const labels = name.replace(/\.$/, '').split('.') + return labels.join('.').length <= 253 && labels.every((label) => LABEL.test(label)) +} + +/** One spelling per address, so names learned from DNS match what clients send. */ +function normalAddress(address) { + return net.isIPv6(address) ? new net.SocketAddress({ address, family: 'ipv6' }).address : address } // Resolve once and connect to that address, so a name can't be pointed at a // private address between the check and the connection. -async function resolveTarget(hostname, options) { - const host = hostname.replace(/^\[|\]$/g, '') +async function resolveTarget(host, options) { const addresses = net.isIP(host) ? [{ address: host }] : await dns.lookup(host, { all: true }) const allowed = addresses.filter(({ address }) => options.allowPrivate || !isPrivate(address)) if (!allowed.length) { - const error = new Error(`${hostname} is a private address`) + const error = new Error(`${host} is a private address`) error.reason = REASON.BLOCKED throw error } @@ -93,10 +146,20 @@ async function resolveTarget(hostname, options) { // --------------------------------------------------------------------------- // DNS-over-HTTPS (RFC 8484), forwarded upstream. Remembers which name each // address belongs to: an HTTP proxy may only accept names (--via-proxy). +// Any client can add to this, so a name from it is only used once the relay +// has looked the name up itself (see proxyName below). // --------------------------------------------------------------------------- const namesByAddress = new Map() +function rememberName(address, name) { + if (!net.isIP(address) || !isHostname(name)) return + address = normalAddress(address) + namesByAddress.delete(address) + namesByAddress.set(address, name.toLowerCase().replace(/\.$/, '')) + if (namesByAddress.size > 10_000) namesByAddress.delete(namesByAddress.keys().next().value) +} + function skipName(message, offset) { while (offset < message.length) { const length = message[offset] @@ -107,8 +170,10 @@ function skipName(message, offset) { return offset } -function rememberAnswers(message) { - if (message.length < 12) return +/** A DNS answer's first question name ('' if none) and its A and AAAA addresses. */ +function readAnswers(message) { + const result = { name: '', addresses: [] } + if (message.length < 12) return result const questions = message.readUInt16BE(4) const answers = message.readUInt16BE(6) let offset = 12 @@ -116,26 +181,30 @@ function rememberAnswers(message) { for (let i = 0; i < questions; i++) { if (i === 0) { for (let o = offset; o < message.length && message[o] !== 0 && (message[o] & 0xc0) !== 0xc0; o += message[o] + 1) { - labels.push(message.subarray(o + 1, o + 1 + message[o]).toString()) + labels.push(message.subarray(o + 1, o + 1 + message[o]).toString('latin1')) } } offset = skipName(message, offset) + 4 } - const name = labels.join('.') - for (let i = 0; i < answers && offset + 10 <= message.length; i++) { + // A label holding a dot would read as two; such names are not remembered. + if (labels.every((label) => LABEL.test(label))) result.name = labels.join('.') + for (let i = 0; i < answers; i++) { offset = skipName(message, offset) + if (offset + 10 > message.length) break const type = message.readUInt16BE(offset) const length = message.readUInt16BE(offset + 8) const data = message.subarray(offset + 10, offset + 10 + length) offset += 10 + length - let address = null - if (type === 1 && length === 4) address = [...data].join('.') - else if (type === 28 && length === 16) address = net.SocketAddress ? new net.SocketAddress({ address: [...Array(8)].map((_, j) => data.readUInt16BE(j * 2).toString(16)).join(':'), family: 'ipv6' }).address : null - if (!address || !name) continue - namesByAddress.delete(address) - namesByAddress.set(address, name) - if (namesByAddress.size > 10_000) namesByAddress.delete(namesByAddress.keys().next().value) + if (data.length !== length) break + if (type === 1 && length === 4) result.addresses.push([...data].join('.')) + else if (type === 28 && length === 16) result.addresses.push(normalAddress([...Array(8)].map((_, j) => data.readUInt16BE(j * 2).toString(16)).join(':'))) } + return result +} + +function rememberAnswers(message) { + const { name, addresses } = readAnswers(message) + for (const address of addresses) rememberName(address, name) } async function serveDns(request, response, options, cors) { @@ -173,7 +242,7 @@ async function serveDns(request, response, options, cors) { request.destroy() return } - const upstream = await fetch(options.dnsUpstream, { method: 'POST', headers: { 'content-type': 'application/dns-message', accept: 'application/dns-message' }, body: query, signal: AbortSignal.timeout(10_000) }) + const upstream = await fetch(options.dnsUpstream, { method: 'POST', headers: { 'content-type': 'application/dns-message', accept: 'application/dns-message' }, body: query, signal: AbortSignal.timeout(DNS_TIMEOUT_MS) }) const answer = Buffer.from(await upstream.arrayBuffer()) if (upstream.ok) rememberAnswers(answer) response.writeHead(upstream.status, { ...cors, 'Content-Type': 'application/dns-message', 'Cache-Control': 'no-store' }).end(answer) @@ -189,21 +258,23 @@ const MAX_DNS_MESSAGE = 4096 // The JSON flavour (?name=&type=, application/dns-json), which some clients // use instead of DNS messages. async function serveDnsJson(params, response, options, cors) { + const name = params.get('name') + const type = params.get('type') ?? 'A' + if (!isHostname(name) || !/^[a-z0-9]{1,16}$/i.test(type)) { + response.writeHead(400, cors).end() + return + } const upstream = new URL(options.dnsUpstream) - upstream.searchParams.set('name', params.get('name')) - upstream.searchParams.set('type', params.get('type') ?? 'A') + upstream.searchParams.set('name', name) + upstream.searchParams.set('type', type) try { - const answer = await fetch(upstream, { headers: { accept: 'application/dns-json' } }) + const answer = await fetch(upstream, { headers: { accept: 'application/dns-json' }, signal: AbortSignal.timeout(DNS_TIMEOUT_MS) }) const body = await answer.text() if (answer.ok) { try { for (const record of JSON.parse(body).Answer ?? []) { - if ((record.type === 1 || record.type === 28) && net.isIP(record.data)) { - namesByAddress.delete(record.data) - namesByAddress.set(record.data, String(params.get('name')).replace(/\.$/, '')) - } + if (record.type === 1 || record.type === 28) rememberName(String(record.data), name) } - if (namesByAddress.size > 10_000) namesByAddress.delete(namesByAddress.keys().next().value) } catch { // Not JSON; pass it on as it is. } @@ -214,25 +285,55 @@ async function serveDnsJson(params, response, options, cors) { } } -function connectTcp(address, port, options, hostname) { +/** + * The name to give the proxy for a connection to `host` (checked: `address`), + * or null to give it the address. A name the client sent is used as it is; + * for an address, a name learned from DNS answers, but only if the relay's + * own lookup of that name gives this address now. Any client can teach the + * relay names, and one client must not decide where another's connection + * goes. + */ +async function proxyName(host, address) { + if (!net.isIP(host)) return host + const name = namesByAddress.get(normalAddress(address)) + if (!name) return null + try { + const found = await dns.lookup(name, { all: true }) + return found.some((entry) => normalAddress(entry.address) === normalAddress(address)) ? name : null + } catch { + return null + } +} + +// `track(socket)` is told about the socket at once, so that closing the +// stream can destroy it before it has connected. +function connectTcp(address, port, options, name, track) { return new Promise((resolve, reject) => { const proxy = options.viaProxy - // A proxy gets the name (it may refuse bare addresses), learned from the - // client or from DNS answers; direct connections use the checked address. - const name = net.isIP(hostname) ? namesByAddress.get(hostname) : hostname + // A proxy gets the name (it may refuse bare addresses) when there is one; + // direct connections use the checked address. A proxy looks the name up + // again itself, so the relay's private-address check on it is only + // advisory: the proxy needs its own rules (see the top of this file). const host = proxy && name ? name : address + // Never write anything but a host name or an address into CONNECT. + if (!net.isIP(host) && !isHostname(host)) return reject(Object.assign(new Error('bad host name'), { reason: REASON.INVALID })) const target = `${net.isIPv6(host) ? `[${host}]` : host}:${port}` const socket = proxy ? net.connect(Number(proxy.port || 80), proxy.hostname) : net.connect(port, address) + track(socket) + let settled = false const timer = setTimeout(() => { socket.destroy() - reject(Object.assign(new Error('connection timed out'), { reason: REASON.TIMEOUT })) + done(Object.assign(new Error('connection timed out'), { reason: REASON.TIMEOUT })) }, CONNECT_TIMEOUT_MS) const done = (error, result) => { + if (settled) return + settled = true clearTimeout(timer) if (error) reject(error) else resolve(result) } socket.once('error', (error) => done(Object.assign(error, { reason: error.code === 'ECONNREFUSED' ? REASON.REFUSED : REASON.UNREACHABLE }))) + socket.once('close', () => done(Object.assign(new Error('connection closed'), { reason: REASON.UNREACHABLE }))) socket.once('connect', () => { if (!proxy) return done(null, socket) // Tunnel through an HTTP proxy (for hosts whose traffic must go through one). @@ -242,7 +343,13 @@ function connectTcp(address, port, options, hostname) { const onData = (chunk) => { head = Buffer.concat([head, chunk]) const end = head.indexOf('\r\n\r\n') - if (end === -1) return + if (end === -1) { + if (head.length > MAX_PROXY_REPLY) { + socket.destroy() + done(Object.assign(new Error('proxy reply too long'), { reason: REASON.REFUSED })) + } + return + } socket.pause() // until the stream's handlers are attached socket.off('data', onData) const status = head.subarray(0, head.indexOf('\r\n')).toString() @@ -280,11 +387,35 @@ function serveClient(ws, request, options) { const stream = streams.get(streamId) if (!stream) return streams.delete(streamId) - stream.socket?.destroy?.() - stream.socket?.close?.() + for (const socket of [stream.socket, stream.connecting]) { + if (!(socket instanceof dgram.Socket)) socket?.destroy() + else { + try { + socket.close() + } catch { + // Closed already (after an error). + } + } + } + pressure() if (notify) send(PACKET.CLOSE, streamId, Buffer.from([reason])) } + // Stop reading the WebSocket while too much of what the client sent is + // still waiting (the Wisp window limits packets, not bytes). + let paused = false + function pressure() { + let waiting = 0 + for (const stream of streams.values()) waiting += stream.queued + (stream.type === STREAM.TCP && stream.socket ? stream.socket.writableLength : 0) + if (!paused && waiting > CLIENT_HIGH_WATER) { + paused = true + ws.pause() + } else if (paused && waiting <= CLIENT_HIGH_WATER / 2) { + paused = false + ws.resume() + } + } + // Keep up with a slow WebSocket by pausing the TCP sockets feeding it. const drain = setInterval(() => { const behind = ws.bufferedAmount > WS_HIGH_WATER @@ -298,11 +429,18 @@ function serveClient(ws, request, options) { async function open(streamId, type, port, hostname) { if (streams.size >= options.maxStreams) return send(PACKET.CLOSE, streamId, Buffer.from([REASON.THROTTLED])) if (!port || options.blockPorts.includes(port)) return send(PACKET.CLOSE, streamId, Buffer.from([REASON.BLOCKED])) - const stream = { type, socket: null, queue: [], inFlight: 0, processed: 0 } + const host = hostname.replace(/^\[|\]$/g, '') + if ((type !== STREAM.TCP && type !== STREAM.UDP) || (!net.isIP(host) && !isHostname(host))) return send(PACKET.CLOSE, streamId, Buffer.from([REASON.INVALID])) + // `allowed` is the most DATA packets the client may have sent so far + // (see write below); `queued` is bytes waiting for the connection. + const stream = { type, socket: null, connecting: null, queue: [], queued: 0, received: 0, allowed: BUFFER_PACKETS, inFlight: 0, udpPending: 0 } streams.set(streamId, stream) + // The stream may have been closed, and its id reused, while waiting: each + // step checks it is still this stream's, or drops what it made. + const current = () => streams.get(streamId) === stream try { - const address = await resolveTarget(hostname, options) - if (!streams.has(streamId)) return + const address = await resolveTarget(host, options) + if (!current()) return if (type === STREAM.UDP) { if (options.viaProxy) throw Object.assign(new Error('UDP is not available through a proxy'), { reason: REASON.INVALID }) const socket = dgram.createSocket(net.isIPv6(address) ? 'udp6' : 'udp4') @@ -311,37 +449,54 @@ function serveClient(ws, request, options) { socket.connect(port, address) stream.socket = socket } else { - const socket = await connectTcp(address, port, options, hostname.replace(/^\[|\]$/g, '')) - if (!streams.has(streamId)) return socket.destroy() + const name = options.viaProxy ? await proxyName(host, address) : null + if (!current()) return + const socket = await connectTcp(address, port, options, name, (pending) => (stream.connecting = pending)) + stream.connecting = null + if (!current()) return socket.destroy() socket.setNoDelay(true) socket.on('data', (chunk) => send(PACKET.DATA, streamId, chunk)) + socket.on('drain', pressure) socket.on('end', () => close(streamId, REASON.VOLUNTARY)) socket.on('error', () => close(streamId, REASON.NETWORK_ERROR)) socket.on('close', () => close(streamId, REASON.VOLUNTARY)) socket.resume() stream.socket = socket } - for (const data of stream.queue.splice(0)) write(streamId, stream, data) + const queue = stream.queue.splice(0) + stream.queued = 0 + for (const data of queue) write(streamId, stream, data) + pressure() } catch (error) { - close(streamId, error.reason ?? REASON.UNREACHABLE) + if (current()) close(streamId, error.reason ?? REASON.UNREACHABLE) } } function write(streamId, stream, data) { - if (stream.type === STREAM.UDP) return stream.socket.send(data) + if (stream.type === STREAM.UDP) { + // Datagrams may be lost anyway: drop them rather than queue without end. + if (stream.udpPending + data.length > UDP_MAX_PENDING) return + stream.udpPending += data.length + return stream.socket.send(data, () => (stream.udpPending -= data.length)) + } stream.inFlight++ stream.socket.write(data, () => { stream.inFlight-- - stream.processed++ - // Let the client send more once half its buffer has been written out. - if (stream.processed >= BUFFER_PACKETS / 2 && stream.inFlight === 0 && streams.has(streamId)) { - stream.processed = 0 + // Let the client send more once all it sent has been written out and + // at most half its window is left. A client sets its window to the + // CONTINUE's count when it gets one, so it may by then have sent up to + // what `allowed` already counted: adding the full count keeps `allowed` + // a true upper bound, and waiting for half keeps it at most half a + // window above the client's, so a client that has used all of its + // window always gets a CONTINUE. + if (stream.inFlight === 0 && stream.allowed - stream.received <= BUFFER_PACKETS / 2 && streams.get(streamId) === stream) { + stream.allowed += BUFFER_PACKETS sendContinue(streamId, BUFFER_PACKETS) } }) } - ws.on('message', (raw) => { + function receive(raw) { const packet = Buffer.isBuffer(raw) ? raw : Buffer.from(raw) if (packet.length < 5) return const type = packet.readUInt8(0) @@ -353,11 +508,28 @@ function serveClient(ws, request, options) { } else if (type === PACKET.DATA) { const stream = streams.get(streamId) if (!stream) return - if (stream.socket) write(streamId, stream, Buffer.from(payload)) - else stream.queue.push(Buffer.from(payload)) + // Wisp v1 flow control: past its window the client isn't following it. + if (stream.type === STREAM.TCP && ++stream.received > stream.allowed) return close(streamId, REASON.THROTTLED) + const data = Buffer.from(payload) + if (stream.socket) write(streamId, stream, data) + else { + stream.queue.push(data) + stream.queued += data.length + } + pressure() } else if (type === PACKET.CLOSE) { close(streamId, REASON.VOLUNTARY, false) } + } + + ws.on('message', (raw) => { + try { + receive(raw) + } catch (error) { + // One client's bad packet must not take the relay (and its other clients) down. + console.error(`${new Date().toISOString()} client ${client}: ${error.stack ?? error}`) + ws.terminate() + } }) ws.on('close', () => { clearInterval(drain) @@ -377,7 +549,7 @@ function serveClient(ws, request, options) { // --------------------------------------------------------------------------- export function createRelay(options, isAllowed) { - const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false }) + const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_PAYLOAD }) return { serveDns(request, response) { if (!isAllowed(request)) return response.writeHead(403).end() @@ -395,7 +567,7 @@ export function createRelay(options, isAllowed) { } } -if (import.meta.url === pathToFileURL(process.argv[1]).href) { +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const options = parseArgs(process.argv.slice(2)) const relay = createRelay(options, (request) => !options.origins.length || options.origins.includes(request.headers.origin?.replace(/\/+$/, ''))) const server = http.createServer((request, response) => { diff --git a/src/App.svelte b/src/App.svelte index f3f8dbc..a535501 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -15,12 +15,11 @@ import { sessionStore } from './lib/stores/sessions.svelte.js' import { linuxStore } from './lib/stores/linux.svelte.js' import { pruneMachines } from './lib/linux/machineStorage.js' - import { MACHINE_FILE_EXTENSION } from './lib/linux/machineFile.js' + import { MACHINE_FILE_EXTENSION, sharedMachineName, sharedMachineUrl } from './lib/linux/machineFile.js' import { MACHINES, machineKindOf } from './lib/linux/machines.js' - import { downloadBytes } from './lib/runtime/toolchains.js' + import { readZip, zipContents } from './lib/runtime/toolchains.js' import { environmentProblem } from './lib/runtime/wasmer.js' import { decodeText } from './lib/runtime/workspaceSync.js' - import { isIgnoredPath } from './lib/paths.js' import { LANGUAGES, WEB_PORT, runPlanFor } from './lib/languages.js' import { EDITOR_THEMES } from './lib/editorThemes.js' import { themeStore } from './lib/stores/theme.svelte.js' @@ -35,12 +34,17 @@ import LinuxWorkspace from './lib/components/LinuxWorkspace.svelte' import Preview from './lib/components/Preview.svelte' import InternetSettings from './lib/components/InternetSettings.svelte' + import ConfirmDialog from './lib/components/ConfirmDialog.svelte' + import { isIgnoredPath } from './lib/paths.js' import { previewStore } from './lib/stores/preview.svelte.js' import { trackViewport, viewport } from './lib/stores/viewport.svelte.js' const MAX_UPLOAD_BYTES = 2 * 1024 * 1024 const MAX_IMPORT_FILES = 2000 const MAX_IMPORT_BYTES = 50 * 1000 * 1000 + // JSZip reads a whole zip into memory. Big ones are mostly files the import + // skips anyway (binaries, node_modules), so allow some room over the 50 MB. + const MAX_ZIP_BYTES = 200 * 1000 * 1000 const layout = readLayout() const narrowQuery = typeof matchMedia === 'undefined' ? null : matchMedia('(max-width: 760px)') @@ -60,6 +64,8 @@ let terminal = $state(null) let importInput = $state(null) let environmentIssue = $state(null) + // A ?machine= link waiting for the user to agree: { url, host }. + let sharedMachine = $state(null) // Where the last text input focus went: 'editor', 'terminal' or null. let typingIn = $state(null) @@ -273,8 +279,11 @@ if (!project) return const { default: JSZip } = await import('jszip') const zip = new JSZip() - for (const folder of project.folders) zip.folder(folder) - for (const file of project.files) zip.file(file.path, file.content) + // Programs can create files with any name; leave out those that could + // land outside the folder the zip is unpacked into. + const { files, folders, skipped } = zipContents(project) + for (const folder of folders) zip.folder(folder) + for (const file of files) zip.file(file.path, file.content) const blob = await zip.generateAsync({ type: 'blob' }) const safeName = project.name.replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '').toLowerCase() || 'project' const url = URL.createObjectURL(blob) @@ -283,7 +292,7 @@ link.download = `${safeName}.zip` link.click() setTimeout(() => URL.revokeObjectURL(url), 1000) - showNotice(`Exported "${project.name}" as ${safeName}.zip`) + showNotice(`Exported "${project.name}" as ${safeName}.zip${skipped ? ` (left out ${skipped} file${skipped === 1 ? '' : 's'} with names a zip can't hold safely)` : ''}`) } async function importFile(file) { @@ -301,20 +310,30 @@ } // A shared machine: ?machine=https://…/lab.opcode-linux opens it as a new - // project (the server must allow cross-origin requests). - async function openSharedMachine() { + // project (the server must allow cross-origin requests), once the user + // agrees: any page can link here, and the machine runs as soon as it opens. + function openSharedMachine() { const params = new URLSearchParams(location.search) const source = params.get('machine') if (!source) return params.delete('machine') history.replaceState(null, '', `${location.pathname}${params.size ? `?${params}` : ''}${location.hash}`) + const url = sharedMachineUrl(source, location.href) + if (!url) { + showNotice('Could not open the shared machine: the link is not a web address.', 'error') + return + } + sharedMachine = { url: url.href, host: url.host } + } + + async function confirmSharedMachine() { + const { url } = sharedMachine + sharedMachine = null try { - const url = new URL(source, location.href).href - const bytes = await downloadBytes('shared machine', url, 40, (progress) => { + const blob = await linuxStore.downloadShared(url, (progress) => { if (progress?.phase === 'downloading') showNotice(`Downloading the shared machine… ${progress.percent == null ? '' : `${Math.floor(progress.percent)}%`}`) }) - const fallback = decodeURIComponent(url.split('/').pop() || 'Shared machine').replace(/\.opcode-linux$/i, '') - await importMachine(new Blob([bytes]), fallback) + await importMachine(blob, sharedMachineName(url)) } catch (error) { showNotice(`Could not open the shared machine: ${error.message}`, 'error') } @@ -322,35 +341,21 @@ async function importZip(file) { try { + if (file.size > MAX_ZIP_BYTES) throw new Error(`it is ${Math.round(file.size / 1e6)} MB; Opcode can import zips up to ${MAX_ZIP_BYTES / 1e6} MB`) const { default: JSZip } = await import('jszip') const zip = await JSZip.loadAsync(file) - // Sizes as the zip states them (JSZip keeps them in _data): a small zip - // can expand to gigabytes, and the whole workspace is saved as one record. - const sizeOf = (entry) => entry._data?.uncompressedSize ?? 0 - let tooBig = 0 - const entries = Object.values(zip.files).filter((entry) => { - if (entry.dir || isIgnoredPath(entry.name) || entry.name.startsWith('__MACOSX/')) return false - if (sizeOf(entry) > MAX_UPLOAD_BYTES) return (tooBig++, false) - return true - }) - const total = entries.reduce((sum, entry) => sum + sizeOf(entry), 0) - if (entries.length > MAX_IMPORT_FILES || total > MAX_IMPORT_BYTES) { - throw new Error(`it has ${entries.length} files (${Math.round(total / 1e6)} MB); a project can import up to ${MAX_IMPORT_FILES} files and ${MAX_IMPORT_BYTES / 1e6} MB`) - } - // Drop a single wrapping folder (zips of a folder usually have one). - const roots = new Set(entries.map((e) => e.name.split('/')[0])) - const strip = roots.size === 1 && entries.every((e) => e.name.includes('/')) ? `${[...roots][0]}/` : '' + // Unpacked in pieces, to the real sizes (see readZip): a small zip can + // expand to gigabytes, and the whole workspace is saved as one record. + const { files: entries, tooBig } = await readZip(zip, { maxFiles: MAX_IMPORT_FILES, maxFileBytes: MAX_UPLOAD_BYTES, maxTotalBytes: MAX_IMPORT_BYTES }) const files = [] - let skipped = 0 - for (const entry of entries) { - const bytes = await entry.async('uint8array') - const text = bytes.length > MAX_UPLOAD_BYTES ? null : decodeText(bytes) + let skipped = tooBig + for (const { path, bytes } of entries) { + const text = decodeText(bytes) if (text === null) skipped++ - else files.push({ path: entry.name.slice(strip.length), content: text }) + else files.push({ path, content: text }) } const name = file.name.replace(/\.zip$/i, '') || 'Imported Project' projectStore.importProject(name, files) - skipped += tooBig showNotice(`Imported ${files.length} file${files.length === 1 ? '' : 's'}${skipped ? ` (skipped ${skipped} binary or large file${skipped === 1 ? '' : 's'})` : ''}`) } catch (error) { showNotice(`Could not import ${file.name}: ${error.message}`, 'error') @@ -358,9 +363,18 @@ } async function uploadFiles(fileList) { + // The same limits as importing a zip, which also leaves out folders the + // editor never shows (node_modules, .git): a folder that has them would + // otherwise always be over the limit. + const all = [...fileList].filter((file) => !isIgnoredPath(file.webkitRelativePath || file.name)) + const total = all.reduce((sum, file) => sum + (file.size > MAX_UPLOAD_BYTES ? 0 : file.size), 0) + if (all.length > MAX_IMPORT_FILES || total > MAX_IMPORT_BYTES) { + showNotice(`Could not add ${all.length} files (${Math.round(total / 1e6)} MB): you can add up to ${MAX_IMPORT_FILES} files and ${MAX_IMPORT_BYTES / 1e6} MB at a time.`, 'error') + return + } const files = [] let skipped = 0 - for (const file of fileList) { + for (const file of all) { if (file.size > MAX_UPLOAD_BYTES) { skipped++ continue @@ -574,6 +588,17 @@ (showInternet = false)} /> {/if} + {#if sharedMachine} + (sharedMachine = null)} + /> + {/if} + {#if notice}
{notice.text}
{/if} diff --git a/src/lib/components/ConfirmDialog.svelte b/src/lib/components/ConfirmDialog.svelte new file mode 100644 index 0000000..b4146cf --- /dev/null +++ b/src/lib/components/ConfirmDialog.svelte @@ -0,0 +1,55 @@ + + + + +
e.key === 'Escape' && onCancel()} role="presentation"> +
e.stopPropagation()} onkeydown={(e) => { if (e.key === 'Escape') onCancel(); e.stopPropagation() }} use:focusDialog> +

{title}

+ {#if message} +

{message}

+ {/if} + {#if detail} +

{detail}

+ {/if} +
+ + +
+
+
+ + diff --git a/src/lib/linux/LinuxMachine.svelte.js b/src/lib/linux/LinuxMachine.svelte.js index 7681461..abe51be 100644 --- a/src/lib/linux/LinuxMachine.svelte.js +++ b/src/lib/linux/LinuxMachine.svelte.js @@ -6,15 +6,16 @@ // Implements the same terminal interface as ProjectSandbox (attach, detach, // input, resize), so TerminalView works with either. -import { downloadBytes, formatBytes, gunzipIfNeeded } from '../runtime/toolchains.js' +import { downloadBytes, formatBytes } from '../runtime/toolchains.js' import { deleteMachine, loadMachine, saveMachine } from './machineStorage.js' -import { encodeMachineFile } from './machineFile.js' +import { encodeMachineFile, unpackMachineState } from './machineFile.js' import { networkSettings, v86DohServer, v86RelayUrl } from '../stores/network.svelte.js' import { MACHINES, recordedKind } from './machines.js' import { exposeOnHost, fetchFromMachine } from './httpBridge.js' const AUTOSAVE_MS = 2 * 60 * 1000 const SIGNAL_AFTER_ENTER_MS = 300 // see #pumpInput +const MAX_AGENT_LINE = 4096 // the agent's messages are short (see #onAgentOutput) const BIOS = 'linux/seabios.bin' const VGA_BIOS = 'linux/vgabios.bin' @@ -52,11 +53,6 @@ const FRESH_PROMPT = '\x1b[1;32mstudent@opcode\x1b[0m:\x1b[1;34m~\x1b[0m$ ' const url = (path) => new URL(path, document.baseURI).href -async function gunzip(bytes) { - const data = await gunzipIfNeeded(new Uint8Array(bytes)) - return data.buffer.byteLength === data.byteLength ? data.buffer : data.slice().buffer -} - async function gzip(buffer) { const stream = new Blob([buffer]).stream().pipeThrough(new CompressionStream('gzip')) return new Response(stream).blob() @@ -144,6 +140,7 @@ export class LinuxMachine { #autosaveTimer = null #startPromise = null #saveChain = Promise.resolve() + #queuedSave = null #closed = false #hardware = 1 // see HARDWARE in toolchains/linux/make-state.mjs #onVisibility = () => { @@ -273,12 +270,14 @@ export class LinuxMachine { let hardware if (compatible) { this.progress = { label: 'your saved machine', phase: 'loading', percent: null } - state = await gunzip(await saved.state.arrayBuffer()) + state = await unpackMachineState(new Uint8Array(await saved.state.arrayBuffer()), this.#manifest.memoryMB).catch(() => { + throw new Error('Your saved machine is damaged. Reset machine erases it and starts a fresh one.') + }) hardware = saved.hardware ?? 1 this.savedAt = saved.savedAt } else { if (saved) this.#write(style.dim('Your saved machine was made by an older version of Opcode, so this is a fresh one.\r\n')) - state = await gunzip(await loadPristine(this.#kind, (progress) => (this.progress = progress))) + state = await unpackMachineState(await loadPristine(this.#kind, (progress) => (this.progress = progress)), this.#manifest.memoryMB) hardware = this.#manifest.hardware ?? 1 } if (this.#closed) return @@ -295,9 +294,10 @@ export class LinuxMachine { } // The emulated hardware must match the snapshot's (see make-state.mjs). - // Offline, v86's fetch adapter stands in for the relay, with its fetching - // turned off (see #createEmulator): it gives nothing internet access, but - // the preview can still open connections into the machine. + // Online, the relay (v86's wisp adapter) is the machine's only way out. + // Offline, v86's fetch adapter stands in for it, with its fetching turned + // off (see #createEmulator): it gives nothing internet access, but the + // preview can still open connections into the machine. #networkDevice(hardware) { if (hardware < 2) return undefined // v86's default NE2000 card const relay = networkSettings.relay @@ -320,18 +320,25 @@ export class LinuxMachine { virtio_console: true, net_device: this.#networkDevice(hardware), preserve_mac_from_state_image: true, - autostart: true, + autostart: false, // started below, once its network is checked disable_speaker: true, disable_keyboard: true, disable_mouse: true, }) const timeout = setTimeout(() => reject(new Error('The Linux machine did not start')), 60_000) - emulator.add_listener('emulator-started', () => { - clearTimeout(timeout) - // Offline: the fetch adapter must not fetch (see #networkDevice). - if (emulator.network_adapter?.fetch && !networkSettings.relay) { + // v86's fetch adapter would send the machine's web requests (to any + // host, port 80) from this page with fetch(). It exists once v86 has + // loaded, before the machine first runs: turn that off, then start + // it. Whatever the relay setting is by now (it may have changed while + // loading); the relay's own adapter has no fetch. + emulator.add_listener('emulator-loaded', () => { + if (typeof emulator.network_adapter?.fetch === 'function') { emulator.network_adapter.fetch = () => Promise.reject(new TypeError('This machine is offline.')) } + emulator.run() + }) + emulator.add_listener('emulator-started', () => { + clearTimeout(timeout) resolve() }) emulator.add_listener('virtio-console0-output-bytes', (bytes) => this.#write(bytes)) @@ -381,18 +388,29 @@ export class LinuxMachine { this.#emulator?.bus.send('virtio-console1-input-bytes', encoder.encode(`${line}\n`)) } + // Anything in the machine can write to the agent's channel, so long lines + // are dropped and repeated requests coalesce (see save and #reboot). #onAgentOutput(bytes) { this.#agentBuffer += decoder.decode(bytes) let newline while ((newline = this.#agentBuffer.search(/\r?\n/)) !== -1) { - const line = this.#agentBuffer.slice(0, newline).trim() + const line = newline > MAX_AGENT_LINE ? '' : this.#agentBuffer.slice(0, newline).trim() this.#agentBuffer = this.#agentBuffer.slice(newline + 1).replace(/^\n/, '') if (line === 'ok time') this.#clockSynced = true else if (line === 'ports' || line.startsWith('ports ')) this.#setServers(line.slice(6)) - else if (line === 'reboot') this.#bootFresh({ message: 'Rebooting…' }).catch((error) => this.#fail(error)) + else if (line === 'reboot') this.#reboot() else if (line === 'poweroff') this.#powerOff() else if (line === 'save') this.save() // e.g. the tutorial after a lesson } + if (this.#agentBuffer.length > MAX_AGENT_LINE) this.#agentBuffer = '' + } + + // Once, however many times it is asked while rebooting (each holds the + // whole machine's memory). + #reboot() { + this.#booting ??= this.#bootFresh({ message: 'Rebooting…' }) + .catch((error) => this.#fail(error)) + .finally(() => (this.#booting = null)) } #setServers(list) { @@ -416,7 +434,7 @@ export class LinuxMachine { async #bootFresh({ message } = {}) { if (!this.#emulator) return if (message) this.#write(`\r\n${style.dim(message)}\r\n`) - const state = await gunzip(await loadPristine(this.#kind, (progress) => (this.progress = progress))) + const state = await unpackMachineState(await loadPristine(this.#kind, (progress) => (this.progress = progress)), this.#manifest.memoryMB) this.progress = null const hardware = this.#manifest.hardware ?? 1 if (hardware === this.#hardware) { @@ -444,6 +462,12 @@ export class LinuxMachine { /** Throw away this machine and start a fresh one. */ async reset() { + if (this.status === 'error') { + // It could not start (a damaged save, say): erase it and start fresh. + await deleteMachine(this.#projectId) + this.savedAt = null + return this.start() + } await this.start() await deleteMachine(this.#projectId) this.savedAt = null @@ -467,7 +491,11 @@ export class LinuxMachine { /** Save the machine (memory, files and running programs) in the browser. */ save() { if (!this.#emulator || this.status === 'error') return this.#saveChain - this.#saveChain = this.#saveChain.then(async () => { + // A save not started yet will save everything up to now as well, so at + // most one waits behind the one in progress. + if (this.#queuedSave) return this.#queuedSave + this.#queuedSave = this.#saveChain = this.#saveChain.then(async () => { + this.#queuedSave = null if (!this.#emulator) return this.saving = true try { diff --git a/src/lib/linux/httpBridge.js b/src/lib/linux/httpBridge.js index 1296e9d..c146a58 100644 --- a/src/lib/linux/httpBridge.js +++ b/src/lib/linux/httpBridge.js @@ -31,28 +31,55 @@ export function encodeRequest({ method = 'GET', path = '/', headers = [], body } return bytes } -function indexOfBlankLine(bytes) { - for (let i = 0; i + 3 < bytes.length; i++) { +// Limits on what a server in the machine can send back: a response is held +// in memory on the page's main thread. Generous for a preview (a page, its +// scripts, images, a dataset); past them the preview gets an error instead +// of a hung or exhausted tab. +export const MAX_HEAD_BYTES = 64 * 1024 +export const MAX_RESPONSE_BYTES = 64 * 1024 * 1024 + +const TOO_LARGE = "The server's answer is larger than the preview takes (64 MB)." +const HEAD_TOO_LARGE = 'The server sent more headers than the preview takes (64 KB).' + +function indexOfBlankLine(bytes, from = 0) { + for (let i = Math.max(0, from); i + 3 < bytes.length; i++) { if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) return i } return -1 } +/** + * One step through a chunked body from `pos`: { need: true } until the next + * chunk has fully arrived, then { size, start, next } (size 0: the last + * chunk), or { malformed: true }. A chunk size is hex digits, optionally + * followed by ";extensions". + */ +function chunkAt(bytes, pos) { + let end = pos + while (end + 1 < bytes.length && !(bytes[end] === 13 && bytes[end + 1] === 10)) { + if (end - pos > 1024) return { malformed: true } // no size line is this long + end++ + } + if (end + 1 >= bytes.length) return { need: true } + const digits = decoder.decode(bytes.subarray(pos, end)).split(';')[0].trim() + if (!/^[0-9a-f]{1,8}$/i.test(digits)) return { malformed: true } + const size = parseInt(digits, 16) + if (size > MAX_RESPONSE_BYTES) throw new Error(TOO_LARGE) + const start = end + 2 + if (size === 0) return { size, start, next: start } + if (start + size + 2 > bytes.length) return { need: true } + return { size, start, next: start + size + 2 } +} + // Decode a chunked body: { body, complete }. function dechunk(bytes) { const parts = [] - let pos = 0 - for (;;) { - let end = pos - while (end + 1 < bytes.length && !(bytes[end] === 13 && bytes[end + 1] === 10)) end++ - if (end + 1 >= bytes.length) return { body: concat(parts), complete: false } - const size = parseInt(decoder.decode(bytes.subarray(pos, end)).split(';')[0].trim(), 16) - if (Number.isNaN(size)) return { body: concat(parts), complete: true } // malformed: keep what came - pos = end + 2 - if (size === 0) return { body: concat(parts), complete: true } - if (pos + size + 2 > bytes.length) return { body: concat(parts), complete: false } - parts.push(bytes.subarray(pos, pos + size)) - pos += size + 2 + for (let pos = 0; ; ) { + const chunk = chunkAt(bytes, pos) + if (chunk.need) return { body: concat(parts), complete: false } + if (chunk.malformed || chunk.size === 0) return { body: concat(parts), complete: true } // malformed: keep what came + parts.push(bytes.subarray(chunk.start, chunk.start + chunk.size)) + pos = chunk.next } } @@ -66,14 +93,9 @@ function concat(parts) { return out } -/** - * Parse an HTTP response received so far: null until its head has arrived, - * then { status, statusText, headers, body, complete }. `ended`: the server - * closed the connection (the end of a body without a length). - */ -export function parseResponse(bytes, { method = 'GET', ended = false } = {}) { - const blank = indexOfBlankLine(bytes) - if (blank === -1) return null +// The head of a response, up to the blank line at `blank`. +function parseHead(bytes, blank) { + if (blank > MAX_HEAD_BYTES) throw new Error(HEAD_TOO_LARGE) const [statusLine, ...headerLines] = decoder.decode(bytes.subarray(0, blank)).split('\r\n') const match = /^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(statusLine) if (!match) throw new Error('The server did not answer with HTTP.') @@ -87,15 +109,32 @@ export function parseResponse(bytes, { method = 'GET', ended = false } = {}) { const name = line.slice(0, colon).trim() const value = line.slice(colon + 1).trim() const lower = name.toLowerCase() - if (lower === 'content-length') length = Number(value) + if (lower === 'content-length') length = /^\d+$/.test(value) ? Number(value) : null if (lower === 'transfer-encoding' && /chunked/i.test(value)) chunked = true if (!HOP_BY_HOP.has(lower)) headers.push([name, value]) } + if (length !== null && length > MAX_RESPONSE_BYTES) throw new Error(TOO_LARGE) + return { status, statusText: match[2], headers, length, chunked } +} + +const bodiless = (method, status) => method === 'HEAD' || status === 204 || status === 304 || (status >= 100 && status < 200) + +/** + * Parse an HTTP response received so far: null until its head has arrived, + * then { status, statusText, headers, body, complete }. `ended`: the server + * closed the connection (the end of a body without a length). + */ +export function parseResponse(bytes, { method = 'GET', ended = false } = {}) { + const blank = indexOfBlankLine(bytes) + if (blank === -1) { + if (bytes.length > MAX_HEAD_BYTES) throw new Error(HEAD_TOO_LARGE) + return null + } + const { status, statusText, headers, length, chunked } = parseHead(bytes, blank) const rest = bytes.subarray(blank + 4) - const noBody = method === 'HEAD' || status === 204 || status === 304 || (status >= 100 && status < 200) let body let complete - if (noBody) { + if (bodiless(method, status)) { body = new Uint8Array(0) complete = true } else if (chunked) { @@ -108,7 +147,80 @@ export function parseResponse(bytes, { method = 'GET', ended = false } = {}) { body = rest complete = ended } - return { status, statusText: match[2], headers, body: body.slice(), complete } + return { status, statusText, headers, body: body.slice(), complete } +} + +/** + * A response as it arrives over a connection. Bytes go into one growing + * buffer, the head is looked for only in new bytes, and a chunked body is + * walked chunk by chunk as they come, so a large answer costs time in + * proportion to its size; it is parsed in full once, when complete. + */ +export class ResponseReader { + #buffer = new Uint8Array(16 * 1024) + #size = 0 + #method + #scanned = 0 // bytes searched for the end of the head + #head = null // { status, length, chunked, body (offset) } + #next = 0 // chunked: where the next chunk starts + #complete = false + + constructor(method = 'GET') { + this.#method = method + } + + get size() { + return this.#size + } + + /** Add received bytes; throws when the answer goes past the limits. */ + push(data) { + if (this.#size + data.length > MAX_HEAD_BYTES + MAX_RESPONSE_BYTES) throw new Error(TOO_LARGE) + if (this.#size + data.length > this.#buffer.length) { + const grown = new Uint8Array(Math.max(this.#buffer.length * 2, this.#size + data.length)) + grown.set(this.#buffer.subarray(0, this.#size)) + this.#buffer = grown + } + this.#buffer.set(data, this.#size) // copied: v86 reuses its packet buffer + this.#size += data.length + } + + /** The response once complete (or the connection `ended`), else null. Throws for one that isn't HTTP. */ + read(ended = false) { + const bytes = this.#buffer.subarray(0, this.#size) + if (!this.#head) { + // The blank line can straddle two packets: look back three bytes. + const blank = indexOfBlankLine(bytes, this.#scanned - 3) + this.#scanned = bytes.length + if (blank === -1) { + if (bytes.length > MAX_HEAD_BYTES) throw new Error(HEAD_TOO_LARGE) + return null + } + const head = parseHead(bytes, blank) + this.#head = { ...head, body: blank + 4 } + this.#next = blank + 4 + this.#complete = bodiless(this.#method, head.status) + } + const head = this.#head + if (!this.#complete) { + if (head.chunked) { + const body = bytes.subarray(head.body) + for (;;) { + const chunk = chunkAt(body, this.#next - head.body) + if (chunk.need) break + if (chunk.malformed || chunk.size === 0) { + this.#complete = true + break + } + this.#next = head.body + chunk.next + } + } else if (head.length !== null) { + this.#complete = bytes.length - head.body >= head.length + } + } + if (!this.#complete && !ended) return null + return parseResponse(bytes, { method: this.#method, ended }) + } } /** @@ -134,8 +246,7 @@ export async function fetchFromMachine(connect, port, request, { timeoutMs = 30_ function attempt(connect, port, request, { timeoutMs, attemptMs }) { return new Promise((resolve, reject) => { - const chunks = [] - let size = 0 + const reader = new ResponseReader(request.method) let connected = false let settled = false let connection @@ -155,15 +266,16 @@ function attempt(connect, port, request, { timeoutMs, attemptMs }) { // Not connected (yet): worth trying again. const refused = (message) => finish(Object.assign(new Error(message), { retry: true })) const received = (ended) => { + if (settled) return let response try { - response = parseResponse(concat(chunks), { method: request.method, ended }) + response = reader.read(ended) } catch (error) { finish(error) return } if (response?.complete) finish(null, response) - else if (ended) finish(new Error(size ? 'The server closed the connection before its answer was complete.' : 'The server closed the connection without answering.')) + else if (ended) finish(new Error(reader.size ? 'The server closed the connection before its answer was complete.' : 'The server closed the connection without answering.')) } timer = setTimeout(() => refused(`Nothing answered on port ${port}.`), attemptMs) try { @@ -173,14 +285,20 @@ function attempt(connect, port, request, { timeoutMs, attemptMs }) { return } connection.on('connect', () => { + if (settled) return connected = true clearTimeout(timer) timer = setTimeout(() => finish(new Error('The server took too long to answer.')), timeoutMs) connection.write(encodeRequest(request, port)) }) connection.on('data', (data) => { - chunks.push(data.slice()) // v86 reuses its packet buffer - size += data.length + if (settled) return + try { + reader.push(data) + } catch (error) { + finish(error) + return + } received(false) }) connection.on('shutdown', () => received(true)) @@ -194,8 +312,37 @@ function attempt(connect, port, request, { timeoutMs, attemptMs }) { // --------------------------------------------------------------------------- // The preview host (Wasmer SDK protocol; see @wasmer/sdk dist/service-worker.js) // --------------------------------------------------------------------------- +// +// A hidden /.wasmer/host.html frame on the host's origin talks to its +// service worker for this page. Previewed pages share that origin, so their +// scripts can reach into the frame (parent.frames[i]) and run code there. +// Two things keep that from mattering: +// +// - The frame is sandboxed. It keeps its origin, which its service worker +// needs, but can't navigate this tab or open windows, which a previewed +// page could otherwise do through it (the preview frame's own sandbox +// stops it doing so directly). +// - Each server gets a frame of its own, removed when the server's route +// closes and before the next frame for that origin loads, so code a page +// plants in one doesn't see the next server's requests. The Wasmer SDK +// keeps one frame per origin for the page's life; installSdkHostBroker() +// takes over its connection (hosts written by scripts/preview-host.mjs +// hand it over) and routes the SDK's servers through frames made here. +// +// What this can't stop, with one host origin for every server: previewed +// pages share that origin's storage (cookies, localStorage, IndexedDB), and +// a page runs while it is shown. A wildcard host (one origin per server) +// avoids both. -const hosts = new Map() // origin -> Promise +/** The host frame's sandbox (see above). */ +export const HOST_SANDBOX = 'allow-scripts allow-same-origin' +const HOST_PAGE = '/.wasmer/host.html' +// How long to wait for the host to confirm a route closed (it closes the +// route's port) before removing its frame. +const CLOSE_WAIT_MS = 500 + +// origin -> settles once the origin's current host frame is gone +const framesGone = new Map() function withTimeout(promise, ms, message) { let timer @@ -204,7 +351,9 @@ function withTimeout(promise, ms, message) { async function connectHost(origin, timeoutMs) { const iframe = document.createElement('iframe') - const url = new URL('/.wasmer/host.html', origin) + // Before src: sandbox flags apply when the frame navigates. + iframe.setAttribute('sandbox', HOST_SANDBOX) + const url = new URL(HOST_PAGE, origin) url.searchParams.set('parentOrigin', location.origin) iframe.src = url.href iframe.hidden = true @@ -227,7 +376,7 @@ async function connectHost(origin, timeoutMs) { }) iframe.contentWindow.postMessage({ type: 'wasmer-sdk:http-host-connect' }, origin, [channel.port2]) await withTimeout(ready, timeoutMs, `The preview host at ${origin} did not connect.`) - return channel.port1 + return { port: channel.port1, iframe } } catch (error) { iframe.remove() throw error @@ -235,50 +384,178 @@ async function connectHost(origin, timeoutMs) { } /** - * Serve requests to the preview host at `hostUrl` with `handle(request)`, - * which resolves to { status, statusText, headers, body }. Resolves with - * { url, close() }, like the SDK's ports.expose(). + * Register server `serverId` with the host at `origin`, in a host frame of + * its own: frames for one origin come one at a time, each removed before + * the next loads, so code a page planted in one is gone (with the page) + * before another server's requests pass through. `onMessage(data, port)` + * gets what the service worker sends for the server. Resolves with + * { port, close() } once the service worker accepts it. */ -export async function exposeOnHost(hostUrl, handle, { timeoutMs = 15_000 } = {}) { - const { origin } = new URL(hostUrl, location.href) - if (!hosts.has(origin)) { - const connection = connectHost(origin, timeoutMs) - hosts.set(origin, connection) - connection.catch(() => hosts.delete(origin)) +async function openRoute(origin, serverId, onMessage, timeoutMs) { + const previous = framesGone.get(origin) ?? Promise.resolve() + let gone + const thisGone = new Promise((resolve) => (gone = resolve)) + framesGone.set(origin, previous.then(() => thisGone)) + let host + try { + // One server per origin (as the host's service worker allows). + await withTimeout(previous, timeoutMs, 'The preview host is still busy with the last server.') + host = await connectHost(origin, timeoutMs) + } catch (error) { + gone() + throw error + } + const remove = () => { + host.port.close() + host.iframe.remove() + gone() } - const host = await hosts.get(origin) - const serverId = crypto.randomUUID() const route = new MessageChannel() const ready = new Promise((resolve, reject) => { - route.port1.addEventListener('message', async ({ data }) => { + route.port1.addEventListener('message', ({ data }) => { if (data?.serverId !== serverId) return - if (data.type === 'wasmer-sdk:http-ready') return resolve() - if (data.type === 'wasmer-sdk:http-error') return reject(new Error(data.error)) - if (data.type !== 'wasmer-sdk:http-request') return - const reply = { type: 'wasmer-sdk:http-response', serverId, requestId: data.requestId } - try { - const response = await handle({ method: data.method, path: data.path, headers: data.headers ?? [], body: data.body?.length ? new Uint8Array(data.body) : undefined }) - const body = response.body ?? new Uint8Array(0) - route.port1.postMessage({ ...reply, status: response.status, statusText: response.statusText, headers: response.headers, body }, [body.buffer]) - } catch (error) { - route.port1.postMessage({ ...reply, error: error?.message ?? String(error) }) - } + if (data.type === 'wasmer-sdk:http-ready') resolve() + else if (data.type === 'wasmer-sdk:http-error') reject(new Error(data.error)) + onMessage(data, route.port1) }) route.port1.start() }) - host.postMessage({ type: 'wasmer-sdk:http-register', serverId }, [route.port2]) + host.port.postMessage({ type: 'wasmer-sdk:http-register', serverId }, [route.port2]) try { await withTimeout(ready, timeoutMs, 'The preview host did not accept the server.') } catch (error) { route.port1.close() + remove() throw error } + let closing = null return { - url: new URL('/', origin), - async close() { - route.port1.postMessage({ type: 'wasmer-sdk:http-close', serverId }) - await new Promise((resolve) => setTimeout(resolve, 0)) - route.port1.close() + port: route.port1, + close() { + closing ??= (async () => { + // The host passes this on to the service worker, then closes its end + // of the port. Removing the frame before that would leave the + // service worker holding a dead route (and refusing the next one). + const closed = new Promise((resolve) => { + route.port1.addEventListener('close', resolve, { once: true }) + setTimeout(resolve, CLOSE_WAIT_MS) + }) + route.port1.postMessage({ type: 'wasmer-sdk:http-close', serverId }) + await closed + route.port1.close() + remove() + })() + return closing }, } } + +/** + * Serve requests to the preview host at `hostUrl` with `handle(request)`, + * which resolves to { status, statusText, headers, body }. Resolves with + * { url, close() }, like the SDK's ports.expose(). + */ +export async function exposeOnHost(hostUrl, handle, { timeoutMs = 15_000 } = {}) { + const { origin } = new URL(hostUrl, location.href) + const serverId = crypto.randomUUID() + const route = await openRoute( + origin, + serverId, + async (data, port) => { + if (data.type !== 'wasmer-sdk:http-request') return + const reply = { type: 'wasmer-sdk:http-response', serverId, requestId: data.requestId } + try { + const response = await handle({ method: data.method, path: data.path, headers: data.headers ?? [], body: data.body?.length ? new Uint8Array(data.body) : undefined }) + const body = response.body ?? new Uint8Array(0) + port.postMessage({ ...reply, status: response.status, statusText: response.statusText, headers: response.headers, body }, [body.buffer]) + } catch (error) { + port.postMessage({ ...reply, error: error?.message ?? String(error) }) + } + }, + timeoutMs, + ) + return { url: new URL('/', origin), close: () => route.close() } +} + +// --------------------------------------------------------------------------- +// The Wasmer SDK's host frames +// --------------------------------------------------------------------------- + +const HANDOFF = 'opcode:wasmer-host-handoff' +let brokerInstalled = false + +/** + * Sandbox the host frames the Wasmer SDK makes (ports.expose()), and ask + * the host to hand the SDK's connection to this page: hosts written by + * scripts/preview-host.mjs then pass it up instead of starting there, and + * the SDK's servers are routed through host frames made by openRoute(), one + * per server. Other hosts ignore the request and work as before (sandboxed). + * Call before the SDK makes a frame. + */ +export function installSdkHostBroker({ timeoutMs = 15_000 } = {}) { + if (brokerInstalled || typeof HTMLIFrameElement === 'undefined') return + brokerInstalled = true + const sdkFrames = new Set() + // The SDK sets src, then adds the frame to the page: the frame is + // sandboxed before it loads anything. + const src = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src') + Object.defineProperty(HTMLIFrameElement.prototype, 'src', { + ...src, + set(value) { + let url = null + try { + url = new URL(value, document.baseURI) + } catch { + // Not a URL: not the SDK's. + } + if (url?.pathname === HOST_PAGE && url.searchParams.has('parentOrigin') && !this.hasAttribute('sandbox')) { + this.setAttribute('sandbox', HOST_SANDBOX) + url.searchParams.set('opcode', 'handoff') + sdkFrames.add(this) + value = url.href + } + src.set.call(this, value) + }, + }) + addEventListener('message', (event) => { + if (event.data?.type !== HANDOFF) return + const iframe = [...sdkFrames].find((frame) => frame.contentWindow === event.source) + const port = event.ports[0] + if (!iframe || !port || event.origin !== new URL(iframe.src).origin) return + sdkFrames.delete(iframe) + brokerSdkConnection(event.origin, port, timeoutMs) + // The SDK only talks to it through the port, which is now here. + iframe.remove() + }) +} + +// Act as the host for the SDK's connection `sdk`: each server it registers +// gets a route through a frame of its own. +function brokerSdkConnection(origin, sdk, timeoutMs) { + sdk.addEventListener('message', async ({ data, ports }) => { + const owner = ports[0] + if (data?.type !== 'wasmer-sdk:http-register' || typeof data.serverId !== 'string' || !owner) return + const { serverId } = data + let route + let closed = false + owner.addEventListener('message', ({ data: message }) => { + if (message?.type === 'wasmer-sdk:http-close') { + closed = true + route?.close() + owner.close() + } else { + route?.port.postMessage(message) + } + }) + owner.start() + try { + route = await openRoute(origin, serverId, (message) => owner.postMessage(message), timeoutMs) + if (closed) route.close() // closed while it opened + } catch (error) { + owner.postMessage({ type: 'wasmer-sdk:http-error', serverId, error: error?.message ?? String(error) }) + owner.close() + } + }) + sdk.start() + sdk.postMessage({ type: 'wasmer-sdk:http-host-ready' }) +} diff --git a/src/lib/linux/machineFile.js b/src/lib/linux/machineFile.js index 5574e32..d780ac7 100644 --- a/src/lib/linux/machineFile.js +++ b/src/lib/linux/machineFile.js @@ -6,8 +6,13 @@ // {"name": ..., "v86": ..., "memoryMB": ..., "hardware": ..., "savedAt": ...}\n // +import { gunzipIfNeeded, measureGunzip } from '../runtime/toolchains.js' + const MAGIC = 'OPCODE-LINUX 1\n' const MAX_HEADER_BYTES = 64 * 1024 +const MAX_NAME_LENGTH = 100 +const MB = 1024 * 1024 +const DAMAGED = 'This Opcode Linux machine file is damaged.' export const MACHINE_FILE_EXTENSION = '.opcode-linux' @@ -24,14 +29,126 @@ export async function decodeMachineFile(blob) { throw new Error('This is not an Opcode Linux machine file.') } const end = head.indexOf(0x0a, magic.length) - if (end === -1) throw new Error('This Opcode Linux machine file is damaged.') + if (end === -1) throw new Error(DAMAGED) let meta try { meta = JSON.parse(new TextDecoder().decode(head.subarray(magic.length, end))) } catch { - throw new Error('This Opcode Linux machine file is damaged.') + throw new Error(DAMAGED) + } + return { meta: checkMeta(meta), state: blob.slice(end + 1) } +} + +/** + * A machine file's header with only the fields Opcode uses, each of the + * expected type (the file may come from anyone). Throws if the required + * ones are missing. + */ +export function checkMeta(raw) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(DAMAGED) + const { v86, memoryMB, name, hardware, savedAt, machine, alpine } = raw + if (typeof v86 !== 'string' || !v86 || v86.length > 40) throw new Error(DAMAGED) + if (!Number.isInteger(memoryMB) || memoryMB <= 0 || memoryMB > 64 * 1024) throw new Error(DAMAGED) + const meta = { v86, memoryMB } + const cleanName = typeof name === 'string' ? machineName(name) : '' + if (cleanName) meta.name = cleanName + if (Number.isInteger(hardware) && hardware >= 1 && hardware <= 100) meta.hardware = hardware + if (Number.isFinite(savedAt) && savedAt >= 0) meta.savedAt = savedAt + if (machine === 'linux' || machine === 'docker') meta.machine = machine + if (typeof alpine === 'string' && alpine.length <= 40) meta.alpine = alpine + return meta +} + +/** A machine's name as shown in Opcode: one line, without control or text-direction characters, at most 100 characters. */ +export function machineName(text) { + const clean = String(text).replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]+/g, ' ').replace(/\s+/g, ' ').trim() + return [...clean].slice(0, MAX_NAME_LENGTH).join('').trim() +} + +/** + * The most a machine's unpacked state can be. v86 saves only the memory + * pages in use, plus the video memory and the devices (a few MB), so + * memory plus 64 MB is generous. The shipped snapshots unpack to about + * 120 MB (Linux, 256 MB of memory) and 395 MB (Docker, 1 GB). + */ +export function stateLimit(memoryMB) { + return (memoryMB + 64) * MB +} + +/** The most a machine file can be (gzip makes no state bigger by more than a fraction of a percent). */ +export function machineFileLimit(memoryMB) { + return Math.ceil(stateLimit(memoryMB) * 1.01) + MAX_HEADER_BYTES +} + +// v86's own snapshot format: a header (magic, version, total length, info +// length), then the device state. The other format v86 accepts, zstd, sizes +// its buffers from the file itself, so only this one is let through. +const V86_STATE_MAGIC = 0x86768676 + +function checkStateHeader(head, size) { + if (head.length < 16) return false + const view = new DataView(head.buffer, head.byteOffset, 16) + return view.getUint32(0, true) === V86_STATE_MAGIC && view.getUint32(8, true) === size +} + +/** + * Check a machine file's state (gzip) before saving it: it must unpack to + * a v86 snapshot no bigger than the machine's memory allows. Only measures + * it; nothing unpacked is kept. + */ +export async function checkMachineState(state, memoryMB) { + const maxBytes = stateLimit(memoryMB) + const start = new Uint8Array(await state.slice(0, 2).arrayBuffer()) + if (start[0] !== 0x1f || start[1] !== 0x8b) throw new Error(DAMAGED) + let measured + try { + measured = await measureGunzip(state, { maxBytes }) + } catch { + throw new Error(DAMAGED) + } + if (!checkStateHeader(measured.head, measured.size)) throw new Error(DAMAGED) +} + +/** + * Unpack a machine's state (gzip, or already unpacked by the server) for + * v86, refusing anything that unpacks past the limit for `memoryMB` or is + * not a v86 snapshot. Resolves to an ArrayBuffer. + */ +export async function unpackMachineState(bytes, memoryMB) { + let data + try { + data = await gunzipIfNeeded(bytes, { maxBytes: stateLimit(memoryMB) }) + } catch { + throw new Error(DAMAGED) + } + if (!checkStateHeader(data.subarray(0, 16), data.length)) throw new Error(DAMAGED) + return data.buffer.byteLength === data.byteLength ? data.buffer : data.slice().buffer +} + +/** + * The address of a shared machine (?machine=…), or null unless it is a web + * address: http: or https:, or a path on this site. + */ +export function sharedMachineUrl(source, base) { + let url + try { + url = new URL(String(source ?? '').trim(), base) + } catch { + return null + } + return url.protocol === 'https:' || url.protocol === 'http:' ? url : null +} + +/** A name for a shared machine from its address (lab-1.opcode-linux → lab-1). */ +export function sharedMachineName(url, fallback = 'Shared machine') { + const last = new URL(url).pathname.split('/').pop() ?? '' + let decoded = last + try { + decoded = decodeURIComponent(last) + } catch { + // Not valid percent-encoding: use it as it is. } - return { meta, state: blob.slice(end + 1) } + return machineName(decoded.replace(/\.opcode-linux$/i, '')) || fallback } /** diff --git a/src/lib/paths.js b/src/lib/paths.js index 1471c4d..c570c36 100644 --- a/src/lib/paths.js +++ b/src/lib/paths.js @@ -20,7 +20,9 @@ export function normalizePath(input) { for (const segment of raw.split('/')) { if (segment === '' || segment === '.') continue if (segment === '..') throw new Error('Paths cannot contain ".."') - if (/[\0<>:"|?*]/.test(segment)) throw new Error(`"${segment}" contains characters that are not allowed in file names`) + // (Control characters too: names a program can create, but not ones to + // show, type or put in a zip.) + if (/[\0-\x1f\x7f<>:"|?*]/.test(segment)) throw new Error(`"${segment}" contains characters that are not allowed in file names`) segments.push(segment) } if (segments.length === 0) throw new Error('A name is required') @@ -39,6 +41,16 @@ export function tryNormalizePath(input) { } } +/** + * True if a path from the terminal can go into the project as it is: what + * normalizePath would keep unchanged. Others (backslashes, "..", control + * characters, a reserved first folder) stay in the terminal only, as they + * would be renamed when the project is next loaded (see migrateProject). + */ +export function isProjectPath(path) { + return tryNormalizePath(path) === path +} + export function basename(path) { const index = path.lastIndexOf('/') return index === -1 ? path : path.slice(index + 1) diff --git a/src/lib/runtime/ProjectSandbox.svelte.js b/src/lib/runtime/ProjectSandbox.svelte.js index 7e5abef..e2284dc 100644 --- a/src/lib/runtime/ProjectSandbox.svelte.js +++ b/src/lib/runtime/ProjectSandbox.svelte.js @@ -12,14 +12,13 @@ import { isTscInput, isTscReady, prepareTsc, runTsc } from './tsc.js' import { isRReady, prepareR } from './r.js' import { R_VERSION, parseRscriptArgs } from './rlang.js' import { mapCompilerArgs, prettifyOutput, COMPILER_SUPPORT_FILES } from './compilerArgs.js' -import { planPush, planPull, applyPushToBaseline, applyPullToBaseline, emptyBaseline, decodeText, impliedDirs } from './workspaceSync.js' -import { BASHRC, SANDBOX_ENV, SHELL_ARGS, HOST_DIR, HISTORY_FILE, HISTORY_PATH, TOOLS_PATH, TOOLS_SCRIPT } from './shell.js' +import { SYNC_LIMITS, planPush, planPull, planScan, applyPushToBaseline, applyPullToBaseline, emptyBaseline, decodeText, impliedDirs } from './workspaceSync.js' +import { BASHRC, SANDBOX_ENV, SHELL_ARGS, HOST_DIR, HISTORY_FILE, HISTORY_PATH, TOOLS_PATH, TOOLS_SCRIPT, limitHistory } from './shell.js' import { RUNTIME_FAILURE, Shell } from './Shell.svelte.js' import { networkSettings, relayDnsUrl } from '../stores/network.svelte.js' import { TOOLCHAINS, runPlanFor, shellQuote, toolchainsForFiles } from '../languages.js' import { INTERNAL_DIR, WORKSPACE_ROOT, basename, dirname, fromWorkspacePath, isIgnoredPath, toWorkspacePath } from '../paths.js' -const MAX_SYNC_BYTES = 1024 * 1024 const MAX_COMPILER_INPUT_BYTES = 32 * 1024 * 1024 const PUSH_DELAY_MS = 250 const BUSY_PULL_MS = 2000 @@ -57,6 +56,7 @@ export class ProjectSandbox { #openFile #saveHistory #historySavedAt = 0 + #toldSkipped = false // the notice about files left out of the editor #sandbox = null #shellPackage = null #nextShellId = 1 @@ -508,38 +508,57 @@ export class ProjectSandbox { applyPullToBaseline(this.#baseline, snapshot, plan, before) const binaries = plan.binaries.map(({ path, size }) => ({ path, size })) if (JSON.stringify(binaries) !== JSON.stringify(this.binaries)) this.binaries = binaries + if (snapshot.skipped && !this.#toldSkipped) { + this.#toldSkipped = true + this.activeShell?.notice(style.yellow(`Some files in ~ aren't shown in the editor: too many or too large in all (over ${SYNC_LIMITS.files.toLocaleString('en-US')} files or ${SYNC_LIMITS.bytes / 1e6} MB), or with names a project can't use. They're still here in the terminal.`)) + } } // Read /workspace. A quick scan re-reads only files whose size changed. // A folder or file that can't be read fails the scan: a snapshot missing // files would make the pull delete them from the editor. (One removed while - // scanning fails it too; the next sync reads it again.) + // scanning fails it too; the next sync reads it again.) Files past the + // limits, or with names the project can't hold, aren't read (see planScan). async #scan({ quick = false } = {}) { const fs = this.#sandbox.fs - const files = new Map() - const dirs = new Set() + const found = [] + const foundDirs = [] const walk = async (dir) => { const entries = await fs.readDir(toWorkspacePath(dir)) for (const entry of entries) { const path = dir ? `${dir}/${entry.name}` : entry.name if (isIgnoredPath(path)) continue if (entry.kind === 'directory') { - dirs.add(path) + foundDirs.push(path) await walk(path) - } else if (entry.size > MAX_SYNC_BYTES) { - files.set(path, { size: entry.size, text: null }) } else { - const known = this.#baseline.files.get(path) - if (quick && known !== undefined && byteLength(known) === entry.size) { - files.set(path, { size: entry.size, text: known }) - continue - } - files.set(path, { size: entry.size, text: decodeText(await fs.readFile(toWorkspacePath(path))) }) + found.push({ path, size: entry.size }) } } } await walk('') - return { files, dirs } + const project = this.#getProject() + const known = { + files: new Set([...this.#baseline.files.keys(), ...(project?.files ?? []).map((file) => file.path)]), + dirs: new Set([...this.#baseline.dirs, ...(project?.folders ?? [])]), + } + const plan = planScan(found, foundDirs, known) + const files = new Map() + for (const { path, size } of found) { + if (plan.skipped.has(path)) { + files.set(path, { size, text: null, skipped: true }) + } else if (plan.large.has(path)) { + files.set(path, { size, text: null }) + } else { + const previous = this.#baseline.files.get(path) + if (quick && previous !== undefined && byteLength(previous) === size) { + files.set(path, { size, text: previous }) + continue + } + files.set(path, { size, text: decodeText(await fs.readFile(toWorkspacePath(path))) }) + } + } + return { files, dirs: plan.dirs, skipped: plan.skipped.size } } /** Delete a file the editor cannot show (e.g. a compiled program). */ @@ -606,7 +625,8 @@ export class ProjectSandbox { const [shellId, toolchainId, ...command] = raw.split('\0').slice(0, -1) const shell = this.#shellById(shellId) if (this.#hostRequests.has(id)) this.#hostRequests.set(id, shell?.id ?? null) - if (!TOOLCHAINS[toolchainId]) throw new Error(`unknown toolchain ${toolchainId}`) + // (Own keys only: the id comes from the sandbox, and could be "__proto__".) + if (!Object.hasOwn(TOOLCHAINS, toolchainId)) throw new Error(`unknown toolchain ${toolchainId}`) try { await this.ensureToolchain(toolchainId, { verbose: true, shell }) } catch { @@ -621,7 +641,10 @@ export class ProjectSandbox { const history = await this.#sandbox?.fs.readText(HISTORY_FILE).catch(() => '') const line = history?.trimEnd().split('\n').pop() ?? '' const simple = !/[;&|\n]/.test(line) && (line === command[0] || line.startsWith(`${command[0]} `)) - return simple ? line : command.map(shellQuote).join(' ') + const typed = simple ? line : command.map(shellQuote).join(' ') + // Both come from the sandbox: never type control characters (they + // would act as keys, e.g. Enter or Ctrl+C). + return hasControlCharacters(typed) ? '' : typed }) await this.#finishCompileRequest(id, 127, '') } else { @@ -635,7 +658,7 @@ export class ProjectSandbox { if (!this.#sandbox || Date.now() - this.#historySavedAt < 2000) return this.#historySavedAt = Date.now() const text = await this.#sandbox.fs.readText(HISTORY_FILE).catch(() => null) - if (text) this.#saveHistory(text.split('\n').slice(-1000).join('\n')) + if (text) this.#saveHistory(limitHistory(text)) } async #handleCompileRequest(id) { @@ -883,7 +906,8 @@ export class ProjectSandbox { added = false const text = [...sources.values()].join('\n') for (const [path, name] of siblings) { - if (!new RegExp(`\\b${name}\\b`).test(text)) continue + // (The name comes from the sandbox: match it literally.) + if (!new RegExp(`\\b${escapeRegExp(name)}\\b`).test(text)) continue const content = await fs.readText(path).catch(() => null) siblings.delete(path) if (content !== null) { @@ -974,10 +998,10 @@ export class ProjectSandbox { const path = dir ? `${dir}/${entry.name}` : entry.name if (isIgnoredPath(path)) continue if (entry.kind === 'directory') { - node[entry.name] = {} - await walk(path, node[entry.name]) + const child = setOwn(node, entry.name, {}) + await walk(path, child) } else if (total + entry.size <= MAX_COMPILER_INPUT_BYTES) { - node[entry.name] = await fs.readFile(toWorkspacePath(path)) + setOwn(node, entry.name, await fs.readFile(toWorkspacePath(path))) total += entry.size } } @@ -993,10 +1017,10 @@ export class ProjectSandbox { for (const [name, value] of Object.entries(node ?? {})) { const path = prefix ? `${prefix}/${name}` : name if (value instanceof Uint8Array) { - const old = before?.[name] + const old = before && Object.hasOwn(before, name) ? before[name] : undefined if (!(old instanceof Uint8Array) || !sameBytes(old, value)) writes.push([path, value]) } else if (value && typeof value === 'object') { - collect(value, before?.[name], path) + collect(value, before && Object.hasOwn(before, name) ? before[name] : undefined, path) } } } @@ -1016,6 +1040,16 @@ export class ProjectSandbox { } } +// A file or folder in a tree object, by name. Names come from the sandbox, +// so "__proto__" must become an entry rather than the object's prototype. +function setOwn(node, name, value) { + Object.defineProperty(node, name, { value, enumerable: true, writable: true, configurable: true }) + return value +} + +export const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +export const hasControlCharacters = (text) => /[\0-\x1f\x7f]/.test(text) + function sameBytes(a, b) { if (a.length !== b.length) return false for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false diff --git a/src/lib/runtime/rlang.js b/src/lib/runtime/rlang.js index c3cb1dc..3fba25f 100644 --- a/src/lib/runtime/rlang.js +++ b/src/lib/runtime/rlang.js @@ -128,10 +128,19 @@ async function evaluate(webR, code, { halt, file = '' }) { } } +// The webR Opcode ships is patched so R can't run JavaScript (see +// scripts/copy-npm-toolchains.mjs). Check before running anything, so a copy +// from before the patch (or a webR that changed) fails safe. +const NO_JS_CHECK = 'tryCatch({ webr::eval_js("0"); "unpatched" }, error = function(e) if (identical(conditionMessage(e), "eval_js is not available in Opcode")) "patched" else "unpatched")' + export function createR(WebR, baseUrl) { async function start() { const webR = new WebR({ baseUrl, interactive: false }) await webR.init() + if ((await webR.evalRString(NO_JS_CHECK)) !== 'patched') { + webR.close() + throw new Error('this copy of webR lets R run JavaScript: run node scripts/copy-npm-toolchains.mjs --force') + } await webR.evalRVoid(SETUP) return webR } diff --git a/src/lib/runtime/shell.js b/src/lib/runtime/shell.js index a6493cc..26faf97 100644 --- a/src/lib/runtime/shell.js +++ b/src/lib/runtime/shell.js @@ -39,6 +39,21 @@ export const TERMCAP = String.raw`xterm-256color|xterm|xterm with 256 colors:am: export const HISTORY_PATH = `${INTERNAL_DIR}/bash_history` export const HISTORY_FILE = `${WORKSPACE_ROOT}/${HISTORY_PATH}` +// What of the shell's history is saved with the project. A program can write +// the history file, so cap the lines kept, their length and the total. +const HISTORY_LINES = 1000 +const HISTORY_LINE_CHARS = 4096 +const HISTORY_CHARS = 256 * 1024 + +/** The shell history to save: the last lines, long ones left out. */ +export function limitHistory(text) { + const lines = String(text ?? '').split('\n').filter((line) => line.length <= HISTORY_LINE_CHARS).slice(-HISTORY_LINES) + let total = 0 + let start = lines.length + while (start > 0 && total + lines[start - 1].length + 1 <= HISTORY_CHARS) total += lines[--start].length + 1 + return lines.slice(start).join('\n') +} + // The shell's id as bash expands it. Defined outside BASHRC, where ${...} // would be read as JavaScript interpolation. const SHELL_ID_EXPANSION = '${OPCODE_SHELL:-1}' diff --git a/src/lib/runtime/toolchains.js b/src/lib/runtime/toolchains.js index a80ee60..62aff20 100644 --- a/src/lib/runtime/toolchains.js +++ b/src/lib/runtime/toolchains.js @@ -5,6 +5,7 @@ import { getWasmer } from './wasmer.js' import { DOTNET_MANAGED, JAVA_HOME, RUST_SYSROOT, RUST_TARGET, SHELL_PACKAGES, TOOLCHAINS } from '../languages.js' +import { isIgnoredPath, tryNormalizePath } from '../paths.js' const CACHE_NAME = 'opcode-toolchains-v1' const loads = new Map() @@ -71,23 +72,45 @@ async function cachedFetch(url) { /** * Download a file with progress, keeping a copy in the Cache API so the - * next visit loads it from disk. Resolves to its bytes. + * next visit loads it from disk. Resolves to its bytes. Only for Opcode's + * own files: anything cached stays there. */ export async function downloadBytes(label, url, sizeHintMB, emit) { const { response, cached } = await cachedFetch(url) if (!response.ok) throw new Error(`Could not download ${label} (HTTP ${response.status})`) - const total = Number(response.headers.get('content-length')) || (cached ? null : sizeHintMB * 1e6) + return readBody(response, { label, sizeHintMB: cached ? null : sizeHintMB, emit: cached ? null : emit }) +} + +/** + * Download a file from somewhere else (a shared machine): not cached, and + * given up once it passes `maxBytes`. Resolves to its bytes. + */ +export async function downloadCapped(label, url, { maxBytes, sizeHintMB = null, emit } = {}) { + const response = await fetch(url, { cache: 'no-store', credentials: 'omit' }) + if (!response.ok) throw new Error(`Could not download ${label} (HTTP ${response.status})`) + return readBody(response, { label, maxBytes, sizeHintMB, emit }) +} + +/** A response's body as bytes, with progress, stopping past `maxBytes`. */ +export async function readBody(response, { label = 'file', maxBytes = Infinity, sizeHintMB = null, emit = null } = {}) { + const tooBig = () => new Error(`The file is larger than ${formatBytes(maxBytes)}.`) + const declared = Number(response.headers.get('content-length')) || null + if (declared > maxBytes) throw tooBig() + const total = declared ?? (sizeHintMB ? sizeHintMB * 1e6 : null) const reader = response.body.getReader() const chunks = [] let received = 0 for (;;) { const { done, value } = await reader.read() if (done) break - chunks.push(value) received += value.length - if (!cached) { - emit({ label, phase: 'downloading', percent: total ? Math.min(99, (received / total) * 100) : null, downloadedBytes: received, totalBytes: total }) + if (received > maxBytes) { + // The server can send more than it said it would. + reader.cancel().catch(() => {}) + throw tooBig() } + chunks.push(value) + emit?.({ label, phase: 'downloading', percent: total ? Math.min(99, (received / total) * 100) : null, downloadedBytes: received, totalBytes: total }) } const bytes = new Uint8Array(received) let offset = 0 @@ -98,15 +121,71 @@ export async function downloadBytes(label, url, sizeHintMB, emit) { return bytes } +const isGzip = (bytes) => bytes[0] === 0x1f && bytes[1] === 0x8b + +/** + * Decompress gzip data, giving up once the output passes `maxBytes` (a few + * hundred kilobytes of gzip can unpack to gigabytes). Hosts that serve .gz + * files with Content-Encoding: gzip hand over already-decompressed bytes, + * which are returned unchanged. + */ +export async function gunzipIfNeeded(bytes, { maxBytes = Infinity } = {}) { + if (!isGzip(bytes)) { + if (bytes.length > maxBytes) throw unpacksTooBig(maxBytes) + return bytes + } + // gzip ends with the unpacked size (mod 4 GB), so the output usually fits + // in one buffer, sized up front. It is only a hint: the cap still holds, + // but data that says it is over the cap is (its last part alone would be). + const stated = bytes.length >= 18 ? new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 4, 4).getUint32(0, true) : 0 + if (stated > maxBytes) throw unpacksTooBig(maxBytes) + let out = new Uint8Array(Math.min(maxBytes, stated || 1 << 20)) + let length = 0 + await inflate(new Blob([bytes]), maxBytes, (chunk) => { + if (length + chunk.length > out.length) { + const grown = new Uint8Array(Math.min(maxBytes, Math.max(out.length * 2, length + chunk.length))) + grown.set(out.subarray(0, length)) + out = grown + } + out.set(chunk, length) + length += chunk.length + }) + return length === out.length ? out : out.subarray(0, length) +} + /** - * Decompress gzip data. Hosts that serve .gz files with - * Content-Encoding: gzip hand over already-decompressed bytes, which are - * returned unchanged. + * The unpacked size of gzip data and its first `headBytes` bytes, without + * keeping the rest (to check a file before saving it). */ -export async function gunzipIfNeeded(bytes) { - if (bytes[0] !== 0x1f || bytes[1] !== 0x8b) return bytes - const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip')) - return new Uint8Array(await new Response(stream).arrayBuffer()) +export async function measureGunzip(blob, { maxBytes = Infinity, headBytes = 16 } = {}) { + const head = new Uint8Array(headBytes) + let size = 0 + await inflate(blob, maxBytes, (chunk) => { + if (size < headBytes) head.set(chunk.subarray(0, headBytes - size), size) + size += chunk.length + }) + return { size, head: head.subarray(0, Math.min(size, headBytes)) } +} + +async function inflate(blob, maxBytes, onChunk) { + const reader = blob.stream().pipeThrough(new DecompressionStream('gzip')).getReader() + let size = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) return size + size += value.length + if (size > maxBytes) { + reader.cancel().catch(() => {}) + throw unpacksTooBig(maxBytes) + } + onChunk(value) + } +} + +function unpacksTooBig(maxBytes) { + const error = new RangeError(`It unpacks to more than ${formatBytes(maxBytes)}.`) + error.code = 'TOO_BIG' + return error } async function loadLocalToolchain(toolchain, emit) { @@ -147,6 +226,101 @@ export function untar(bytes) { return files } +/** + * The files in a zip (a JSZip object) to import as a project: [{ path, bytes }], + * without a single wrapping folder, and how many were too big. The sizes a + * zip states can be false, and JSZip only checks them after unpacking an + * entry in full, so each entry is unpacked in pieces and given up once it + * passes `maxFileBytes`; past `maxTotalBytes` in all, the import fails. + */ +export async function readZip(zip, { maxFiles, maxFileBytes, maxTotalBytes }) { + const limits = `a project can import up to ${maxFiles} files and ${Math.round(maxTotalBytes / 1e6)} MB` + // Stated sizes (JSZip keeps them in _data): an early, cheap check only. + const statedSize = (entry) => entry._data?.uncompressedSize ?? 0 + let tooBig = 0 + const entries = Object.values(zip.files).filter((entry) => { + if (entry.dir || isIgnoredPath(entry.name) || entry.name.startsWith('__MACOSX/')) return false + if (statedSize(entry) > maxFileBytes) return (tooBig++, false) + return true + }) + const stated = entries.reduce((sum, entry) => sum + statedSize(entry), 0) + if (entries.length > maxFiles || stated > maxTotalBytes) { + throw new Error(`it has ${entries.length} files (${Math.round(stated / 1e6)} MB); ${limits}`) + } + // Drop a single wrapping folder (zips of a folder usually have one). + const roots = new Set(entries.map((e) => e.name.split('/')[0])) + const strip = roots.size === 1 && entries.every((e) => e.name.includes('/')) ? `${[...roots][0]}/` : '' + const files = [] + let total = 0 + for (const entry of entries) { + // JSZip fails an entry whose real size isn't the stated one, once it + // has unpacked it (within maxFileBytes, here). + const bytes = await readZipEntry(entry, maxFileBytes).catch(() => { + throw new Error('it is damaged') + }) + if (!bytes) { + tooBig++ + continue + } + total += bytes.length + if (total > maxTotalBytes) throw new Error(`it unpacks to more than ${Math.round(maxTotalBytes / 1e6)} MB; ${limits}`) + files.push({ path: entry.name.slice(strip.length), bytes }) + } + return { files, tooBig } +} + +/** A zip entry's bytes, or null once it passes `maxBytes` (unpacking stops there). */ +export function readZipEntry(entry, maxBytes) { + return new Promise((resolve, reject) => { + const chunks = [] + let size = 0 + let stopped = false + const stream = entry.internalStream('uint8array') + stream + .on('data', (chunk) => { + if (stopped) return + size += chunk.length + if (size > maxBytes) { + stopped = true + chunks.length = 0 + stream.pause() + resolve(null) + return + } + chunks.push(chunk) + }) + .on('error', (error) => stopped || reject(error)) + .on('end', () => { + if (stopped) return + const bytes = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { + bytes.set(chunk, offset) + offset += chunk.length + } + resolve(bytes) + }) + .resume() + }) +} + +/** + * A project's files and folders as they go into an exported zip: only paths + * the project itself accepts (no "..", absolute paths or reserved names), so + * a file a program created with a hostile name can't escape the folder the + * zip is unpacked into. `skipped` counts what was left out. + */ +export function zipContents({ files, folders }) { + let skipped = 0 + const safe = (path) => tryNormalizePath(path) ?? (skipped++, null) + const safeFolders = folders.map(safe).filter(Boolean) + const safeFiles = files.flatMap((file) => { + const path = safe(file.path) + return path ? [{ path, content: file.content }] : [] + }) + return { files: safeFiles, folders: safeFolders, skipped } +} + // Rust: rustc as a command, with the standard library bundled as files at // RUST_SYSROOT (both downloads report progress together). async function loadRustToolchain(toolchain, emit) { diff --git a/src/lib/runtime/wasmer.js b/src/lib/runtime/wasmer.js index 851c840..f7b9d23 100644 --- a/src/lib/runtime/wasmer.js +++ b/src/lib/runtime/wasmer.js @@ -4,6 +4,7 @@ import { APPLE_MOBILE_RUNTIME_PAGES, capSharedMemories, isAppleMobile } from './appleMobile.js' import appleWorkerUrl from './wasmerWorker.apple.js?worker&url' import { installWasmerMirror } from './wasmerMirror.js' +import { installSdkHostBroker } from '../linux/httpBridge.js' let clientPromise = null @@ -53,6 +54,8 @@ export function getWasmer() { if (problem) throw new EnvironmentError(problem) installAppleMobileWorkarounds() installWasmerMirror() + // The SDK's web preview host frames: sandboxed, one per server (see httpBridge.js). + installSdkHostBroker() const { Wasmer } = await importSdk() const client = new Wasmer() await client.ready() diff --git a/src/lib/runtime/wasmerMirror.js b/src/lib/runtime/wasmerMirror.js index e25ea8c..982b6d5 100644 --- a/src/lib/runtime/wasmerMirror.js +++ b/src/lib/runtime/wasmerMirror.js @@ -10,17 +10,37 @@ const REGISTRY = 'https://registry.wasmer.io/graphql' const CDN_FILES = 'https://cdn.wasmer.io/webcimages/' +// After a failed load of the mirror (offline, a 5xx), how long requests go to +// Wasmer before it is tried again. +export const MIRROR_RETRY_MS = 5000 /** Answer the SDK's registry and package requests from `wasmer/` under `base`. */ export function installWasmerMirror(scope = globalThis, base = scope.document?.baseURI ?? scope.location.href) { if (scope.fetch.opcodeMirror) return const realFetch = scope.fetch.bind(scope) + // The registry, or null for a build without the mirror. Only a definite + // answer is kept: a failure is tried again later, so one dropped request + // doesn't send the rest of the session to Wasmer unpinned. let mirror = null - const loadMirror = () => - (mirror ??= realFetch(new URL('wasmer/registry.json', base)) - .then((response) => (response.ok ? response.json() : null)) - .then((registry) => registry && { ...registry, files: new Set(Object.values(registry.packages).flatMap(fileNames)) }) - .catch(() => null)) + let failedAt = -Infinity + const loadMirror = () => { + if (mirror) return mirror + if (Date.now() - failedAt < MIRROR_RETRY_MS) return Promise.resolve(null) + return (mirror = realFetch(new URL('wasmer/registry.json', base)) + .then(async (response) => { + // Not there: this build has no mirror (supported), so don't ask again. + if (response.status === 404 || response.status === 410) return null + if (!response.ok) throw new Error(`HTTP ${response.status}`) + // Something other than JSON is a host's fallback page: no mirror either. + const registry = await response.json().catch(() => null) + return registry?.packages ? { ...registry, files: new Set(Object.values(registry.packages).flatMap(fileNames)) } : null + }) + .catch(() => { + mirror = null + failedAt = Date.now() + return null + })) + } async function mirroredFetch(input, init) { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input?.url diff --git a/src/lib/runtime/workspaceSync.js b/src/lib/runtime/workspaceSync.js index 4ba07f0..8db782a 100644 --- a/src/lib/runtime/workspaceSync.js +++ b/src/lib/runtime/workspaceSync.js @@ -4,10 +4,55 @@ // return the operations to apply. ProjectSandbox performs the I/O. // // Baseline: { files: Map, dirs: Set } -// Snapshot (from the sandbox): { files: Map, dirs: Set } +// Snapshot (from the sandbox): { files: Map, dirs: Set } // where `text` is the file contents, or null for binary or oversized files. +// `skipped` files (see planScan) are left out of the editor: it keeps its +// own copy, if it has one, and nothing is deleted on either side. -import { ancestors, isWithin } from '../paths.js' +import { ancestors, isProjectPath, isWithin } from '../paths.js' + +// How much of /workspace the editor mirrors, so a program can't grow a +// project until it can't be saved or shown. Generous: imports allow 2,000 +// files and 50 MB (see App.svelte). +export const SYNC_LIMITS = { fileBytes: 1024 * 1024, files: 5000, bytes: 50 * 1000 * 1000 } + +/** + * Which of the files a scan found to read into the editor. `files`: + * [{ path, size }]; `dirs`: [path]; `known`: { files, dirs }, paths the + * editor or the baseline already has, which go first so new files can't + * push them out. Returns { read, large, skipped, dirs } (Sets): large files + * are shown as binaries (as before); skipped ones stay in the terminal only: + * names the project can't hold as they are, and anything past the limits. + * `dirs` are the folders to mirror. + */ +export function planScan(files, dirs, known, limits = SYNC_LIMITS) { + const read = new Set() + const large = new Set() + const skipped = new Set() + let count = 0 + let bytes = 0 + const byPath = (a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0) + const knownFirst = [...files.filter((f) => known.files.has(f.path)).sort(byPath), ...files.filter((f) => !known.files.has(f.path)).sort(byPath)] + for (const { path, size } of knownFirst) { + if (!isProjectPath(path)) skipped.add(path) + else if (size > limits.fileBytes) large.add(path) + else if (bytes + size > limits.bytes || (!known.files.has(path) && count >= limits.files)) skipped.add(path) + else { + read.add(path) + count++ + bytes += size + } + } + // Folders: the ones the editor knows, those of files it shows, then new + // ones up to the limit. (A folder left out is also left out of the + // baseline, so a push never removes it from the terminal.) + const shown = new Set() + for (const path of read) for (const dir of ancestors(path)) shown.add(dir) + const valid = [...dirs].filter(isProjectPath).sort() + const mirrored = new Set(valid.filter((dir) => known.dirs.has(dir) || shown.has(dir))) + for (const dir of valid) if (mirrored.size < limits.files) mirrored.add(dir) + return { read, large, skipped, dirs: mirrored } +} export function emptyBaseline() { return { files: new Map(), dirs: new Set() } @@ -90,8 +135,13 @@ export function planPull(snapshot, editorFiles, editorFolders, baseline) { for (const [path, entry] of snapshot.files) { const editor = editorByPath.get(path) const base = baseline.files.get(path) + if (entry.skipped) { + // Not mirrored (see planScan): the editor keeps its copy, if any. + if (!editor && binaries.length < SYNC_LIMITS.files) binaries.push({ path, size: entry.size }) + continue + } if (entry.text === null) { - binaries.push({ path, size: entry.size }) + if (binaries.length < SYNC_LIMITS.files) binaries.push({ path, size: entry.size }) // A text file the terminal overwrote with binary data (e.g. a compiler // output) leaves the editor unless it has unsynced edits. if (editor && editor.content === base) deletes.push(path) @@ -140,6 +190,8 @@ export function applyPullToBaseline(baseline, snapshot, plan, editorFiles) { // writes (or removes) them. const files = new Map() for (const [path, entry] of snapshot.files) { + // A skipped file keeps what the baseline had (the editor didn't change). + if (entry.skipped && baseline.files.has(path)) files.set(path, baseline.files.get(path)) if (entry.text === null) continue if (editorPaths.has(path) || baseline.files.has(path)) files.set(path, entry.text) } diff --git a/src/lib/stores/linux.svelte.js b/src/lib/stores/linux.svelte.js index f653794..9f769b9 100644 --- a/src/lib/stores/linux.svelte.js +++ b/src/lib/stores/linux.svelte.js @@ -5,8 +5,9 @@ import { LinuxMachine, loadManifest } from '../linux/LinuxMachine.svelte.js' import { deleteMachine, saveMachine } from '../linux/machineStorage.js' -import { decodeMachineFile, incompatibility } from '../linux/machineFile.js' -import { recordedKind } from '../linux/machines.js' +import { checkMachineState, decodeMachineFile, incompatibility, machineFileLimit, machineName } from '../linux/machineFile.js' +import { MACHINES, recordedKind } from '../linux/machines.js' +import { downloadCapped } from '../runtime/toolchains.js' import { projectStore } from './projects.svelte.js' const state = $state({ machine: null }) @@ -40,13 +41,25 @@ export const linuxStore = { const kind = recordedKind(meta) const problem = incompatibility(meta, await loadManifest(kind)) if (problem) throw new Error(`This machine can't be opened here. ${problem}`) - const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : fallbackName + // Before it is saved or opened: it is unpacked every time it starts. + await checkMachineState(snapshot, meta.memoryMB) + const name = meta.name || machineName(fallbackName) || 'Shared machine' const id = projectStore.createProject(name, kind, { activate: false }) await saveMachine(id, { state: snapshot, savedAt: meta.savedAt ?? Date.now(), v86: meta.v86, memoryMB: meta.memoryMB, hardware: meta.hardware ?? 1, machine: kind }) projectStore.setActiveProject(id) return name }, + /** + * Download a shared machine file (?machine=…) without keeping it in the + * browser's cache, and no bigger than any machine can be. Resolves to a Blob. + */ + async downloadShared(url, onProgress) { + const manifests = await Promise.all(Object.keys(MACHINES).map((kind) => loadManifest(kind))) + const maxBytes = machineFileLimit(Math.max(...manifests.map((manifest) => manifest.memoryMB))) + return new Blob([await downloadCapped('shared machine', url, { maxBytes, sizeHintMB: 40, emit: onProgress })]) + }, + /** Forget a deleted project's machine. */ async remove(projectId) { if (state.machine?.projectId === projectId) { diff --git a/src/lib/stores/preview.svelte.js b/src/lib/stores/preview.svelte.js index fa6abef..d5e4e7f 100644 --- a/src/lib/stores/preview.svelte.js +++ b/src/lib/stores/preview.svelte.js @@ -23,8 +23,31 @@ export function previewHostFor(name, host = PREVIEW_HOST) { return host.replace('*', name) } -// DNS-safe and hard to guess: a server's address works for whoever has it -// while its tab is open. +/** + * Why `host` can't be the preview host for a page at `pageOrigin`, or null. + * Previewed pages own the host's origin: on the app's own origin they could + * script the app itself. + */ +export function previewHostProblem(host = PREVIEW_HOST, pageOrigin = globalThis.location?.origin) { + let origin + try { + origin = new URL(previewHostFor('p0', host)).origin + } catch { + return `The web preview host "${host}" is not a valid address.` + } + if (pageOrigin && origin === pageOrigin) { + return `The web preview host (${host}) is this site's own address. Previewed pages would control the site, so the preview is off: set the preview host to a separate origin (see docs/deploying.md, "Web preview host").` + } + return null +} + +// DNS-safe and hard to guess. A server's address works while its Opcode tab +// is open, for pages whose browser storage partition holds the service +// worker that routes it: in browsers that partition storage by top-level +// site (Chrome, Safari, Firefox), pages of the app's own site, such as the +// preview or Open in a new tab, but not other sites, which get the host's +// "no server" page. The name keeps those pages from guessing a server's +// address. function newServerName() { const bytes = crypto.getRandomValues(new Uint8Array(8)) return `p${[...bytes].map((byte) => (byte % 36).toString(36)).join('')}` @@ -166,6 +189,12 @@ class PreviewStore { this.status = 'stopped' return } + const problem = previewHostProblem() + if (problem) { + this.status = 'error' + this.error = problem + return + } // Before any wait: a show() of the same server meanwhile joins this one. this.status = 'connecting' this.error = null diff --git a/src/lib/stores/projects.svelte.js b/src/lib/stores/projects.svelte.js index 6e70ed2..db0a5d1 100644 --- a/src/lib/stores/projects.svelte.js +++ b/src/lib/stores/projects.svelte.js @@ -7,7 +7,7 @@ import { LoadError, loadState, saveState, saveStateNow } from '../persistence.js' import { LANGUAGES, languageForFiles } from '../languages.js' -import { ancestors, dirname, extname, isWithin, joinPath, normalizePath, reparent, stem, tryNormalizePath } from '../paths.js' +import { ancestors, dirname, extname, isProjectPath, isWithin, joinPath, normalizePath, reparent, stem, tryNormalizePath } from '../paths.js' const SAVE_DELAY_MS = 400 @@ -413,20 +413,33 @@ export const projectStore = { applySandboxChanges(projectId, { upserts = [], deletes = [], addFolders = [], removeFolders = [] }) { const project = findProject(projectId) if (!project) return + // Linear in the number of files (a program can make many). + const byPath = new Map(project.files.map((f) => [f.path, f])) + const added = [] for (const { path, content } of upserts) { - const file = project.files.find((f) => f.path === path) + // Only names the project can hold as they are (the sync leaves others + // in the terminal; see planScan). + if (!isProjectPath(path)) continue + const file = byPath.get(path) if (file) file.content = content - else project.files.push(newFile(path, content)) + else { + const created = newFile(path, content) + byPath.set(path, created) + added.push(created) + } } + if (added.length) project.files.push(...added) if (deletes.length) { const gone = new Set(deletes) removeFiles(project, (f) => gone.has(f.path)) } const removed = new Set(removeFolders) - project.folders = project.folders.filter((dir) => !removed.has(dir)) - for (const dir of addFolders) if (!project.folders.includes(dir)) project.folders.push(dir) + const folders = new Set(project.folders.filter((dir) => !removed.has(dir))) + for (const dir of addFolders) if (isProjectPath(dir)) folders.add(dir) // Folders that now contain files no longer need an explicit entry. - project.folders = project.folders.filter((dir) => !project.files.some((f) => isWithin(f.path, dir) && f.path !== dir)) + const filled = new Set(project.files.flatMap((f) => ancestors(f.path))) + const kept = [...folders].filter((dir) => !filled.has(dir)) + if (kept.length !== project.folders.length || kept.some((dir, i) => dir !== project.folders[i])) project.folders = kept if (upserts.length || deletes.length) touch(project) scheduleSave() }, diff --git a/tests/e2e/linux.spec.js b/tests/e2e/linux.spec.js index 394724f..bb30bd8 100644 --- a/tests/e2e/linux.spec.js +++ b/tests/e2e/linux.spec.js @@ -98,8 +98,15 @@ test('downloads a machine and opens it from a file and from a link', async ({ pa // So does a link to the file. await page.route('**/shared/lab.opcode-linux', (route) => route.fulfill({ path: file, contentType: 'application/octet-stream' })) await page.goto('/?machine=shared/lab.opcode-linux') - await expectProjects(page, 'Lab Template', 3) + // It asks first, and does nothing if the answer is no. + const ask = page.getByRole('alertdialog') + await expect(ask).toContainText('Open a shared machine from localhost:4173?') await expect(page).not.toHaveURL(/machine=/) + await ask.getByRole('button', { name: 'Cancel' }).click() + await expectProjects(page, 'Lab Template', 2) + await page.goto('/?machine=shared/lab.opcode-linux') + await page.getByRole('alertdialog').getByRole('button', { name: 'Open' }).click() + await expectProjects(page, 'Lab Template', 3) await expect(page.locator('.linux-workspace .status')).toContainText('Running', { timeout: 60_000 }) await term.type('cat lab/README') await expect(term.rows).toContainText('prepared by the teacher') diff --git a/tests/httpBridge.test.js b/tests/httpBridge.test.js index 4c3e78f..af6f87a 100644 --- a/tests/httpBridge.test.js +++ b/tests/httpBridge.test.js @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { encodeRequest, fetchFromMachine, parseResponse } from '../src/lib/linux/httpBridge.js' +import { encodeRequest, fetchFromMachine, MAX_HEAD_BYTES, MAX_RESPONSE_BYTES, parseResponse, ResponseReader } from '../src/lib/linux/httpBridge.js' const text = (bytes) => new TextDecoder().decode(bytes) const bytes = (string) => new TextEncoder().encode(string) @@ -35,6 +35,26 @@ describe('parseResponse', () => { expect(parseResponse(bytes(raw.slice(0, -7))).complete).toBe(false) }) + it('takes only hex digits as a chunk size', () => { + // Negative and non-hex sizes once looped forever (security-review-pocs/preview/chunk.mjs). + for (const size of ['-2', '-1', '+4', '0x4', '4 4', '', ' ', 'g', '1z', '١']) { + const started = Date.now() + const response = parseResponse(bytes(`HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n${size}\r\nAAAA\r\n0\r\n\r\n`)) + expect(response.complete, size).toBe(true) + expect(text(response.body), size).toBe('ok') + expect(Date.now() - started).toBeLessThan(1000) + } + expect(text(parseResponse(bytes('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nA\r\n0123456789\r\na;x=y\r\n0123456789\r\n0\r\n\r\n')).body)).toBe('01234567890123456789') + }) + + it('refuses answers past the size limits', () => { + expect(() => parseResponse(bytes(`HTTP/1.1 200 OK\r\nContent-Length: ${MAX_RESPONSE_BYTES + 1}\r\n\r\n`))).toThrow(/larger/) + expect(() => parseResponse(bytes('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nffffffff\r\n'))).toThrow(/larger/) + expect(() => parseResponse(bytes(`HTTP/1.1 200 OK\r\nX: ${'a'.repeat(MAX_HEAD_BYTES)}`))).toThrow(/headers/) + expect(() => parseResponse(bytes(`HTTP/1.1 200 OK\r\nX: ${'a'.repeat(MAX_HEAD_BYTES)}\r\n\r\n`))).toThrow(/headers/) + expect(parseResponse(bytes('HTTP/1.1 200 OK\r\nContent-Length: 5, 5\r\n\r\nhello'), { ended: true }).complete).toBe(true) + }) + it('reads to the end of the connection without a length, and knows bodiless answers', () => { const raw = bytes('HTTP/1.0 200 OK\r\nServer: SimpleHTTP\r\n\r\n

hi

') expect(parseResponse(raw).complete).toBe(false) @@ -48,6 +68,66 @@ describe('parseResponse', () => { }) }) +describe('ResponseReader', () => { + const feed = (raw, size) => { + const reader = new ResponseReader('GET') + const data = bytes(raw) + for (let i = 0; i < data.length; i += size) { + reader.push(data.subarray(i, i + size)) + const response = reader.read(false) + if (response) return { response, at: Math.min(i + size, data.length), length: data.length } + } + return { response: null } + } + + it('finds the end of the answer however the bytes arrive', () => { + const chunked = 'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nnot \r\n5;ext=1\r\nfound\r\n0\r\n\r\n' + const sized = 'HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello' + for (const size of [1, 2, 3, 7, 1000]) { + const a = feed(chunked, size) + expect(text(a.response.body)).toBe('not found') + expect(a.at).toBeGreaterThanOrEqual(chunked.length - 4) // the trailer's last CRLF is optional + const b = feed(sized, size) + expect(text(b.response.body)).toBe('hello') + expect(b.at).toBe(sized.length) + } + expect(feed('HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhel', 4).response).toBeNull() + }) + + it('ends at a malformed chunk size, and with the connection', () => { + expect(text(feed('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n-1\r\nxx', 5).response.body)).toBe('ok') + const reader = new ResponseReader('GET') + reader.push(bytes('HTTP/1.0 200 OK\r\n\r\nall')) + expect(reader.read(false)).toBeNull() + expect(text(reader.read(true).body)).toBe('all') + }) + + it('takes a large answer in time proportional to its size', () => { + const reader = new ResponseReader('GET') + const chunk = new Uint8Array(1460).fill(97) + const total = 20 * 1024 * 1024 + reader.push(bytes(`HTTP/1.1 200 OK\r\nContent-Length: ${total}\r\n\r\n`)) + const started = Date.now() + let response = null + for (let sent = 0; sent < total; sent += chunk.length) { + reader.push(chunk.subarray(0, Math.min(chunk.length, total - sent))) + response = reader.read(false) + } + expect(response.body.length).toBe(total) + expect(Date.now() - started).toBeLessThan(5000) + }) + + it('refuses more than the limit', () => { + const reader = new ResponseReader('GET') + reader.push(bytes('HTTP/1.1 200 OK\r\n\r\n')) + reader.read(false) + const block = new Uint8Array(16 * 1024 * 1024) + expect(() => { + for (let i = 0; i < 6; i++) reader.push(block) + }).toThrow(/larger/) + }) +}) + // A stand-in for a v86 TCP connection. function fakeConnect(script) { return () => { @@ -106,6 +186,32 @@ describe('fetchFromMachine', () => { expect(response.status).toBe(200) }) + it('stops at a bad chunk size instead of hanging', async () => { + const connect = fakeConnect((on) => { + on.connect() + on.data(bytes('HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n-2\r\n')) + }) + const response = await fetchFromMachine(connect, 80, { method: 'GET', path: '/', headers: [] }) + expect(text(response.body)).toBe('ok') + }) + + it('gives up on an answer past the limit, and ignores data after that', async () => { + let connection + let after = 0 + const connect = fakeConnect((on, c) => { + connection = c + on.connect() + on.data(bytes('HTTP/1.1 200 OK\r\n\r\n')) + const block = new Uint8Array(16 * 1024 * 1024) + for (let i = 0; i < 6; i++) on.data(block) + after++ + on.data(block) + }) + await expect(fetchFromMachine(connect, 80, { method: 'GET', path: '/', headers: [] })).rejects.toThrow(/larger/) + expect(connection.closed).toBe(true) + expect(after).toBe(1) + }) + it('ends a body without a length when the server closes', async () => { const connect = fakeConnect((on) => { on.connect() diff --git a/tests/rlang.test.js b/tests/rlang.test.js index 0778cbc..d3dac06 100644 --- a/tests/rlang.test.js +++ b/tests/rlang.test.js @@ -1,6 +1,7 @@ -import { fileURLToPath } from 'node:url' +import { fileURLToPath, pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { createR, parseRscriptArgs } from '../src/lib/runtime/rlang.js' +import { patchedWebrForTests } from '../scripts/copy-npm-toolchains.mjs' describe('Rscript command line', () => { it('reads a file and its arguments, or expressions', () => { @@ -13,13 +14,15 @@ describe('Rscript command line', () => { }) }) -// webR itself, as in the browser (its Node build). +// webR itself, as in the browser (its Node build), patched as the app ships +// it (see scripts/copy-npm-toolchains.mjs). describe('R', () => { const encode = (text) => new TextEncoder().encode(text) let R beforeAll(async () => { - const { WebR } = await import('webr') - R = createR(WebR, fileURLToPath(new URL('../node_modules/webr/dist/', import.meta.url))) + const dir = patchedWebrForTests(fileURLToPath(new URL('../node_modules/.cache/webr-rlang-test/', import.meta.url))) + const { WebR } = await import(pathToFileURL(`${dir}webr.mjs`).href) + R = createR(WebR, dir) }) afterAll(() => R?.closeConsole('test')) diff --git a/tests/security-guest-sync.test.js b/tests/security-guest-sync.test.js new file mode 100644 index 0000000..947e19f --- /dev/null +++ b/tests/security-guest-sync.test.js @@ -0,0 +1,174 @@ +import 'fake-indexeddb/auto' +import { beforeAll, describe, expect, it } from 'vitest' +import { SYNC_LIMITS, applyPullToBaseline, applyPushToBaseline, emptyBaseline, planPull, planPush, planScan } from '../src/lib/runtime/workspaceSync.js' +import { escapeRegExp, hasControlCharacters } from '../src/lib/runtime/ProjectSandbox.svelte.js' +import { limitHistory } from '../src/lib/runtime/shell.js' +import { isProjectPath, tryNormalizePath } from '../src/lib/paths.js' +import { migrateProject, projectStore } from '../src/lib/stores/projects.svelte.js' + +// What a program in the sandbox can do to the project through the sync: +// make many or large files, or files with names the project can't hold. + +const limits = { fileBytes: 100, files: 3, bytes: 250 } + +// One sync as ProjectSandbox does it (#scan, then #pull, then #push): the +// terminal's files are { path: text }; the editor is { files, folders }. +function sync(terminal, terminalDirs, editor, baseline, limits) { + const found = Object.entries(terminal).map(([path, text]) => ({ path, size: text.length })) + const known = { files: new Set([...baseline.files.keys(), ...editor.files.map((f) => f.path)]), dirs: new Set([...baseline.dirs, ...editor.folders]) } + const scan = planScan(found, terminalDirs, known, limits) + const files = new Map(found.map(({ path, size }) => [path, scan.skipped.has(path) ? { size, text: null, skipped: true } : scan.large.has(path) ? { size, text: null } : { size, text: terminal[path] }])) + const snapshot = { files, dirs: scan.dirs } + const before = editor.files.map((f) => ({ ...f })) + const pull = planPull(snapshot, before, editor.folders, baseline) + // The store (applySandboxChanges, simplified). + for (const { path, content } of pull.upserts) { + const file = editor.files.find((f) => f.path === path) + if (file) file.content = content + else editor.files.push({ path, content }) + } + editor.files = editor.files.filter((f) => !pull.deletes.includes(f.path)) + editor.folders = [...new Set([...editor.folders.filter((d) => !pull.removeFolders.includes(d)), ...pull.addFolders])] + applyPullToBaseline(baseline, snapshot, pull, before) + const push = planPush(editor.files, editor.folders, baseline) + applyPushToBaseline(baseline, push) + return { scan, pull, push } +} + +describe('planScan', () => { + it('leaves out names the project would rename, like after a reload', () => { + const names = ['ok.txt', 'a\\b.txt', '..', 'x/../y', 'bell\x07.txt', 'esc\x1b[31m', 'c:d.txt', '.opcode/x', 'sp ace .txt '] + const plan = planScan(names.map((path) => ({ path, size: 1 })), [], { files: new Set(), dirs: new Set() }, SYNC_LIMITS) + expect([...plan.read]).toEqual(['ok.txt']) + for (const name of names.slice(1)) { + expect(plan.skipped.has(name)).toBe(true) + // migrateProject (on reload) would not keep it as it is either. + expect(tryNormalizePath(name)).not.toBe(name) + } + expect(planScan([], ['ok', 'bad\\dir', 'ok/..'], { files: new Set(), dirs: new Set() }, SYNC_LIMITS).dirs).toEqual(new Set(['ok'])) + }) + + it('reads files the editor knows first, then new ones up to the limits', () => { + const files = [{ path: 'a-new', size: 10 }, { path: 'b-new', size: 10 }, { path: 'z-known', size: 90 }, { path: 'big', size: 101 }] + const plan = planScan(files, [], { files: new Set(['z-known']), dirs: new Set() }, limits) + expect([...plan.read]).toEqual(['z-known', 'a-new', 'b-new']) + expect([...plan.large]).toEqual(['big']) + const crowded = planScan([...files, { path: 'c-new', size: 1 }], [], { files: new Set(['z-known']), dirs: new Set() }, limits) + expect(crowded.skipped.has('c-new')).toBe(true) // the 4th file + const heavy = planScan([{ path: 'a', size: 100 }, { path: 'b', size: 100 }, { path: 'c', size: 60 }], [], { files: new Set(), dirs: new Set() }, limits) + expect([...heavy.skipped]).toEqual(['c']) // over 250 bytes in all + }) + + it('stays fast for a program that makes 200,000 files', () => { + const files = Array.from({ length: 200_000 }, (_, i) => ({ path: `f${i}`, size: 0 })) + const start = performance.now() + const plan = planScan(files, [], { files: new Set(), dirs: new Set() }) + expect(plan.read.size).toBe(SYNC_LIMITS.files) + expect(performance.now() - start).toBeLessThan(2000) + }) +}) + +describe('sync with the limits', () => { + it("never deletes the editor's files, and settles", () => { + const editor = { files: [{ path: 'main.py', content: 'x'.repeat(90) }, { path: 'notes.txt', content: 'n'.repeat(90) }], folders: [] } + const baseline = emptyBaseline() + for (const f of editor.files) baseline.files.set(f.path, f.content) + // The program grows notes.txt past the total and floods ~ with files. + const terminal = { 'main.py': 'x'.repeat(90), 'notes.txt': 'N'.repeat(99), 'flood/1': 'a', 'flood/2': 'b', 'flood/3': 'c', 'bad\\name': 'd' } + for (let round = 0; round < 3; round++) { + const { pull, push } = sync(terminal, ['flood'], editor, baseline, limits) + expect(pull.deletes).toEqual([]) + expect(push.removes).toEqual([]) + expect(push.rmdirs).toEqual([]) + if (round > 0) expect(pull.upserts).toEqual([]) // settled: no flapping + } + expect(editor.files.map((f) => f.path).sort()).toEqual(['flood/1', 'main.py', 'notes.txt']) + expect(editor.files.find((f) => f.path === 'notes.txt').content).toBe('N'.repeat(99)) + // What didn't fit is still the terminal's, listed as files the editor can't show. + const { pull } = sync(terminal, ['flood'], editor, baseline, limits) + expect(pull.binaries.map((b) => b.path).sort()).toEqual(['bad\\name', 'flood/2', 'flood/3']) + }) + + it('keeps editor files that no longer fit, and pushes their edits', () => { + const editor = { files: [{ path: 'a', content: 'a'.repeat(100) }, { path: 'b', content: 'b'.repeat(100) }, { path: 'c', content: 'c' }], folders: [] } + const baseline = emptyBaseline() + for (const f of editor.files) baseline.files.set(f.path, f.content) + // The terminal makes c large enough that the three pass 250 bytes. + const terminal = { a: 'a'.repeat(100), b: 'b'.repeat(100), c: 'C'.repeat(60) } + const { scan, pull, push } = sync(terminal, [], editor, baseline, limits) + expect([...scan.skipped]).toEqual(['c']) + expect(pull.deletes).toEqual([]) + expect(push.writes).toEqual([]) // the terminal's c stays + expect(editor.files.find((f) => f.path === 'c').content).toBe('c') + editor.files.find((f) => f.path === 'c').content = 'edited' + expect(planPush(editor.files, editor.folders, baseline).writes).toEqual([{ path: 'c', content: 'edited' }]) + }) + + it("doesn't mirror folders past the limit, nor remove them from the terminal", () => { + const editor = { files: [], folders: [] } + const baseline = emptyBaseline() + const dirs = ['d1', 'd2', 'd3', 'd4', 'd5'] + for (let round = 0; round < 2; round++) { + const { push } = sync({}, dirs, editor, baseline, limits) + expect(push.rmdirs).toEqual([]) + } + expect(editor.folders).toEqual(['d1', 'd2', 'd3']) + }) +}) + +describe('project store', () => { + beforeAll(async () => { + await projectStore.load() + projectStore.createProject('Guest', 'python') + }) + + it('applies many files from the terminal in linear time', () => { + const id = projectStore.activeProject.id + const upserts = Array.from({ length: 20_000 }, (_, i) => ({ path: `out/f${i}.txt`, content: String(i) })) + const start = performance.now() + projectStore.applySandboxChanges(id, { upserts, addFolders: ['out', 'empty'] }) + expect(performance.now() - start).toBeLessThan(2000) + expect(projectStore.files).toHaveLength(20_001) + expect(projectStore.folders).toEqual(['empty']) // "out" holds files + projectStore.applySandboxChanges(id, { upserts: [{ path: 'out/f7.txt', content: 'seven' }], deletes: upserts.slice(100).map((u) => u.path) }) + expect(projectStore.files).toHaveLength(101) + expect(projectStore.files.find((f) => f.path === 'out/f7.txt').content).toBe('seven') + }) + + it("never takes in names it would rename on reload (as migrateProject does)", () => { + const id = projectStore.activeProject.id + const bad = ['..\\..\\Startup\\x.bat', 'a/../b', 'tab\there', '.opcode/bashrc'] + projectStore.applySandboxChanges(id, { upserts: bad.map((path) => ({ path, content: '@echo pwned' })), addFolders: ['..\\up', 'ctl\x01'] }) + for (const path of bad) expect(projectStore.files.some((f) => f.path === path)).toBe(false) + expect(projectStore.folders.some((dir) => !isProjectPath(dir))).toBe(false) + // After a reload such a name would not survive as it is either. + const migrated = migrateProject({ files: bad.map((path, i) => ({ id: String(i), path, content: '' })) }) + for (const file of migrated.files) expect(bad).not.toContain(file.path) + }) +}) + +describe('other guest-supplied strings', () => { + it('javac: a sibling file name is matched literally', () => { + const name = '(x+x+)+y' // from "(x+x+)+y.java"; unescaped this takes seconds + const start = performance.now() + expect(new RegExp(`\\b${escapeRegExp(name)}\\b`).test('x'.repeat(29))).toBe(false) + expect(performance.now() - start).toBeLessThan(100) + expect(new RegExp(`\\b${escapeRegExp('Foo$Bar')}\\b`).test('new Foo$Bar()')).toBe(true) + }) + + it('a command replayed after an install has no control characters', () => { + expect(hasControlCharacters('python3 main.py')).toBe(false) + expect(hasControlCharacters('ls\rrm -rf ~')).toBe(true) + expect(hasControlCharacters('x\x03')).toBe(true) + expect(hasControlCharacters('x\x1b[200~')).toBe(true) + }) + + it('saved shell history is capped in lines, line length and size', () => { + expect(limitHistory('a\nb\nc')).toBe('a\nb\nc') + expect(limitHistory(Array.from({ length: 1500 }, (_, i) => `cmd ${i}`).join('\n')).split('\n')).toHaveLength(1000) + expect(limitHistory(`ls\n${'x'.repeat(5000)}\npwd`)).toBe('ls\npwd') + const big = limitHistory(Array.from({ length: 1000 }, () => 'y'.repeat(4000)).join('\n')) + expect(big.length).toBeLessThanOrEqual(256 * 1024) + expect(big.endsWith('y'.repeat(4000))).toBe(true) + }) +}) diff --git a/tests/security-guest-webr.test.js b/tests/security-guest-webr.test.js new file mode 100644 index 0000000..ae56a7c --- /dev/null +++ b/tests/security-guest-webr.test.js @@ -0,0 +1,153 @@ +import { readFileSync } from 'node:fs' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { createR } from '../src/lib/runtime/rlang.js' +import { patchRSource, patchWebrMainSource, patchWebrWorkerSource, patchedWebrForTests } from '../scripts/copy-npm-toolchains.mjs' + +// R code must not be able to run JavaScript: webR's worker and the page that +// starts it are on the app's origin (see scripts/copy-npm-toolchains.mjs). + +const NO_JS = 'eval_js is not available in Opcode' +const original = fileURLToPath(new URL('../node_modules/webr/dist/', import.meta.url)) +const read = (name) => readFileSync(`${original}${name}`, 'utf8') + +// Minimal Emscripten side modules (what dyn.load loads), written by hand. +const leb = (n) => { + const out = [] + do { + let byte = n & 127 + n >>>= 7 + if (n) byte |= 128 + out.push(byte) + } while (n) + return out +} +const str = (text) => { + const bytes = [...new TextEncoder().encode(text)] + return [...leb(bytes.length), ...bytes] +} +const vec = (items) => [...leb(items.length), ...items.flat()] +const section = (id, bytes) => [id, ...leb(bytes.length), ...bytes] +const wasm = (sections) => new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, ...sections.flat()]) +const dylink = (memorySize) => section(0, [...str('dylink.0'), 1, ...leb(leb(memorySize).length + 3), ...leb(memorySize), 0, 0, 0]) +const data = (bytes) => section(11, vec([[0, 0x23, 0, 0x0b, ...leb(bytes.length), ...bytes]])) +const memoryImports = [[...str('env'), ...str('memory'), 2, 0, 0], [...str('env'), ...str('__memory_base'), 3, 0x7f, 0]] +const cString = (text) => [...new TextEncoder().encode(text), 0] + +// Its constructor calls the imported JavaScript function `name` with `script`. +function callingImport(name, script) { + const bytes = cString(script) + return wasm([ + dylink(bytes.length), + section(1, vec([[0x60, 0, 0], [0x60, 1, 0x7f, 0]])), + section(2, vec([...memoryImports, [...str('env'), ...str(name), 0, 1]])), + section(3, vec([[0]])), + section(7, vec([[...str('__wasm_call_ctors'), 0, 1]])), + section(10, vec([[...leb(6), 0, 0x23, 0, 0x10, 0, 0x0b]])), + data(bytes), + ]) +} + +// It carries `body` as EM_ASM JavaScript, which the loader evals. +function withEmAsm(body) { + const bytes = cString(body) + const i32 = (n) => [0x7f, 0, 0x41, ...leb(n), 0x0b] + return wasm([ + dylink(bytes.length), + section(2, vec(memoryImports)), + section(6, vec([i32(0), i32(bytes.length)])), + section(7, vec([[...str('__start_em_asm'), 3, 1], [...str('__stop_em_asm'), 3, 2]])), + data(bytes), + ]) +} + +// Each writes a marker file in R's file system if its JavaScript runs. +const MODULES = { + run: callingImport('emscripten_run_script', 'globalThis.Module.FS.writeFile("/tmp/ran-run", "1")'), + int: callingImport('emscripten_run_script_int', 'globalThis.Module.FS.writeFile("/tmp/ran-int", "1")'), + string: callingImport('emscripten_run_script_string', 'globalThis.Module.FS.writeFile("/tmp/ran-string", "1")'), + asm: withEmAsm('}; globalThis.Module.FS.writeFile("/tmp/ran-asm", "1"); {'), +} + +async function loadModules(webR) { + const ran = {} + for (const [name, bytes] of Object.entries(MODULES)) { + await webR.FS.writeFile(`/tmp/${name}.so`, bytes) + await webR.evalRVoid(`try(dyn.load("/tmp/${name}.so"), silent = TRUE)`).catch(() => {}) + ran[name] = await webR.evalRBoolean(`file.exists("/tmp/ran-${name}")`) + } + return ran +} + +describe('webR as Opcode ships it', () => { + let dir + let WebR + let webR + beforeAll(async () => { + dir = patchedWebrForTests(fileURLToPath(new URL('../node_modules/.cache/webr-security-test/', import.meta.url))) + ;({ WebR } = await import(pathToFileURL(`${dir}webr.mjs`).href)) + webR = new WebR({ baseUrl: dir, interactive: false }) + await webR.init() + }, 60_000) + afterAll(() => { + webR?.close() + delete globalThis.opcodeMarker + }) + + it('raises an R error for webr::eval_js, in the worker or on the page', async () => { + const message = (code) => webR.evalRString(`tryCatch({ ${code}; "ran" }, error = function(e) conditionMessage(e))`) + expect(await message('webr::eval_js("1")')).toBe(NO_JS) + expect(await message('webr::eval_js("globalThis.opcodeMarker = 1", await = TRUE)')).toBe(NO_JS) + expect(await message('.Call(webr:::ffi_eval_js, "globalThis.opcodeMarker = 1", TRUE)')).toBe(NO_JS) + expect(globalThis.opcodeMarker).toBeUndefined() + expect(await webR.evalRString('as.character(6 * 7)')).toBe('42') + }, 60_000) + + it("doesn't run JavaScript from modules R loads, and still loads R's own", async () => { + expect(await loadModules(webR)).toEqual({ run: false, int: false, string: false, asm: false }) + expect(await webR.evalRString('{ library(grid); library(splines); library(tools); "loaded" }')).toBe('loaded') + }, 60_000) + + it("through Opcode's R runner (what a guest's Rscript request reaches)", async () => { + const R = createR(WebR, dir) + const result = await R.runScript({ cwd: '/workspace', expression: 'cat(webr::eval_js("globalThis.opcodeMarker = 1; 2", await = TRUE), "\\n")' }) + expect(result.code).toBe(1) + expect(result.output).toContain(NO_JS) + expect(globalThis.opcodeMarker).toBeUndefined() + }, 60_000) +}) + +describe('webR as published (why the patches exist)', () => { + it('runs JavaScript from a module R loads, and the R runner refuses it', async () => { + const { WebR } = await import('webr') + const webR = new WebR({ baseUrl: original, interactive: false }) + await webR.init() + try { + expect(await loadModules(webR)).toMatchObject({ run: true, int: true, asm: true }) + } finally { + webR.close() + } + await expect(createR(WebR, original).runScript({ cwd: '/workspace', expression: '1' })).rejects.toThrow(/lets R run JavaScript/) + }, 60_000) +}) + +describe('webR patches', () => { + it('fail when webR changed and a pattern no longer matches', () => { + expect(() => patchWebrWorkerSource(read('webr-worker.js').replace('evalJs:', 'evalJS:'))).toThrow(/webR changed \(evalJs/) + expect(() => patchWebrWorkerSource('"use strict";')).toThrow(/webR changed/) + expect(() => patchWebrMainSource(read('webr.js').replaceAll('eval-await', 'evalAwait'))).toThrow(/webR changed \(eval-await/) + expect(() => patchRSource(read('R.js').replace('var _emscripten_run_script=', 'var _emscripten_run_script2='))).toThrow(/webR changed \(emscripten_run_script/) + }) + + it('fail when an eval is left over', () => { + expect(() => patchWebrMainSource(`${read('webr.js')};(0,eval)("1")`)).toThrow(/evals, expected 0/) + expect(() => patchWebrWorkerSource(`${read('webr-worker.js')};eval("1")`)).toThrow(/evals, expected 0/) + expect(() => patchRSource(`${read('R.js')};new Function("1")`)).toThrow(/evals, expected 3/) + }) + + it('leave no eval in the scripts the page and worker run', () => { + for (const source of [patchWebrWorkerSource(read('webr-worker.js')), patchWebrMainSource(read('webr.js')), patchWebrMainSource(read('webr.mjs'))]) { + expect(source).not.toMatch(/\(0,eval\)|(? { + const good = { name: 'Lab 1', v86: '0.5.470', memoryMB: 256, hardware: 2, savedAt: 5, machine: 'linux', alpine: '3.24.2' } + + it('keeps the fields Opcode uses', () => { + expect(checkMeta({ ...good, extra: 'ignored' })).toEqual(good) + }) + + it('calls anything that is not an object damaged, not a crash', async () => { + for (const raw of [null, 1, 'text', [], true]) expect(() => checkMeta(raw)).toThrow(/damaged/) + await expect(decodeMachineFile(new Blob([MAGIC, 'null\n', 'S']))).rejects.toThrow(/damaged/) + await expect(decodeMachineFile(new Blob([MAGIC, '[]\n', 'S']))).rejects.toThrow(/damaged/) + }) + + it('requires the emulator version and memory, with their types', () => { + expect(() => checkMeta({ memoryMB: 256 })).toThrow(/damaged/) + expect(() => checkMeta({ v86: '0.5.470' })).toThrow(/damaged/) + expect(() => checkMeta({ v86: 470, memoryMB: 256 })).toThrow(/damaged/) + expect(() => checkMeta({ v86: '0.5.470', memoryMB: '256' })).toThrow(/damaged/) + expect(() => checkMeta({ v86: '0.5.470', memoryMB: -1 })).toThrow(/damaged/) + }) + + it('drops optional fields of the wrong type', () => { + const meta = checkMeta({ v86: '0.5.470', memoryMB: 256, name: {}, hardware: '2', savedAt: -1, machine: 'windows', alpine: 3 }) + expect(meta).toEqual({ v86: '0.5.470', memoryMB: 256 }) + }) + + it('ignores __proto__ in the file', async () => { + const { meta } = await decodeMachineFile(new Blob([MAGIC, '{"__proto__":{"polluted":1},"v86":"0.5.470","memoryMB":256}\n', 'S'])) + expect(meta).toEqual({ v86: '0.5.470', memoryMB: 256 }) + expect(Object.getPrototypeOf(meta)).toBe(Object.prototype) + expect({}.polluted).toBeUndefined() + }) + + it('cleans and shortens names', () => { + expect(machineName(' Lab\n1\x1b[31m red‮ ')).toBe('Lab 1 [31m red') + expect(machineName('x'.repeat(500))).toHaveLength(100) + expect(checkMeta({ ...good, name: '\x00\x01' }).name).toBeUndefined() + }) +}) + +describe('unpacking machine states', () => { + it('caps gzip output and stops reading there', async () => { + // The bomb from the review, smaller: 64 MB of zeros in about 64 kB. + const bomb = new Uint8Array(gzipSync(Buffer.alloc(64 * MB), { level: 9 })) + expect(bomb.length).toBeLessThan(100_000) + await expect(gunzipIfNeeded(bomb, { maxBytes: 8 * MB })).rejects.toMatchObject({ code: 'TOO_BIG' }) + await expect(measureGunzip(new Blob([bomb]), { maxBytes: 8 * MB })).rejects.toMatchObject({ code: 'TOO_BIG' }) + expect((await gunzipIfNeeded(bomb, { maxBytes: 64 * MB })).length).toBe(64 * MB) + }) + + it('does not trust the size gzip states', async () => { + const gz = new Uint8Array(gzipSync(Buffer.alloc(4 * MB, 7))) + new DataView(gz.buffer).setUint32(gz.length - 4, 10, true) // says 10 bytes + await expect(gunzipIfNeeded(gz)).rejects.toThrow() // the gzip checksum catches the lie + // Says it is over the cap: refused before unpacking. + await expect(gunzipIfNeeded(new Uint8Array(gzipSync(Buffer.alloc(4 * MB, 7))), { maxBytes: MB })).rejects.toMatchObject({ code: 'TOO_BIG' }) + const honest = new Uint8Array(gzipSync(Buffer.alloc(4 * MB, 7))) + new DataView(honest.buffer).setUint32(honest.length - 4, 0, true) + await expect(gunzipIfNeeded(honest, { maxBytes: MB })).rejects.toMatchObject({ code: 'TOO_BIG' }) + }) + + it('accepts a v86 snapshot within the machine memory limit', async () => { + const state = v86State(3 * MB) + const gz = new Uint8Array(gzipSync(state)) + const unpacked = await unpackMachineState(gz, 256) + expect(unpacked).toBeInstanceOf(ArrayBuffer) + expect(unpacked.byteLength).toBe(state.length) + // Already unpacked by the server (Content-Encoding: gzip). + expect((await unpackMachineState(state, 256)).byteLength).toBe(state.length) + await expect(checkMachineState(new Blob([gz]), 256)).resolves.toBeUndefined() + }) + + it('refuses a decompression bomb as damaged', async () => { + // The review's bomb unpacked to 512 MB; the limit for a 256 MB machine is 320 MB. + expect(stateLimit(256)).toBe(320 * MB) + const bomb = new Uint8Array(gzipSync(Buffer.alloc(stateLimit(1) + 1), { level: 9 })) + await expect(unpackMachineState(bomb, 1)).rejects.toThrow(/damaged/) + await expect(checkMachineState(new Blob([bomb]), 1)).rejects.toThrow(/damaged/) + }) + + it('refuses states that are not v86 snapshots, including zstd ones', async () => { + const zstd = new Uint8Array(64) + new DataView(zstd.buffer).setUint32(0, 0xfd2fb528, true) + await expect(unpackMachineState(zstd, 256)).rejects.toThrow(/damaged/) + await expect(unpackMachineState(new Uint8Array(gzipSync(zstd)), 256)).rejects.toThrow(/damaged/) + await expect(checkMachineState(new Blob([zstd]), 256)).rejects.toThrow(/damaged/) + await expect(checkMachineState(new Blob([gzipSync(zstd)]), 256)).rejects.toThrow(/damaged/) + // A length in the header that doesn't match. + const wrong = v86State(1024) + new DataView(wrong.buffer).setUint32(8, 4096, true) + await expect(unpackMachineState(new Uint8Array(gzipSync(wrong)), 256)).rejects.toThrow(/damaged/) + // Not gzip at all, or broken gzip. + await expect(checkMachineState(new Blob([new Uint8Array([0x1f, 0x8b, 8, 0, 1, 2, 3])]), 256)).rejects.toThrow(/damaged/) + }) + + it('round-trips a machine file and checks it', async () => { + const gz = gzipSync(v86State(MB)) + const file = encodeMachineFile({ name: 'Lab', v86: '0.5.470', memoryMB: 256 }, new Blob([gz])) + const { meta, state } = await decodeMachineFile(file) + await expect(checkMachineState(state, meta.memoryMB)).resolves.toBeUndefined() + expect(machineFileLimit(256)).toBeGreaterThan(stateLimit(256)) + }) +}) + +describe('shared machine links', () => { + const base = 'https://opcode.example/app/?machine=x' + + it('opens only web addresses', () => { + expect(sharedMachineUrl('https://labs.example/lab-1.opcode-linux', base).host).toBe('labs.example') + expect(sharedMachineUrl('http://labs.example/a', base).protocol).toBe('http:') + for (const bad of ['javascript:alert(1)', 'data:text/plain,hi', 'blob:https://opcode.example/1', 'file:///etc/passwd', 'ftp://x/y', 'http://[bad']) { + expect(sharedMachineUrl(bad, base)).toBeNull() + } + }) + + it('keeps relative paths on this site', () => { + const url = sharedMachineUrl('labs/lab-1.opcode-linux', base) + expect(url.href).toBe('https://opcode.example/app/labs/lab-1.opcode-linux') + expect(sharedMachineUrl('//evil.example/x', base).host).toBe('evil.example') // a host, so the prompt names it + }) + + it('names the project after the file', () => { + expect(sharedMachineName('https://labs.example/files/Lab%201.opcode-linux')).toBe('Lab 1') + expect(sharedMachineName('https://labs.example/%E0%A4%A.opcode-linux')).toBe('%E0%A4%A') + expect(sharedMachineName('https://labs.example/')).toBe('Shared machine') + expect(sharedMachineName('https://labs.example/%0a%1b.opcode-linux')).toBe('Shared machine') + }) +}) + +describe('capped downloads', () => { + const streamOf = (chunks) => + new ReadableStream({ + pull(controller) { + const next = chunks.shift() + if (next) controller.enqueue(next) + else controller.close() + }, + }) + + it('reads a body with progress', async () => { + const progress = [] + const bytes = await readBody(new Response(streamOf([new Uint8Array(10), new Uint8Array(5)])), { maxBytes: 100, emit: (p) => progress.push(p.downloadedBytes) }) + expect(bytes.length).toBe(15) + expect(progress).toEqual([10, 15]) + }) + + it('stops once the body passes the cap, whatever the server says', async () => { + let pulled = 0 + const endless = new ReadableStream({ + pull(controller) { + pulled++ + controller.enqueue(new Uint8Array(MB)) + }, + }) + await expect(readBody(new Response(endless, { headers: { 'content-length': '10' } }), { maxBytes: 4 * MB })).rejects.toThrow(/larger than/) + expect(pulled).toBeLessThan(10) + }) + + it('refuses a stated size over the cap before reading', async () => { + const response = new Response(streamOf([new Uint8Array(1)]), { headers: { 'content-length': String(10 * MB) } }) + await expect(readBody(response, { maxBytes: MB })).rejects.toThrow(/larger than/) + }) +}) + +// A zip whose `lying` entries claim to be 10 bytes (as in the review's zipbomb.cjs). +async function lyingZip(entries, lying = Object.keys(entries)) { + const zip = new JSZip() + for (const [name, bytes] of Object.entries(entries)) zip.file(name, bytes) + const buffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE', compressionOptions: { level: 9 } }) + const nameAt = (offset, lengthAt) => buffer.toString('utf8', offset, offset + buffer.readUInt16LE(lengthAt)) + for (let i = 0; i < buffer.length - 4; i++) { + const signature = buffer.readUInt32LE(i) + if (signature === 0x04034b50 && lying.includes(nameAt(i + 30, i + 26))) buffer.writeUInt32LE(10, i + 22) + if (signature === 0x02014b50 && lying.includes(nameAt(i + 46, i + 28))) buffer.writeUInt32LE(10, i + 24) + } + return JSZip.loadAsync(buffer) +} + +// Entries that stream the given sizes in 64 kB pieces, whatever they claim. +function fakeZip(sizes) { + const files = {} + for (const [name, size] of Object.entries(sizes)) { + files[name] = { + name, + dir: false, + _data: { uncompressedSize: 10 }, + internalStream() { + const handlers = {} + let sent = 0 + let paused = false + const pump = () => { + while (!paused && sent < size) { + const chunk = new Uint8Array(Math.min(65536, size - sent)) + sent += chunk.length + handlers.data(chunk) + } + if (!paused) setTimeout(() => handlers.end()) + } + const stream = { + on: (event, fn) => ((handlers[event] = fn), stream), + pause: () => ((paused = true), stream), + resume: () => (setTimeout(pump), stream), + } + return stream + }, + } + } + return { files } +} + +describe('zip import', () => { + const limits = { maxFiles: 2000, maxFileBytes: 2 * MB, maxTotalBytes: 5 * MB } + + it('stops unpacking an entry bigger than it says at the per-file limit', async () => { + const zip = await lyingZip({ 'big.txt': Buffer.alloc(40 * MB, 0x61), 'small.txt': Buffer.from('hello') }, ['big.txt']) + expect(zip.files['big.txt']._data.uncompressedSize).toBe(10) + const before = process.memoryUsage().arrayBuffers + expect(await readZipEntry(zip.files['big.txt'], 2 * MB)).toBeNull() + expect(process.memoryUsage().arrayBuffers - before).toBeLessThan(30 * MB) + const { files, tooBig } = await readZip(zip, limits) + expect(tooBig).toBe(1) + expect(files.map((f) => f.path)).toEqual(['small.txt']) + }) + + it('calls a zip damaged when an entry under the limit lies about its size', async () => { + const zip = await lyingZip({ 'a.txt': Buffer.alloc(MB, 0x61) }) + await expect(readZip(zip, limits)).rejects.toThrow(/damaged/) + }) + + it('fails once the real total passes the limit', async () => { + let read = 0 + const zip = fakeZip({ 'a.txt': 1.5 * MB, 'b.txt': 1.5 * MB, 'c.txt': 1.5 * MB, 'd.txt': 1.5 * MB, 'e.txt': 1.5 * MB }) + for (const entry of Object.values(zip.files)) { + const open = entry.internalStream + entry.internalStream = () => (read++, open()) + } + await expect(readZip(zip, limits)).rejects.toThrow(/unpacks to more than 5 MB/) + expect(read).toBe(4) + }) + + it('keeps the stated-size checks, folder stripping and ignored paths', async () => { + const zip = new JSZip() + zip.file('project/main.py', 'print(1)') + zip.file('project/src/a.py', 'x = 1') + zip.file('project/node_modules/x/index.js', 'skip') + zip.file('__MACOSX/project/._main.py', 'skip') + const loaded = await JSZip.loadAsync(await zip.generateAsync({ type: 'uint8array' })) + const { files, tooBig } = await readZip(loaded, limits) + expect(tooBig).toBe(0) + expect(files.map((f) => f.path).sort()).toEqual(['main.py', 'src/a.py']) + expect(new TextDecoder().decode(files.find((f) => f.path === 'main.py').bytes)).toBe('print(1)') + await expect(readZip(loaded, { ...limits, maxFiles: 1 })).rejects.toThrow(/it has 2 files/) + }) +}) + +describe('zip export', () => { + it('leaves out names that could escape the folder the zip is unpacked into', () => { + const files = ['main.py', '..\\..\\x.bat', '../up.txt', 'a/../../b', '.opcode/bashrc', 'dir\\file.txt', 'bad|name'].map((path) => ({ path, content: path })) + const { files: out, folders, skipped } = zipContents({ files, folders: ['src', '../outside'] }) + expect(out.map((f) => f.path)).toEqual(['main.py', 'dir/file.txt']) + expect(folders).toEqual(['src']) + expect(skipped).toBe(6) + }) +}) diff --git a/tests/security-preview.test.js b/tests/security-preview.test.js new file mode 100644 index 0000000..e04136a --- /dev/null +++ b/tests/security-preview.test.js @@ -0,0 +1,47 @@ +import { describe, expect, it, vi } from 'vitest' + +// A deployment whose preview host is the app's own origin. +globalThis.OPCODE_CONFIG = { previewHost: 'https://opcode.example/' } +vi.stubGlobal('location', { origin: 'https://opcode.example', href: 'https://opcode.example/' }) + +let exposures = 0 +const sandbox = { + async exposePort() { + exposures++ + return { url: new URL('https://opcode.example/'), async close() {} } + }, +} +vi.mock('../src/lib/stores/sessions.svelte.js', () => ({ sessionStore: { get: () => sandbox } })) +vi.mock('../src/lib/stores/linux.svelte.js', () => ({ linuxStore: { get: () => undefined } })) + +const { previewHostProblem, previewStore, PREVIEW_HOST } = await import('../src/lib/stores/preview.svelte.js') + +describe('previewHostProblem', () => { + it('refuses the page\'s own origin, wildcard filled in', () => { + expect(previewHostProblem('https://opcode.example/', 'https://opcode.example')).toMatch(/own address/) + expect(previewHostProblem('https://opcode.example/*', 'https://opcode.example')).toMatch(/own address/) + expect(previewHostProblem('https://opcode.example:443/', 'https://opcode.example')).toMatch(/own address/) + }) + + it('takes a separate origin', () => { + expect(previewHostProblem('https://preview.opcode.example/', 'https://opcode.example')).toBeNull() + expect(previewHostProblem('https://*.preview.opcode.example/', 'https://opcode.example')).toBeNull() + expect(previewHostProblem('http://opcode.example/', 'https://opcode.example')).toBeNull() + expect(previewHostProblem('https://opcode.example:8443/', 'https://opcode.example')).toBeNull() + }) + + it('explains an address that is not one', () => { + expect(previewHostProblem('not a url', 'https://opcode.example')).toMatch(/not a valid address/) + }) +}) + +describe('the preview with the app\'s own origin as its host', () => { + it('stays off with an explanation, and never exposes a server', async () => { + expect(PREVIEW_HOST).toBe('https://opcode.example/') + await previewStore.show('p1', 8000) + expect(previewStore.status).toBe('error') + expect(previewStore.error).toMatch(/own address/) + expect(previewStore.src).toBeNull() + expect(exposures).toBe(0) + }) +}) diff --git a/tests/server.test.js b/tests/server.test.js index 4200917..aeee258 100644 --- a/tests/server.test.js +++ b/tests/server.test.js @@ -2,6 +2,7 @@ // ahead of time (scripts/precompress.mjs), on a small stand-in build. import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs' import http from 'node:http' +import net from 'node:net' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { brotliDecompressSync, gzipSync } from 'node:zlib' @@ -32,6 +33,20 @@ function request(port, path, headers = {}) { }) } +/** A request sent byte for byte, for paths http.get would tidy up: { status, headers }. */ +function raw(port, target, host = `127.0.0.1:${port}`) { + return new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1', () => socket.write(`GET ${target} HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`)) + let text = '' + socket.on('data', (chunk) => (text += chunk.toString('latin1'))) + socket.on('close', () => { + const [status, ...lines] = text.split('\r\n\r\n')[0].split('\r\n') + resolve({ status: Number(status.split(' ')[1]), headers: Object.fromEntries(lines.map((line) => [line.slice(0, line.indexOf(':')).toLowerCase(), line.slice(line.indexOf(':') + 1).trim()])) }) + }) + socket.on('error', reject) + }) +} + function connect(port, headers) { return new Promise((resolve) => { const ws = new WebSocket(`ws://127.0.0.1:${port}/wisp/`, { headers }) @@ -61,6 +76,7 @@ describe('production server', () => { 'assets/llvm.core-abcd.wasm': WASM, 'toolchains/go.wasm.gz': gzipSync(WASM), 'linux/opcode-linux.state': gzipSync(Buffer.alloc(100_000)), + 'docs folder/index.html': 'docs', }) write(join(root, 'preview'), { 'index.html': 'No server is being previewed.', '.wasmer/host.html': 'host' }) write(root, { 'secret.txt': 'outside the build' }) @@ -84,6 +100,10 @@ describe('production server', () => { expect(() => configFromEnv({ OPCODE_RELAY: 'yes' })).toThrow(/OPCODE_RELAY/) expect(() => configFromEnv({ OPCODE_PREVIEW_HOST: 'preview.example.com' })).toThrow(/OPCODE_PREVIEW_HOST/) expect(() => configFromEnv({ OPCODE_RELAY_ARGS: '--unknown' })).toThrow(/Unknown option/) + expect(configFromEnv({}).trustProxy).toBe(false) + expect(configFromEnv({ OPCODE_TRUST_PROXY: 'on' }).trustProxy).toBe(true) + expect(configFromEnv({ OPCODE_TRUST_PROXY: 'off' }).trustProxy).toBe(false) + expect(() => configFromEnv({ OPCODE_TRUST_PROXY: 'yes' })).toThrow(/OPCODE_TRUST_PROXY/) }) it('serves the app cross-origin isolated, with caching by kind of file', async () => { @@ -94,6 +114,8 @@ describe('production server', () => { expect(index.headers['cross-origin-embedder-policy']).toBe('require-corp') expect(index.headers['content-type']).toBe('text/html; charset=utf-8') expect(index.headers['cache-control']).toBe('no-cache') + // Never framed. + expect(index.headers['content-security-policy']).toBe("frame-ancestors 'none'") expect(index.body.toString()).toContain('Opcode') expect((await request(port, '/', { 'If-None-Match': index.headers.etag })).status).toBe(304) @@ -144,6 +166,27 @@ describe('production server', () => { expect((await request(port, '/assets')).status).toBe(301) }) + it('survives requests the file system rejects', async () => { + const port = await start() + // Too long for a file name: statSync throws ENAMETOOLONG. + expect((await request(port, `/${'A'.repeat(300)}`)).status).toBe(404) + expect((await request(port, `/assets/${'A'.repeat(300)}/x.js`)).status).toBe(404) + expect((await request(port, `/${'A/'.repeat(3000)}`)).status).toBe(404) + expect((await request(port, '/')).status).toBe(200) + }) + + it('redirects folders only to paths on this site', async () => { + const port = await start() + for (const target of ['/assets', '//x//evil.example/..%2fassets', '/.//evil.example/..%2fassets', '//x/\\evil.example/..%2fassets', '//evil.example/assets']) { + const response = await raw(port, target) + expect(response.status, target).toBe(301) + expect(response.headers.location, target).toBe('/assets/') + } + // Names are sent encoded. + expect((await raw(port, '/docs%20folder')).headers.location).toBe('/docs%20folder/') + expect((await request(port, '/docs%20folder/')).body.toString()).toBe('docs') + }) + it("gives the app the environment's settings, or the build's own", async () => { expect((await request(await start(), '/config.js')).body.toString()).toBe('window.OPCODE_CONFIG = {}\n') const port = await start({ OPCODE_RELAY: 'on', OPCODE_PREVIEW_HOST: 'https://*.preview.example.com/' }) @@ -160,8 +203,21 @@ describe('production server', () => { expect(host.status).toBe(200) expect(host.body.toString()).toContain('host') expect(host.headers['cross-origin-resource-policy']).toBe('cross-origin') - // Behind a proxy that keeps the name in X-Forwarded-Host. - expect((await request(port, '/', { Host: 'opcode:8080', 'X-Forwarded-Host': 'p1.preview.example.com' })).body.toString()).toContain('No server') + // The app frames it; sandboxed, it can't navigate the app's tab. + expect(host.headers['content-security-policy']).toBe('sandbox allow-scripts allow-same-origin') + // Whatever the spelling of its path. + expect((await request(port, '/.wasmer//x/../host.html', { Host: 'p12345.preview.example.com' })).headers['content-security-policy']).toBe('sandbox allow-scripts allow-same-origin') + expect((await request(port, '/', { Host: 'p12345.preview.example.com' })).headers['content-security-policy']).toBeUndefined() + // Only the app's pages may embed it, when the server is told which they are. + const listed = await start({ OPCODE_PREVIEW_HOST: 'https://*.preview.example.com/', OPCODE_APP_ORIGINS: 'https://opcode.example.com/' }) + expect((await request(listed, '/.wasmer/host.html', { Host: 'p1.preview.example.com' })).headers['content-security-policy']).toBe('sandbox allow-scripts allow-same-origin; frame-ancestors https://opcode.example.com') + expect(() => configFromEnv({ OPCODE_APP_ORIGINS: 'opcode.example.com' })).toThrow(/OPCODE_APP_ORIGINS/) + // X-Forwarded-Host is the client's word unless a trusted proxy sets it. + expect((await request(port, '/', { Host: 'opcode.example.com', 'X-Forwarded-Host': 'p1.preview.example.com' })).body.toString()).toContain('Opcode') + expect((await request(port, '/', { Host: 'p1.preview.example.com', 'X-Forwarded-Host': 'opcode.example.com' })).body.toString()).toContain('No server') + const proxied = await start({ OPCODE_PREVIEW_HOST: 'https://*.preview.example.com/', OPCODE_TRUST_PROXY: 'on' }) + expect((await request(proxied, '/', { Host: 'opcode:8080', 'X-Forwarded-Host': 'p1.preview.example.com' })).body.toString()).toContain('No server') + expect((await request(proxied, '/', { Host: 'opcode:8080' })).body.toString()).toContain('Opcode') // The app's own address, and the bare domain, are the app. expect((await request(port, '/', { Host: 'opcode.example.com' })).body.toString()).toContain('Opcode') expect((await request(port, '/', { Host: 'preview.example.com' })).body.toString()).toContain('Opcode') @@ -182,5 +238,9 @@ describe('production server', () => { expect(await connect(port, { Origin: 'https://other.example.com' })).toBe('open') expect(await connect(port, { Origin: 'https://evil.example.com' })).toBe(403) expect((await request(port, '/dns-query', { Origin: 'https://evil.example.com' })).status).toBe(403) + // A forged X-Forwarded-Host doesn't make another site's page this site's. + expect(await connect(port, { Origin: 'https://evil.example.com', 'X-Forwarded-Host': 'evil.example.com' })).toBe(403) + const proxied = await start({ OPCODE_RELAY: 'on', OPCODE_TRUST_PROXY: 'on' }) + expect(await connect(proxied, { Origin: 'https://opcode.example.com', 'X-Forwarded-Host': 'opcode.example.com' })).toBe('open') }) }) diff --git a/tests/wasmerMirror.test.js b/tests/wasmerMirror.test.js index 6571338..cf956cd 100644 --- a/tests/wasmerMirror.test.js +++ b/tests/wasmerMirror.test.js @@ -1,5 +1,5 @@ -import { describe, expect, it } from 'vitest' -import { installWasmerMirror, packageAsked } from '../src/lib/runtime/wasmerMirror.js' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { MIRROR_RETRY_MS, installWasmerMirror, packageAsked } from '../src/lib/runtime/wasmerMirror.js' const query = (name) => JSON.stringify({ query: `{\n getPackage(name: "${name}") { packageName }\n info { defaultFrontend } }` }) const bash = { @@ -9,22 +9,28 @@ const bash = { } // A page whose own fetch knows the site's files and records what leaves it. +// A file can be a function, called for each request, to fail some of them. function page(files) { const outside = [] + const site = [] const scope = { location: { href: 'https://opcode.example/app/' }, fetch: async (input) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url - if (url in files) return new Response(files[url]) + if (url.startsWith('https://opcode.example/')) site.push(url) + if (url in files) return typeof files[url] === 'function' ? files[url]() : new Response(files[url]) if (url.startsWith('https://opcode.example/')) return new Response('', { status: 404 }) outside.push(url) return new Response('from wasmer') }, } installWasmerMirror(scope) - return { scope, outside } + return { scope, outside, site } } +const askBash = (scope) => scope.fetch('https://registry.wasmer.io/graphql', { method: 'POST', body: query('wasmer/bash') }) +const REGISTRY_JSON = 'https://opcode.example/app/wasmer/registry.json' + const mirror = { 'https://opcode.example/app/wasmer/registry.json': JSON.stringify({ info: { defaultFrontend: 'x' }, packages: { 'wasmer/bash': bash } }), 'https://opcode.example/app/wasmer/abc.webc': 'local bytes', @@ -59,4 +65,45 @@ describe('the Wasmer mirror', () => { await scope.fetch('https://cdn.wasmer.io/webcimages/abc.webc') expect(outside).toHaveLength(2) }) + + it('asks for a missing mirror only once', async () => { + const { scope, site } = page({}) + for (let i = 0; i < 3; i++) await askBash(scope) + expect(site.filter((url) => url === REGISTRY_JSON)).toHaveLength(1) + }) + + it('takes a page served in place of registry.json as no mirror', async () => { + const { scope, site, outside } = page({ [REGISTRY_JSON]: 'Opcode' }) + for (let i = 0; i < 3; i++) await askBash(scope) + expect(site.filter((url) => url === REGISTRY_JSON)).toHaveLength(1) + expect(outside).toHaveLength(3) + }) + + describe('after a failed load', () => { + afterEach(() => vi.useRealTimers()) + + for (const [failure, fail] of [ + ['a server error', () => new Response('', { status: 503 })], + ['a network error', () => Promise.reject(new TypeError('Failed to fetch'))], + ]) { + it(`tries the mirror again after ${failure}`, async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + let failing = true + const { scope, outside, site } = page({ ...mirror, [REGISTRY_JSON]: () => (failing ? fail() : new Response(mirror[REGISTRY_JSON])) }) + await askBash(scope) + expect(outside).toEqual(['https://registry.wasmer.io/graphql']) + // Within the backoff, Wasmer answers without another try. + failing = false + await askBash(scope) + expect(site.filter((url) => url === REGISTRY_JSON)).toHaveLength(1) + expect(outside).toHaveLength(2) + // Then the mirror is tried again, and kept. + vi.setSystemTime(Date.now() + MIRROR_RETRY_MS) + expect(await (await askBash(scope)).json()).toEqual({ data: { getPackage: bash, info: { defaultFrontend: 'x' } } }) + await askBash(scope) + expect(site.filter((url) => url === REGISTRY_JSON)).toHaveLength(2) + expect(outside).toHaveLength(2) + }) + } + }) }) diff --git a/tests/wisp-server.test.js b/tests/wisp-server.test.js index 82c88dc..e3bff68 100644 --- a/tests/wisp-server.test.js +++ b/tests/wisp-server.test.js @@ -1,8 +1,12 @@ // Runs the relay (scripts/wisp-server.mjs) against a local echo server. +import { client as wisp } from '@mercuryworkshop/wisp-js/client' import { spawn } from 'node:child_process' +import dgram from 'node:dgram' +import http from 'node:http' import net from 'node:net' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import WebSocket from 'ws' +import { createRelay, parseArgs } from '../scripts/wisp-server.mjs' const packet = (type, stream, payload = Buffer.alloc(0)) => { const bytes = Buffer.alloc(5 + payload.length) @@ -33,6 +37,107 @@ async function startRelay(args) { return { child, url: `ws://127.0.0.1:${port}/` } } +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** The relay in this process, as scripts/server.mjs runs it. */ +async function startInProcess(args) { + const relay = createRelay(parseArgs(args), () => true) + const server = http.createServer((request, response) => (request.url.startsWith('/dns-query') ? relay.serveDns(request, response) : response.end())) + server.on('upgrade', relay.upgrade) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const { port } = server.address() + return { server, url: `ws://127.0.0.1:${port}/`, http: `http://127.0.0.1:${port}` } +} + +/** A DNS query message for one name (labels as raw bytes, as a client could send). */ +function dnsQuery(labels, type = 1) { + const parts = [Buffer.from([0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0])] + for (const label of labels) { + const bytes = Buffer.from(label, 'latin1') + parts.push(Buffer.from([bytes.length]), bytes) + } + parts.push(Buffer.from([0, 0, type, 0, 1])) + return Buffer.concat(parts) +} + +/** A DNS-over-HTTPS upstream that answers every name with 127.0.0.1. */ +async function fakeUpstream() { + const server = http.createServer(async (request, response) => { + const url = new URL(request.url, 'http://upstream') + if (url.searchParams.has('name')) { + return response.writeHead(200, { 'content-type': 'application/dns-json' }).end(JSON.stringify({ Status: 0, Answer: [{ name: url.searchParams.get('name'), type: 1, TTL: 60, data: '127.0.0.1' }] })) + } + const chunks = [] + for await (const chunk of request) chunks.push(chunk) + const query = Buffer.concat(chunks) + const header = Buffer.from(query.subarray(0, 12)) + header.writeUInt16BE(0x8180, 2) + header.writeUInt16BE(1, 6) + const record = Buffer.from([0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 127, 0, 0, 1]) + response.writeHead(200, { 'content-type': 'application/dns-message' }).end(Buffer.concat([header, query.subarray(12), record])) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { server, url: `http://127.0.0.1:${server.address().port}/` } +} + +/** An HTTP CONNECT proxy that tunnels for real and keeps each request's head. */ +async function fakeProxy() { + const heads = [] + const server = net.createServer((socket) => { + let head = Buffer.alloc(0) + socket.on('error', () => {}) + const onData = (chunk) => { + head = Buffer.concat([head, chunk]) + const end = head.indexOf('\r\n\r\n') + if (end === -1) return + socket.off('data', onData) + heads.push(head.subarray(0, end).toString('latin1')) + const [, host, port] = /^CONNECT (\S+):(\d+) /.exec(heads.at(-1)) ?? [] + if (!host) return socket.end('HTTP/1.1 400 Bad Request\r\n\r\n') + const upstream = net.connect(Number(port), host.replace(/^\[|\]$/g, ''), () => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + const rest = head.subarray(end + 4) + if (rest.length) upstream.write(rest) + socket.pipe(upstream).pipe(socket) + }) + upstream.on('error', () => socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')) + } + socket.on('data', onData) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + return { server, heads, url: `http://127.0.0.1:${server.address().port}` } +} + +/** Opens a wisp-js client connection (the client Opcode's Wasmer sandbox uses). */ +function wispClient(url) { + return new Promise((resolve, reject) => { + const connection = new wisp.ClientConnection(url) + connection.onopen = () => resolve(connection) + connection.onerror = reject + }) +} + +/** Sends `total` bytes over a wisp-js stream to an echo server; resolves with what came back. */ +function echoThrough(connection, host, port, total, chunk = 64 << 10) { + const sent = Buffer.alloc(total) + for (let i = 0; i < total; i++) sent[i] = i % 251 + return new Promise((resolve, reject) => { + const stream = connection.create_stream(host, port) + const received = [] + let length = 0 + stream.onmessage = (data) => { + received.push(Buffer.from(data)) + length += data.length + if (length >= total) { + stream.close() + resolve({ sent, received: Buffer.concat(received) }) + } + } + stream.onclose = (reason) => reject(new Error(`stream closed (reason ${reason}) after ${length} bytes`)) + for (let offset = 0; offset < total; offset += chunk) stream.send(sent.subarray(offset, offset + chunk)) + }) +} + function open(url) { const ws = new WebSocket(url) const messages = [] @@ -64,7 +169,10 @@ describe('wisp relay', () => { }) afterAll(() => { echo.close() - for (const relay of relays) relay.child.kill() + for (const relay of relays) { + relay.child?.kill() + relay.server?.close() + } }) it('relays TCP streams', async () => { @@ -102,4 +210,170 @@ describe('wisp relay', () => { }) expect(status).toBe(403) }) + + it('carries a few MB each way for a client that follows the Wisp window', async () => { + const relay = await startInProcess(['--allow-private']) + relays.push(relay) + const connection = await wispClient(relay.url) + const { sent, received } = await echoThrough(connection, '127.0.0.1', echoPort, 6 << 20) + expect(received.equals(sent)).toBe(true) + // Small packets too, as v86 sends (one per TCP segment). + const small = await echoThrough(connection, '127.0.0.1', echoPort, 1 << 20, 1460) + expect(small.received.equals(small.sent)).toBe(true) + connection.close() + }) + + it('waits, without cutting it off, for a peer that stops reading', async () => { + let peer + let length = 0 + const sink = net.createServer((socket) => { + peer = socket + socket.pause() + socket.on('data', (chunk) => (length += chunk.length)) + }) + await new Promise((resolve) => sink.listen(0, '127.0.0.1', resolve)) + const relay = await startInProcess(['--allow-private']) + relays.push(relay) + const connection = await wispClient(relay.url) + const stream = connection.create_stream('127.0.0.1', sink.address().port) + let closed = null + stream.onclose = (reason) => (closed = reason) + const total = 40 << 20 // more than the relay buffers for a client + for (let offset = 0; offset < total; offset += 64 << 10) stream.send(Buffer.alloc(64 << 10, 1)) + await sleep(1000) + expect(closed).toBe(null) + expect(length).toBeLessThan(total) + peer.resume() + for (let i = 0; i < 100 && length < total; i++) await sleep(100) + expect(length).toBe(total) + expect(closed).toBe(null) + connection.close() + sink.close() + }) + + it('closes a stream whose client sends past its window', async () => { + const relay = await startInProcess(['--allow-private']) + relays.push(relay) + const { ws, next } = await open(relay.url) + ws.send(connectPacket(1, '127.0.0.1', echoPort)) + for (let i = 0; i < 200; i++) ws.send(packet(0x02, 1, Buffer.alloc(1024))) + expect((await next((m) => m.type === 0x04 && m.stream === 1)).payload[0]).toBe(0x49) + ws.close() + }) + + it('refuses host names that are not host names', async () => { + const relay = await startInProcess(['--allow-private']) + relays.push(relay) + const { ws, next } = await open(relay.url) + for (const [stream, host] of [[1, 'example.com:80 HTTP/1.1\r\nX-Injected: yes'], [3, 'a b.example'], [5, `${'a'.repeat(64)}.example`], [7, 'x'.repeat(300)]]) { + ws.send(connectPacket(stream, host, 80)) + expect((await next((m) => m.type === 0x04 && m.stream === stream)).payload[0]).toBe(0x41) + } + ws.close() + }) + + it('leaves no sockets behind when a client reuses stream ids', async () => { + const connections = new Set() + const listener = net.createServer((socket) => { + connections.add(socket) + socket.on('close', () => connections.delete(socket)) + socket.on('error', () => {}) + }) + // Every address: "localhost" may be 127.0.0.1 or ::1. + await new Promise((resolve) => listener.listen(0, resolve)) + const udp = dgram.createSocket('udp4') + await new Promise((resolve) => udp.bind(0, '127.0.0.1', resolve)) + const udpSockets = () => process.getActiveResourcesInfo().filter((name) => name === 'UDPWrap').length + const before = udpSockets() + + const relay = await startInProcess(['--allow-private', '--max-streams', '4']) + relays.push(relay) + const { ws, next } = await open(relay.url) + await next((m) => m.type === 0x03 && m.stream === 0) + // A name, so each lookup takes a moment and the next CONNECT lands meanwhile. + const udpConnect = (stream) => { + const bytes = connectPacket(stream, 'localhost', udp.address().port) + bytes[5] = 0x02 + return bytes + } + for (let i = 0; i < 50; i++) { + ws.send(connectPacket(7, 'localhost', listener.address().port)) + ws.send(packet(0x04, 7, Buffer.from([0x02]))) + ws.send(udpConnect(8)) + ws.send(packet(0x04, 8, Buffer.from([0x02]))) + } + ws.send(connectPacket(7, 'localhost', listener.address().port)) + ws.send(udpConnect(8)) + await sleep(1000) + expect(connections.size).toBe(1) + expect(udpSockets() - before).toBe(1) + ws.close() + await sleep(500) + expect(connections.size).toBe(0) + expect(udpSockets() - before).toBe(0) + listener.close() + udp.close() + }) + + describe('through an HTTP proxy (--via-proxy)', () => { + let upstream + let proxy + let relay + + beforeAll(async () => { + upstream = await fakeUpstream() + proxy = await fakeProxy() + relay = await startInProcess(['--allow-private', '--via-proxy', proxy.url, '--dns-upstream', upstream.url]) + relays.push(relay) + }) + afterAll(() => { + upstream.server.close() + proxy.server.close() + }) + + it('carries data both ways, by name and by address', async () => { + const connection = await wispClient(relay.url) + const byName = await echoThrough(connection, 'localhost', echoPort, 3 << 20) + expect(byName.received.equals(byName.sent)).toBe(true) + expect(proxy.heads.at(-1)).toMatch(new RegExp(`^CONNECT localhost:${echoPort} HTTP/1.1\r\n`)) + // A client that looked the name up through the relay, then connects by + // address: the proxy gets the name, which the relay's own lookup confirms. + expect((await fetch(`${relay.http}/dns-query`, { method: 'POST', headers: { 'content-type': 'application/dns-message' }, body: dnsQuery(['localhost']) })).status).toBe(200) + const byAddress = await echoThrough(connection, '127.0.0.1', echoPort, 3 << 20) + expect(byAddress.received.equals(byAddress.sent)).toBe(true) + expect(proxy.heads.at(-1)).toMatch(new RegExp(`^CONNECT localhost:${echoPort} HTTP/1.1\r\n`)) + connection.close() + }) + + it('never lets a client write into the CONNECT request', async () => { + const evil = '169.254.169.254:80 HTTP/1.1\r\nX-Injected: yes\r\nX: ' + expect((await fetch(`${relay.http}/dns-query`, { method: 'POST', headers: { 'content-type': 'application/dns-message' }, body: dnsQuery([evil, 'attacker', 'test']) })).status).toBe(200) + expect((await fetch(`${relay.http}/dns-query?name=${encodeURIComponent(`${evil}.attacker.test`)}`)).status).toBe(400) + expect((await fetch(`${relay.http}/dns-query?name=example.com&type=${encodeURIComponent('A\r\nX: y')}`)).status).toBe(400) + const { ws, next } = await open(relay.url) + ws.send(connectPacket(1, evil, 80)) + expect((await next((m) => m.type === 0x04 && m.stream === 1)).payload[0]).toBe(0x41) + ws.send(connectPacket(3, '127.0.0.1', echoPort)) + ws.send(packet(0x02, 3, Buffer.from('ping'))) + expect((await next((m) => m.type === 0x02 && m.stream === 3)).payload.toString()).toBe('ping') + ws.close() + expect(proxy.heads.length).toBeGreaterThan(0) + for (const head of proxy.heads) { + expect(head).not.toContain('X-Injected') + expect(head.split('\r\n')[0]).toMatch(/^CONNECT [\w.:[\]-]+ HTTP\/1\.1$/) + } + }) + + it("doesn't let one client choose the name another client's connection goes by", async () => { + // The attacker teaches the relay a name for 127.0.0.1 (the upstream + // answers every name with it) that the relay's own lookup doesn't give. + expect((await fetch(`${relay.http}/dns-query?name=hijack.attacker.test`)).status).toBe(200) + const { ws, next } = await open(relay.url) + ws.send(connectPacket(1, '127.0.0.1', echoPort)) + ws.send(packet(0x02, 1, Buffer.from('ping'))) + expect((await next((m) => m.type === 0x02 && m.stream === 1)).payload.toString()).toBe('ping') + expect(proxy.heads.at(-1)).toMatch(new RegExp(`^CONNECT 127\\.0\\.0\\.1:${echoPort} HTTP/1.1\r\n`)) + ws.close() + }) + }) }) diff --git a/toolchains/linux/build.sh b/toolchains/linux/build.sh index db3379f..1bae31c 100755 --- a/toolchains/linux/build.sh +++ b/toolchains/linux/build.sh @@ -28,6 +28,32 @@ ALPINE_VERSION=3.24.2 ALPINE_BRANCH=v3.24 MIRROR=${ALPINE_MIRROR:-https://dl-cdn.alpinelinux.org/alpine} +# Pinned here rather than read from the mirror, so a mirror can't hand out a +# different file along with its checksum. To update, for a new ALPINE_VERSION: +# curl -fsSL https://dl-cdn.alpinelinux.org/alpine/$ALPINE_BRANCH/releases/x86/alpine-minirootfs-$ALPINE_VERSION-x86.tar.gz.sha256 +# and for apk-tools-static (the branch keeps only its newest build, so this +# needs updating when the download below fails): the file name in +# https://dl-cdn.alpinelinux.org/alpine/$ALPINE_BRANCH/main//, +# then sha256sum of that .apk. +MINIROOTFS_SHA256=757f07c5a3476ba3947cfbea2323b7f02fb6fb2fba8a3a3c2b9d17f0a54c9226 +APK_TOOLS_VERSION=3.0.9-r0 +declare -A APK_TOOLS_SHA256=( + [x86_64]=0a1a0682375f66a83b7b903f6e4638ccfe312547d50d336b5f2be9fc391281be + [x86]=10a588ec557af8bfa7c6f82da013bab44f96fb7a4342e547f02ed1de800ab35c +) + +# apk checks package signatures, but the two files above run before it can, +# as root: only fetch them over plain HTTP if asked to. +case "$MIRROR" in + https://*) ;; + *) + if [ "${ALPINE_ALLOW_INSECURE_MIRROR:-}" != 1 ]; then + echo "ALPINE_MIRROR must be an https:// URL (set ALPINE_ALLOW_INSECURE_MIRROR=1 to use $MIRROR anyway)." >&2 + exit 1 + fi + ;; +esac + # What students get. Keep it focused: tools for learning the command line. PACKAGES=( bash bash-completion coreutils findutils grep sed gawk diffutils patch @@ -72,13 +98,21 @@ fi echo "==> Downloading Alpine $ALPINE_VERSION (x86)" tarball=alpine-minirootfs-$ALPINE_VERSION-x86.tar.gz curl -fsSL -o "$work/$tarball" "$MIRROR/$ALPINE_BRANCH/releases/x86/$tarball" -expected=$(curl -fsSL "$MIRROR/$ALPINE_BRANCH/releases/x86/$tarball.sha256" | cut -d' ' -f1) -echo "$expected $work/$tarball" | sha256sum -c - +echo "$MINIROOTFS_SHA256 $work/$tarball" | sha256sum -c - tar -xzf "$work/$tarball" -C "$rootfs" host_arch=$(uname -m) -apk_tools=$(curl -fsSL "$MIRROR/$ALPINE_BRANCH/main/$host_arch/" | grep -o 'apk-tools-static-[^"]*\.apk' | sort -V | tail -1) -curl -fsSL -o "$work/apk-tools.apk" "$MIRROR/$ALPINE_BRANCH/main/$host_arch/$apk_tools" +case "$host_arch" in i?86) host_arch=x86 ;; esac +if [ -z "${APK_TOOLS_SHA256[$host_arch]:-}" ]; then + echo "No pinned apk-tools-static for $host_arch (expected x86_64 or x86)." >&2 + exit 1 +fi +apk_tools=apk-tools-static-$APK_TOOLS_VERSION.apk +if ! curl -fsSL -o "$work/apk-tools.apk" "$MIRROR/$ALPINE_BRANCH/main/$host_arch/$apk_tools"; then + echo "Could not download $apk_tools: Alpine may have replaced it with a newer build. Update APK_TOOLS_VERSION and APK_TOOLS_SHA256 (see the top of this script)." >&2 + exit 1 +fi +echo "${APK_TOOLS_SHA256[$host_arch]} $work/apk-tools.apk" | sha256sum -c - tar -xzf "$work/apk-tools.apk" -C "$work" sbin/apk.static 2>/dev/null apk() { "$work/sbin/apk.static" --arch x86 --keys-dir "$rootfs/etc/apk/keys" \ diff --git a/toolchains/linux/fetch-images.mjs b/toolchains/linux/fetch-images.mjs index 5ebdad6..a4ef721 100644 --- a/toolchains/linux/fetch-images.mjs +++ b/toolchains/linux/fetch-images.mjs @@ -13,7 +13,7 @@ // anonymous users may download images). import { createHash } from 'node:crypto' -import { copyFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs' +import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { gunzipSync } from 'node:zlib' @@ -77,6 +77,42 @@ function tar(entries) { return Buffer.concat(blocks) } +// Reads back what tar() writes: archive path -> data. +function untar(archive) { + const files = new Map() + for (let at = 0; at + 512 <= archive.length; ) { + const header = archive.subarray(at, at + 512) + if (header.every((byte) => byte === 0)) break + const path = header.subarray(0, 100).toString().replace(/\0.*$/s, '') + const size = parseInt(header.subarray(124, 136).toString(), 8) + files.set(path, archive.subarray(at + 512, at + 512 + size)) + at += 512 + Math.ceil(size / 512) * 512 + } + return files +} + +// A cached archive is only used if it still matches the pinned digests: each +// image's manifest (kept next to the archive) has its pinned digest, and the +// config and layers in the archive have the checksums that manifest and +// config name. Anything else in the cache is ignored and fetched again. +function verifyCached(archive, manifests) { + const files = untar(archive) + const expected = [] + for (const { name, tag, digest } of IMAGES) { + const manifestBytes = Buffer.from(manifests[digest] ?? '', 'base64') + if (`sha256:${sha256(manifestBytes)}` !== digest) return false + const image = JSON.parse(manifestBytes) + const configPath = `${image.config.digest.slice('sha256:'.length)}.json` + const configBytes = files.get(configPath) + if (!configBytes || `sha256:${sha256(configBytes)}` !== image.config.digest) return false + const config = JSON.parse(configBytes) + const layers = config.rootfs.diff_ids.map((diffId) => `${diffId.slice('sha256:'.length)}.tar`) + for (const [i, path] of layers.entries()) if (!files.has(path) || `sha256:${sha256(files.get(path))}` !== config.rootfs.diff_ids[i]) return false + expected.push({ Config: configPath, RepoTags: [`${name}:${tag}`], Layers: layers }) + } + return files.get('manifest.json')?.toString() === JSON.stringify(expected) && files.size === new Set(expected.flatMap((item) => [item.Config, ...item.Layers])).size + 1 +} + if (process.argv[2] === '--latest') { for (const { name, tag } of IMAGES) { const repository = `library/${name}` @@ -96,19 +132,27 @@ if (!output) { const cacheDir = join(dirname(fileURLToPath(import.meta.url)), '../../node_modules/.cache/opcode-docker-images') const cached = join(cacheDir, `images-${sha256(JSON.stringify(IMAGES)).slice(0, 16)}.tar`) -if (existsSync(cached)) { - copyFileSync(cached, output) - console.log(` ${output}: from the cache`) - process.exit(0) +const cachedManifests = `${cached}.manifests.json` +if (existsSync(cached) && existsSync(cachedManifests)) { + try { + if (verifyCached(readFileSync(cached), JSON.parse(readFileSync(cachedManifests, 'utf8')))) { + copyFileSync(cached, output) + console.log(` ${output}: from the cache`) + process.exit(0) + } + } catch {} + console.log(' The cached images do not match their digests; downloading them again') } const files = new Map() // archive path -> data (layers shared between images are stored once) const manifest = [] +const manifests = {} // pinned digest -> manifest bytes (base64), to check the cache with for (const { name, tag, digest } of IMAGES) { const repository = `library/${name}` const auth = await token(repository) const manifestBytes = await get(repository, `manifests/${digest}`, auth) if (`sha256:${sha256(manifestBytes)}` !== digest) throw new Error(`Checksum mismatch for ${name}@${digest}`) + manifests[digest] = manifestBytes.toString('base64') const image = JSON.parse(manifestBytes) const configBytes = await blob(repository, image.config.digest, auth) const config = JSON.parse(configBytes) @@ -135,4 +179,5 @@ writeFileSync(output, archive) mkdirSync(cacheDir, { recursive: true }) writeFileSync(`${cached}.part`, archive) renameSync(`${cached}.part`, cached) +writeFileSync(cachedManifests, JSON.stringify(manifests)) console.log(` ${output}: ${(archive.length / 1e6).toFixed(1)} MB`) diff --git a/vercel.json b/vercel.json index 3de04dd..84c5ec8 100644 --- a/vercel.json +++ b/vercel.json @@ -4,7 +4,8 @@ "source": "/(.*)", "headers": [ { "key": "Cross-Origin-Opener-Policy", "value": "same-origin" }, - { "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" } + { "key": "Cross-Origin-Embedder-Policy", "value": "require-corp" }, + { "key": "Content-Security-Policy", "value": "frame-ancestors 'none'" } ] } ] From 9ca93be9d1b700d9fd82aa669966f98c6f916ed8 Mon Sep 17 00:00:00 2001 From: tks98 <70284059+tks98@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:29:15 -0600 Subject: [PATCH 2/2] CI: run on Ubuntu 24.04 ubuntu-latest is now Ubuntu 26.04, where Playwright 1.56 can't install Chromium ("Playwright does not support chromium on ubuntu26.04-x64"), so the end-to-end job failed before running a test. Pin the runner like the actions themselves; move it along with a Playwright update. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 8 ++++---- .github/workflows/pages.yml | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60272ec..4ea941c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ concurrency: jobs: check: name: Check, test and build - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: @@ -45,7 +45,7 @@ jobs: e2e: name: End-to-end (Chromium) needs: check - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 @@ -82,7 +82,7 @@ jobs: name: Docker image # Only a main whose tests pass is published as :latest, which compose.yaml pulls. needs: [check, e2e] - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 @@ -122,7 +122,7 @@ jobs: name: Publish the Docker image needs: [check, e2e, docker] if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: packages: write diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index a6df8f5..39d87f8 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -21,7 +21,7 @@ concurrency: jobs: build: name: Build - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 20 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 @@ -57,7 +57,7 @@ jobs: deploy: name: Deploy needs: build - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 permissions: pages: write id-token: write